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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
| // 批量处理标签
/**
* Zotero 批量标签处理脚本,适配 Actions and Tags 插件
* 功能:标签添加、删除、替换、拆分、合并、添加前缀/后缀、标签大小写格式化
* 特性:支持通配符搜索标签、自定义专业缩写大写、括号内文本弹窗确认大写、防重复执行、操作耗时日志记录
*/
const Zotero = require("Zotero");
const window = require("window");
(async function () {
const startTime = new Date();
// Prevent duplicate execution
if (window.batchTagRunning) return;
window.batchTagRunning = true;
// Store user responses for parentheses capitalization
const promptedValues = new Map();
// Custom capitalization dictionary
const customCapitalization = {
'nist': 'NIST',
'nerc': 'NERC',
// Add more custom capitalizations as needed
};
// Convert a string to title case based on specified rules
function toTitleCase(str, title, currentIndex, totalCount) {
const lowerCaseWords = ["a", "an", "and", "as", "at", "but", "by", "for", "if", "nor", "of", "on", "or", "so", "the", "to", "up", "yet"];
const separators = ['-', ':', '–', '/', '"', '“', '”'];
let words = str.split(' ');
for (let i = 0; i < words.length; i++) {
let word = words[i];
const lowerWord = word.toLowerCase();
// Handle custom capitalization
if (customCapitalization[lowerWord]) {
words[i] = customCapitalization[lowerWord];
continue;
}
// Capitalize the first and last word, words following a special character, and major words
if (i === 0 || i === words.length - 1 || !lowerCaseWords.includes(lowerWord) || isFollowingSpecialChar(words, i, separators) || word.length >= 4) {
words[i] = capitalizeHyphenatedAndSlashed(word);
} else {
words[i] = lowerWord;
}
}
// Ensure words following quotation marks are capitalized
for (let i = 0; i < words.length; i++) {
if (words[i].startsWith('"') && words[i].length > 1) {
words[i] = '"' + capitalizeFirstLetter(words[i].slice(1));
}
}
// Handle text within parentheses
return words.join(' ').replace(/$([^)]+)$/g, function (match, p1) {
const lowerP1 = p1.toLowerCase();
if (customCapitalization[lowerP1]) {
return `(${customCapitalization[lowerP1]})`;
}
if (promptedValues.has(lowerP1)) {
return `(${promptedValues.get(lowerP1)})`;
}
if (p1 !== p1.toUpperCase()) {
const userResponse = window.confirm(`是否要将标题"${title}"中的"${p1}"转换为大写?您的选择将应用于"${p1}"的所有后续出现。(提示 ${currentIndex}/${totalCount})`);
const userResponseValue = userResponse ? p1.toUpperCase() : p1;
promptedValues.set(lowerP1, userResponseValue);
return `(${userResponseValue})`;
}
return match;
});
}
// Capitalize both parts of a hyphenated or slashed word
function capitalizeHyphenatedAndSlashed(word) {
const separators = ['-', '/'];
return word.split(new RegExp(`(${separators.join('|')})`)).map(part => capitalizeFirstLetter(part)).join('');
}
// Capitalize the first letter of a word
function capitalizeFirstLetter(word) {
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}
// Check if the word follows a special character (-, :, –, /, ")
function isFollowingSpecialChar(arr, index, separators) {
if (index > 0) {
const prevWord = arr[index - 1];
return separators.some(separator => prevWord.endsWith(separator));
}
return false;
}
// Convert a string to sentence case
function toSentenceCase(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase().replace(/(\.\s*\w)/g, function (c) {
return c.toUpperCase();
});
}
// Convert a string to upper case
function toUpperCase(str) {
return str.toUpperCase();
}
// Convert a string to lower case
function toLowerCase(str) {
return str.toLowerCase();
}
// Escape special characters for use in regular expressions
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
// Get items to edit based on user selection using the Actions and Tags plugin environment
async function getItemsToEdit(triggerType, item, items) {
if (items && items.length > 0) {
// Return multiple items if selected
return items;
} else if (item) {
// Return single item if selected
return [item];
} else {
window.alert("未选择任何条目。");
return null;
}
}
// Get all unique tags from items
function getAllTags(items) {
const tagSet = new Set();
for (const item of items) {
const tags = item.getTags();
for (const tag of tags) {
tagSet.add(tag.tag);
}
}
return Array.from(tagSet);
}
// Function to search tags based on search term (with optional wildcard '*')
function searchTags(allTags, searchTerm) {
let regex;
if (searchTerm.includes('*')) {
regex = new RegExp(searchTerm.replace(/\*/g, '.*'), 'i'); // Replace all occurrences of '*' with '.*'
} else {
regex = new RegExp(escapeRegExp(searchTerm), 'i');
}
return allTags.filter(tag => regex.test(tag));
}
// Prompt user to select tags from search results
function selectTagsFromSearchResults(tags) {
if (tags.length === 0) {
window.alert("未找到匹配的标签。");
return null;
}
const choices = tags.map((tag, index) => `${index + 1}. ${tag}`).join("\n");
const choice = window.prompt(`通过逗号分隔的数字选择标签,或输入新的搜索词:\n\n${choices}`);
if (choice === null) {
window.alert("操作已取消。");
return null;
}
const selectedIndices = choice.split(',').map(str => parseInt(str.trim(), 10) - 1);
const selectedTags = selectedIndices.filter(index => !isNaN(index) && index >= 0 && index < tags.length).map(index => tags[index]);
if (selectedTags.length === 0) {
window.alert("未选择有效的标签。");
return null;
}
return selectedTags;
}
// Get valid input from the user based on predefined options
async function getValidInput(promptMessage, validOptions) {
while (true) {
const userInput = window.prompt(promptMessage);
const sanitizedInput = userInput ? userInput.trim() : null;
if (sanitizedInput === null) {
window.alert("操作已取消。");
return null;
}
if (validOptions.includes(sanitizedInput)) {
return sanitizedInput;
} else {
window.alert(`无效的选项:"${sanitizedInput}"。请输入以下选项之一:${validOptions.join(', ')}`);
}
}
}
// Perform tag operations (add, remove, replace, split, combine, prefix, suffix)
async function performTagOperation(operation, tags, items, newTags = [], delimiter = null) {
const promises = items.map(async item => {
try {
if (operation === 'add') {
item.addTag(tags[0]);
} else if (operation === 'remove') {
for (const tag of tags) {
item.removeTag(tag);
}
} else if (operation === 'removeAll') {
item.setTags([]);
} else if (operation === 'replace') {
for (const tag of tags) {
item.removeTag(tag);
}
item.addTag(newTags[0]);
} else if (operation === 'split') {
for (const tag of tags) {
const itemTags = item.getTags().map(t => t.tag);
if (itemTags.includes(tag)) {
item.removeTag(tag);
const splitTags = tag.split(delimiter).map(t => t.trim());
for (const newTag of splitTags) {
item.addTag(newTag);
}
}
}
} else if (operation === 'combine') {
for (const tag of tags) {
item.removeTag(tag);
}
for (const newTag of newTags) {
item.addTag(newTag);
}
} else if (operation === 'prefix' || operation === 'suffix') {
for (const tag of tags) {
item.removeTag(tag);
}
for (const newTag of newTags) {
item.addTag(newTag);
}
}
await item.saveTx();
} catch (error) {
Zotero.logError(`Error during ${operation} tag operation on item ${item.id}: ${error.message}`);
}
});
await Promise.all(promises);
window.alert(`标签操作"${operation}"已完成,处理了 ${items.length} 个条目。`);
}
// Apply case conversion to tags
async function performTagCaseOperation(caseFunction, items) {
const allTags = getAllTags(items);
const tagMap = new Map();
for (let tag of allTags) {
const newTag = caseFunction(tag, allTags.indexOf(tag) + 1, allTags.length);
tagMap.set(tag, newTag);
}
const promises = items.map(async item => {
const tags = item.getTags();
const newTags = tags.map(t => {
return { tag: tagMap.get(t.tag) || t.tag };
});
item.setTags(newTags);
await item.saveTx();
});
await Promise.all(promises);
window.alert(`已为 ${items.length} 个条目更新标签。`);
}
// Log the elapsed time for a given operation
function logTime(label, time) {
try {
Zotero.logError(`${label}: ${(time / 1000).toFixed(2)} seconds`);
} catch (error) {
Zotero.logError(`Failed to log time for ${label}: ${error.message}`);
}
}
// Select a base tag from search results
async function selectBaseTag(allTags) {
let baseTagChoices = searchTags(allTags, window.prompt("输入基础标签的搜索词:"));
baseTagChoices = baseTagChoices.map((tag, index) => `${index + 1}. ${tag}`).join("\n");
const baseTagChoice = window.prompt(`通过数字选择基础标签或输入新的搜索词:\n\n${baseTagChoices}`);
if (baseTagChoice === null) {
window.alert("操作已取消。");
return null;
}
const baseTagIndex = parseInt(baseTagChoice.trim(), 10) - 1;
if (isNaN(baseTagIndex) || baseTagIndex < 0 || baseTagIndex >= baseTagChoices.length) {
window.alert("无效的选择。");
return null;
}
return baseTagChoices.split("\n")[baseTagIndex].split(". ")[1];
}
// Search and select tags from search results
async function searchAndSelectTags(allTags) {
const searchTerm = window.prompt("输入要搜索的正则表达式或标签:");
const matchingTags = searchTags(allTags, searchTerm);
if (matchingTags.length === 0) {
window.alert("未找到匹配的标签。");
return null;
}
return matchingTags;
}
try {
// Ensure items and item are provided
if (!items && !item) {
window.alert("批量标签操作", "未提供条目或条目数组。");
window.batchTagRunning = false;
return;
}
// Get items to edit based on user selection
let itemsToEdit = await getItemsToEdit(triggerType, item, items);
if (!itemsToEdit) {
window.batchTagRunning = false;
return;
}
Zotero.logError(`Total items to edit: ${itemsToEdit.length}`);
// Get the action to perform from the user
const action = await getValidInput(
`选择操作:
1. 添加标签
2. 删除标签(多个选项)
3. 替换标签
4. 拆分标签
5. 合并标签
6. 对标签应用大小写转换
7. 为标签添加前缀或后缀`,
['1', '2', '3', '4', '5', '6', '7']
);
let searchTerm, matchingTags, selectedTags, newTag, delimiter;
switch (action) {
case '1':
const tagToAdd = window.prompt("输入要添加的标签:");
if (tagToAdd) await performTagOperation('add', [tagToAdd], itemsToEdit);
else window.alert("未输入标签。");
break;
case '2':
const removeAction = await getValidInput(
`选择删除选项:
1. 删除单个标签
2. 通过搜索删除多个标签
3. 删除所有标签
4. 删除除指定标签外的所有标签`,
['1', '2', '3', '4']
);
switch (removeAction) {
case '1':
searchTerm = window.prompt("输入要搜索的标签:");
matchingTags = searchTags(getAllTags(itemsToEdit), searchTerm);
selectedTags = selectTagsFromSearchResults(matchingTags);
if (selectedTags) await performTagOperation('remove', selectedTags, itemsToEdit);
break;
case '2':
searchTerm = window.prompt("输入标签搜索词(例如 'temp*' 匹配 'temp'、'temporary' 等):");
matchingTags = searchTags(getAllTags(itemsToEdit), searchTerm);
selectedTags = selectTagsFromSearchResults(matchingTags);
if (selectedTags) await performTagOperation('remove', selectedTags, itemsToEdit);
break;
case '3':
await performTagOperation('removeAll', [], itemsToEdit);
break;
case '4':
searchTerm = window.prompt("输入要保留的标签搜索词(例如 'temp*' 匹配 'temp'、'temporary' 等):");
matchingTags = searchTags(getAllTags(itemsToEdit), searchTerm);
selectedTags = selectTagsFromSearchResults(matchingTags);
if (selectedTags) {
const tagsToKeep = new Set(selectedTags);
await performTagOperation('remove', getAllTags(itemsToEdit).filter(tag => !tagsToKeep.has(tag)), itemsToEdit);
}
break;
}
break;
case '3':
searchTerm = window.prompt("输入要搜索的标签(用逗号分隔):");
matchingTags = searchTags(getAllTags(itemsToEdit), searchTerm);
selectedTags = selectTagsFromSearchResults(matchingTags);
if (selectedTags) {
newTag = window.prompt("输入新标签:");
if (newTag) await performTagOperation('replace', selectedTags, itemsToEdit, [newTag]);
else window.alert("未输入新标签。");
}
break;
case '4':
const splitAction = await getValidInput(
`选择拆分选项:
1. 拆分单个标签
2. 按指定分隔符拆分所有标签`,
['1', '2']
);
if (splitAction === '1') {
searchTerm = window.prompt("输入要搜索的标签:");
matchingTags = searchTags(getAllTags(itemsToEdit), searchTerm);
selectedTags = selectTagsFromSearchResults(matchingTags);
if (selectedTags) {
delimiter = window.prompt("输入拆分标签的分隔符:");
if (delimiter) await performTagOperation('split', selectedTags, itemsToEdit, null, delimiter);
else window.alert("未输入分隔符。");
}
} else if (splitAction === '2') {
delimiter = window.prompt("输入拆分所有标签的分隔符:");
if (delimiter) await performTagOperation('split', getAllTags(itemsToEdit), itemsToEdit, null, delimiter);
else window.alert("未输入分隔符。");
}
break;
case '5':
const allTags = getAllTags(itemsToEdit);
const baseTag = await selectBaseTag(allTags);
if (baseTag) {
delimiter = window.prompt("输入连接标签的分隔符(可选):");
const tagToCombineRegex = window.prompt("输入要合并的正则表达式或标签:");
if (tagToCombineRegex !== null) {
const tagsToCombine = searchTags(allTags, tagToCombineRegex);
if (tagsToCombine.length > 0) {
const newTags = tagsToCombine.map(tag => `${baseTag}${delimiter || ''}${tag}`);
await performTagOperation('combine', tagsToCombine.concat(baseTag), itemsToEdit, newTags);
} else {
window.alert(`未找到匹配模式"${tagToCombineRegex}"的标签。`);
}
} else {
window.alert("正则表达式输入无效。");
}
}
break;
case '6':
const caseOption = await getValidInput(
"输入 '1' 选择标题大小写,'2' 选择句子大小写,'3' 选择全大写,'4' 选择全小写:",
['1', '2', '3', '4']
);
let caseFunction;
switch (caseOption) {
case '1':
caseFunction = (str, currentIndex, totalCount) => toTitleCase(str, str, currentIndex, totalCount);
break;
case '2':
caseFunction = toSentenceCase;
break;
case '3':
caseFunction = toUpperCase;
break;
case '4':
caseFunction = toLowerCase;
break;
}
await performTagCaseOperation(caseFunction, itemsToEdit);
break;
case '7':
const prefixOrSuffix = await getValidInput(
"输入 '1' 添加前缀,或 '2' 添加后缀:",
['1', '2']
);
newTag = window.prompt(`输入要添加的${prefixOrSuffix === '1' ? '前缀' : '后缀'}:`);
if (!newTag) {
window.alert("未输入前缀或后缀。");
break;
}
matchingTags = await searchAndSelectTags(getAllTags(itemsToEdit));
if (matchingTags) {
const newTags = matchingTags.map(tag =>
prefixOrSuffix === '1' ? `${newTag}${tag}` : `${tag}${newTag}`
);
await performTagOperation(prefixOrSuffix === '1' ? 'prefix' : 'suffix', matchingTags, itemsToEdit, newTags);
} else {
window.alert("未找到匹配模式的标签。");
}
break;
default:
window.alert("无效的操作。");
break;
}
} catch (error) {
Zotero.logError(`批量标签脚本错误: ${error.message}`);
window.alert(`发生错误: ${error.message}`);
} finally {
window.batchTagRunning = false;
const endTime = new Date();
logTime("Total time", endTime - startTime);
}
})();
|