Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function onOpen() {
- DocumentApp.getUi()
- .createMenu('Chapter Tools')
- .addItem('Quote Normalization', 'quoteNormalization')
- .addItem('Find Straight Quotes', 'findStraightQuotes')
- .addToUi();
- }
- function quoteNormalization() {
- const ui = DocumentApp.getUi();
- const doc = DocumentApp.getActiveDocument();
- const body = doc.getBody();
- const paragraphs = body.getParagraphs();
- const STRAIGHT_DOUBLE = '"';
- const CURLY_DOUBLE_OPEN = '\u201C';
- const CURLY_DOUBLE_CLOSE = '\u201D';
- const STRAIGHT_SINGLE = "'";
- const CURLY_SINGLE_CLOSE = '\u2019';
- const CONTRACTIONS = [
- "who's", "who'd", "could've", "she'll", "didn't", "wouldn't", "couldn't",
- "shouldn't", "how's", "she'd", "let's", "hasn't", "you'll", "won't",
- "should've", "she's", "would've", "it'd", "that's", "it'll", "how'd",
- "they'll", "hadn't", "must've", "we'll", "don't", "there'll", "when's",
- "i'm", "why'd", "you'd", "aren't", "wasn't", "i'd", "that'll", "we've",
- "haven't", "you're", "it's", "ain't", "they'd", "they're", "we're",
- "weren't", "you've", "i'll", "there's", "doesn't", "isn't", "i've",
- "we'd", "what's", "can't", "something's", "someone's", "everyone's",
- "food'll", "he's", "'em", "y'all", "ma'am", "'cause", "'til", "o'clock"
- ];
- const PROPER_POSSESSIVES = [
- "leah's", "ava's", "kaylee's", "olivia's", "paul's", "jake's", "ethan's",
- "laura's", "dean's", "jenny's", "melanie's", "zoe's", "albrecht's",
- "tucker's", "natalie's", "monday's", "yardley's"
- ];
- const COMMON_POSSESSIVES = [
- "father's", "driver's", "dog's", "girl's", "roommate's", "water's",
- "semester's", "student's", "mom's", "professor's", "car's", "mother's",
- "mp3's", "people's", "troll's", "pig's", "trailer's", "drink's",
- "women's", "lover's", "grandma's", "table's", "woman's", "lion's",
- "fuck's", "reeves'"
- ];
- const KNOWN_APOSTROPHE_WORDS = new Set([
- ...CONTRACTIONS,
- ...PROPER_POSSESSIVES,
- ...COMMON_POSSESSIVES
- ]);
- const warnings = [];
- const errors = [];
- let totalDoubleQuotesFixed = 0;
- let totalSingleQuotesFixed = 0;
- let paragraphsModified = 0;
- for (let i = 0; i < paragraphs.length; i++) {
- const p = paragraphs[i];
- const originalText = p.getText();
- if (!originalText.trim()) continue;
- const doubleQuoteCount = (originalText.match(/"/g) || []).length;
- const singleQuoteCount = (originalText.match(/'/g) || []).length;
- if (doubleQuoteCount === 0 && singleQuoteCount === 0) continue;
- let newText = originalText;
- // Double quote processing
- if (doubleQuoteCount > 0) {
- if (doubleQuoteCount % 2 !== 0) {
- warnings.push(
- `Line ${i + 1}: odd number of straight double quotes (${doubleQuoteCount}), skipping: "${originalText.substring(0, 60)}${originalText.length > 60 ? '...' : ''}"`
- );
- } else {
- let quoteIndex = 0;
- newText = newText.replace(/"/g, () => {
- const replacement = (quoteIndex % 2 === 0) ? CURLY_DOUBLE_OPEN : CURLY_DOUBLE_CLOSE;
- quoteIndex++;
- return replacement;
- });
- totalDoubleQuotesFixed += doubleQuoteCount;
- }
- }
- // Single quote processing
- if (singleQuoteCount > 0) {
- let unresolvedSingleQuotes = 0;
- let result = '';
- let pos = 0;
- while (pos < newText.length) {
- if (newText.charAt(pos) === "'") {
- let matched = false;
- for (const word of KNOWN_APOSTROPHE_WORDS) {
- const apostropheIndexInWord = word.indexOf("'");
- if (apostropheIndexInWord === -1) continue;
- const wordStart = pos - apostropheIndexInWord;
- if (wordStart < 0) continue;
- const wordEnd = wordStart + word.length;
- if (wordEnd > newText.length) continue;
- const candidate = newText.substring(wordStart, wordEnd).toLowerCase();
- if (candidate === word) {
- const charBefore = wordStart > 0 ? newText.charAt(wordStart - 1) : ' ';
- const charAfter = wordEnd < newText.length ? newText.charAt(wordEnd) : ' ';
- const validBoundaryBefore = /[\s\n\r\u201C\u201D\(\[\{]/.test(charBefore) || wordStart === 0;
- const validBoundaryAfter = /[\s\n\r,.\!\?\;\:\u201C\u201D\)\]\}]/.test(charAfter) || wordEnd === newText.length;
- if (validBoundaryBefore && validBoundaryAfter) {
- result += CURLY_SINGLE_CLOSE;
- matched = true;
- totalSingleQuotesFixed++;
- break;
- }
- }
- }
- if (!matched) {
- unresolvedSingleQuotes++;
- result += "'";
- }
- pos++;
- } else {
- result += newText.charAt(pos);
- pos++;
- }
- }
- newText = result;
- if (unresolvedSingleQuotes > 0) {
- warnings.push(
- `Line ${i + 1}: ${unresolvedSingleQuotes} unresolved straight single quote(s), needs manual review: "${originalText.substring(0, 60)}${originalText.length > 60 ? '...' : ''}"`
- );
- }
- }
- // Apply changes
- if (newText !== originalText) {
- const validationResult = paranoidReplacement(p, newText);
- if (!validationResult.success) {
- errors.push(
- `Line ${i + 1}: paranoid replacement BLOCKED change: ${validationResult.error}`
- );
- } else {
- paragraphsModified++;
- }
- }
- }
- // Report results
- if (errors.length > 0) {
- const msg =
- 'Quote Normalization encountered ERRORS (some changes were blocked):\n\n' +
- errors.join('\n') +
- (warnings.length > 0 ? '\n\nWarnings:\n' + warnings.join('\n') : '');
- ui.alert('Quote Normalization – Errors', msg, ui.ButtonSet.OK);
- return;
- }
- if (totalDoubleQuotesFixed === 0 && totalSingleQuotesFixed === 0 && warnings.length === 0) {
- ui.alert('Quote Normalization', 'No straight quotes found. Document is clean!', ui.ButtonSet.OK);
- return;
- }
- let summaryParts = [];
- if (paragraphsModified > 0) {
- summaryParts.push(`Modified ${paragraphsModified} paragraph(s)`);
- }
- if (totalDoubleQuotesFixed > 0) {
- summaryParts.push(`Fixed ${totalDoubleQuotesFixed} double quote(s)`);
- }
- if (totalSingleQuotesFixed > 0) {
- summaryParts.push(`Fixed ${totalSingleQuotesFixed} single quote(s)`);
- }
- if (warnings.length > 0) {
- const msg =
- summaryParts.join('\n') +
- '\n\nWarnings (require manual review):\n\n' +
- warnings.join('\n');
- ui.alert('Quote Normalization – Completed with Warnings', msg, ui.ButtonSet.OK);
- } else {
- ui.alert('Quote Normalization', summaryParts.join('\n') + '\n\nAll quotes normalized successfully!', ui.ButtonSet.OK);
- }
- }
- /**
- * Replaces paragraph text only if changes are limited to straight-to-curly quote conversions.
- * Preserves all formatting by replacing character-by-character.
- */
- function paranoidReplacement(paragraph, newText) {
- const oldText = paragraph.getText();
- if (oldText.length !== newText.length) {
- return {
- success: false,
- error: `Length mismatch: original is ${oldText.length} chars, replacement is ${newText.length} chars`
- };
- }
- const STRAIGHT_DOUBLE = '"';
- const CURLY_DOUBLE_OPEN = '\u201C';
- const CURLY_DOUBLE_CLOSE = '\u201D';
- const STRAIGHT_SINGLE = "'";
- const CURLY_SINGLE_OPEN = '\u2018';
- const CURLY_SINGLE_CLOSE = '\u2019';
- const replacements = [];
- for (let i = 0; i < oldText.length; i++) {
- const oldChar = oldText.charAt(i);
- const newChar = newText.charAt(i);
- if (oldChar === newChar) continue;
- if (oldChar === STRAIGHT_DOUBLE &&
- (newChar === CURLY_DOUBLE_OPEN || newChar === CURLY_DOUBLE_CLOSE)) {
- replacements.push({ index: i, oldChar, newChar });
- continue;
- }
- if (oldChar === STRAIGHT_SINGLE &&
- (newChar === CURLY_SINGLE_OPEN || newChar === CURLY_SINGLE_CLOSE)) {
- replacements.push({ index: i, oldChar, newChar });
- continue;
- }
- return {
- success: false,
- error: `Forbidden character change at position ${i}: "${oldChar}" (U+${oldChar.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0')}) -> "${newChar}" (U+${newChar.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0')})`
- };
- }
- const textElement = paragraph.editAsText();
- for (let i = replacements.length - 1; i >= 0; i--) {
- const r = replacements[i];
- textElement.deleteText(r.index, r.index);
- textElement.insertText(r.index, r.newChar);
- }
- return { success: true, error: null };
- }
- function findStraightQuotes() {
- const ui = DocumentApp.getUi();
- const doc = DocumentApp.getActiveDocument();
- const body = doc.getBody();
- const paragraphs = body.getParagraphs();
- const results = [];
- for (let i = 0; i < paragraphs.length; i++) {
- const text = paragraphs[i].getText();
- const straightDouble = (text.match(/"/g) || []).length;
- const straightSingle = (text.match(/'/g) || []).length;
- if (straightDouble > 0 || straightSingle > 0) {
- results.push(`Line ${i + 1}: ${straightDouble}" ${straightSingle}' → "${text.substring(0, 50)}..."`);
- }
- }
- if (results.length === 0) {
- ui.alert('Find Straight Quotes', 'No straight quotes found!', ui.ButtonSet.OK);
- } else {
- const msg = `Found ${results.length} paragraphs with straight quotes:\n\n` +
- results.slice(0, 20).join('\n') +
- (results.length > 20 ? `\n\n...and ${results.length - 20} more` : '');
- ui.alert('Find Straight Quotes', msg, ui.ButtonSet.OK);
- }
- }
Add Comment
Please, Sign In to add comment