lucgumshoe

Quote Normalization Script for Google Docs (Straight To Curly Quotes)

Jan 28th, 2026
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 9.61 KB | Writing | 0 0
  1. function onOpen() {
  2.   DocumentApp.getUi()
  3.     .createMenu('Chapter Tools')
  4.     .addItem('Quote Normalization', 'quoteNormalization')
  5.     .addItem('Find Straight Quotes', 'findStraightQuotes')
  6.     .addToUi();
  7. }
  8.  
  9. function quoteNormalization() {
  10.   const ui = DocumentApp.getUi();
  11.   const doc = DocumentApp.getActiveDocument();
  12.   const body = doc.getBody();
  13.   const paragraphs = body.getParagraphs();
  14.  
  15.   const STRAIGHT_DOUBLE = '"';
  16.   const CURLY_DOUBLE_OPEN = '\u201C';
  17.   const CURLY_DOUBLE_CLOSE = '\u201D';
  18.  
  19.   const STRAIGHT_SINGLE = "'";
  20.   const CURLY_SINGLE_CLOSE = '\u2019';
  21.  
  22.   const CONTRACTIONS = [
  23.     "who's", "who'd", "could've", "she'll", "didn't", "wouldn't", "couldn't",
  24.     "shouldn't", "how's", "she'd", "let's", "hasn't", "you'll", "won't",
  25.     "should've", "she's", "would've", "it'd", "that's", "it'll", "how'd",
  26.     "they'll", "hadn't", "must've", "we'll", "don't", "there'll", "when's",
  27.     "i'm", "why'd", "you'd", "aren't", "wasn't", "i'd", "that'll", "we've",
  28.     "haven't", "you're", "it's", "ain't", "they'd", "they're", "we're",
  29.     "weren't", "you've", "i'll", "there's", "doesn't", "isn't", "i've",
  30.     "we'd", "what's", "can't", "something's", "someone's", "everyone's",
  31.     "food'll", "he's", "'em", "y'all", "ma'am", "'cause", "'til", "o'clock"
  32.   ];
  33.  
  34.   const PROPER_POSSESSIVES = [
  35.     "leah's", "ava's", "kaylee's", "olivia's", "paul's", "jake's", "ethan's",
  36.     "laura's", "dean's", "jenny's", "melanie's", "zoe's", "albrecht's",
  37.     "tucker's", "natalie's", "monday's", "yardley's"
  38.   ];
  39.  
  40.   const COMMON_POSSESSIVES = [
  41.     "father's", "driver's", "dog's", "girl's", "roommate's", "water's",
  42.     "semester's", "student's", "mom's", "professor's", "car's", "mother's",
  43.     "mp3's", "people's", "troll's", "pig's", "trailer's", "drink's",
  44.     "women's", "lover's", "grandma's", "table's", "woman's", "lion's",
  45.     "fuck's", "reeves'"
  46.   ];
  47.  
  48.   const KNOWN_APOSTROPHE_WORDS = new Set([
  49.     ...CONTRACTIONS,
  50.     ...PROPER_POSSESSIVES,
  51.     ...COMMON_POSSESSIVES
  52.   ]);
  53.  
  54.   const warnings = [];
  55.   const errors = [];
  56.   let totalDoubleQuotesFixed = 0;
  57.   let totalSingleQuotesFixed = 0;
  58.   let paragraphsModified = 0;
  59.  
  60.   for (let i = 0; i < paragraphs.length; i++) {
  61.     const p = paragraphs[i];
  62.     const originalText = p.getText();
  63.  
  64.     if (!originalText.trim()) continue;
  65.  
  66.     const doubleQuoteCount = (originalText.match(/"/g) || []).length;
  67.     const singleQuoteCount = (originalText.match(/'/g) || []).length;
  68.  
  69.     if (doubleQuoteCount === 0 && singleQuoteCount === 0) continue;
  70.  
  71.     let newText = originalText;
  72.  
  73.     // Double quote processing
  74.     if (doubleQuoteCount > 0) {
  75.       if (doubleQuoteCount % 2 !== 0) {
  76.         warnings.push(
  77.           `Line ${i + 1}: odd number of straight double quotes (${doubleQuoteCount}), skipping: "${originalText.substring(0, 60)}${originalText.length > 60 ? '...' : ''}"`
  78.         );
  79.       } else {
  80.         let quoteIndex = 0;
  81.         newText = newText.replace(/"/g, () => {
  82.           const replacement = (quoteIndex % 2 === 0) ? CURLY_DOUBLE_OPEN : CURLY_DOUBLE_CLOSE;
  83.           quoteIndex++;
  84.           return replacement;
  85.         });
  86.         totalDoubleQuotesFixed += doubleQuoteCount;
  87.       }
  88.     }
  89.  
  90.     // Single quote processing
  91.     if (singleQuoteCount > 0) {
  92.       let unresolvedSingleQuotes = 0;
  93.       let result = '';
  94.       let pos = 0;
  95.  
  96.       while (pos < newText.length) {
  97.         if (newText.charAt(pos) === "'") {
  98.           let matched = false;
  99.  
  100.           for (const word of KNOWN_APOSTROPHE_WORDS) {
  101.             const apostropheIndexInWord = word.indexOf("'");
  102.             if (apostropheIndexInWord === -1) continue;
  103.  
  104.             const wordStart = pos - apostropheIndexInWord;
  105.             if (wordStart < 0) continue;
  106.  
  107.             const wordEnd = wordStart + word.length;
  108.             if (wordEnd > newText.length) continue;
  109.  
  110.             const candidate = newText.substring(wordStart, wordEnd).toLowerCase();
  111.  
  112.             if (candidate === word) {
  113.               const charBefore = wordStart > 0 ? newText.charAt(wordStart - 1) : ' ';
  114.               const charAfter = wordEnd < newText.length ? newText.charAt(wordEnd) : ' ';
  115.  
  116.               const validBoundaryBefore = /[\s\n\r\u201C\u201D\(\[\{]/.test(charBefore) || wordStart === 0;
  117.               const validBoundaryAfter = /[\s\n\r,.\!\?\;\:\u201C\u201D\)\]\}]/.test(charAfter) || wordEnd === newText.length;
  118.  
  119.               if (validBoundaryBefore && validBoundaryAfter) {
  120.                 result += CURLY_SINGLE_CLOSE;
  121.                 matched = true;
  122.                 totalSingleQuotesFixed++;
  123.                 break;
  124.               }
  125.             }
  126.           }
  127.  
  128.           if (!matched) {
  129.             unresolvedSingleQuotes++;
  130.             result += "'";
  131.           }
  132.  
  133.           pos++;
  134.         } else {
  135.           result += newText.charAt(pos);
  136.           pos++;
  137.         }
  138.       }
  139.  
  140.       newText = result;
  141.  
  142.       if (unresolvedSingleQuotes > 0) {
  143.         warnings.push(
  144.           `Line ${i + 1}: ${unresolvedSingleQuotes} unresolved straight single quote(s), needs manual review: "${originalText.substring(0, 60)}${originalText.length > 60 ? '...' : ''}"`
  145.         );
  146.       }
  147.     }
  148.  
  149.     // Apply changes
  150.     if (newText !== originalText) {
  151.       const validationResult = paranoidReplacement(p, newText);
  152.  
  153.       if (!validationResult.success) {
  154.         errors.push(
  155.           `Line ${i + 1}: paranoid replacement BLOCKED change: ${validationResult.error}`
  156.         );
  157.       } else {
  158.         paragraphsModified++;
  159.       }
  160.     }
  161.   }
  162.  
  163.   // Report results
  164.   if (errors.length > 0) {
  165.     const msg =
  166.       'Quote Normalization encountered ERRORS (some changes were blocked):\n\n' +
  167.       errors.join('\n') +
  168.       (warnings.length > 0 ? '\n\nWarnings:\n' + warnings.join('\n') : '');
  169.     ui.alert('Quote Normalization – Errors', msg, ui.ButtonSet.OK);
  170.     return;
  171.   }
  172.  
  173.   if (totalDoubleQuotesFixed === 0 && totalSingleQuotesFixed === 0 && warnings.length === 0) {
  174.     ui.alert('Quote Normalization', 'No straight quotes found. Document is clean!', ui.ButtonSet.OK);
  175.     return;
  176.   }
  177.  
  178.   let summaryParts = [];
  179.   if (paragraphsModified > 0) {
  180.     summaryParts.push(`Modified ${paragraphsModified} paragraph(s)`);
  181.   }
  182.   if (totalDoubleQuotesFixed > 0) {
  183.     summaryParts.push(`Fixed ${totalDoubleQuotesFixed} double quote(s)`);
  184.   }
  185.   if (totalSingleQuotesFixed > 0) {
  186.     summaryParts.push(`Fixed ${totalSingleQuotesFixed} single quote(s)`);
  187.   }
  188.  
  189.   if (warnings.length > 0) {
  190.     const msg =
  191.       summaryParts.join('\n') +
  192.       '\n\nWarnings (require manual review):\n\n' +
  193.       warnings.join('\n');
  194.     ui.alert('Quote Normalization – Completed with Warnings', msg, ui.ButtonSet.OK);
  195.   } else {
  196.     ui.alert('Quote Normalization', summaryParts.join('\n') + '\n\nAll quotes normalized successfully!', ui.ButtonSet.OK);
  197.   }
  198. }
  199.  
  200. /**
  201.  * Replaces paragraph text only if changes are limited to straight-to-curly quote conversions.
  202.  * Preserves all formatting by replacing character-by-character.
  203.  */
  204. function paranoidReplacement(paragraph, newText) {
  205.   const oldText = paragraph.getText();
  206.  
  207.   if (oldText.length !== newText.length) {
  208.     return {
  209.       success: false,
  210.       error: `Length mismatch: original is ${oldText.length} chars, replacement is ${newText.length} chars`
  211.     };
  212.   }
  213.  
  214.   const STRAIGHT_DOUBLE = '"';
  215.   const CURLY_DOUBLE_OPEN = '\u201C';
  216.   const CURLY_DOUBLE_CLOSE = '\u201D';
  217.  
  218.   const STRAIGHT_SINGLE = "'";
  219.   const CURLY_SINGLE_OPEN = '\u2018';
  220.   const CURLY_SINGLE_CLOSE = '\u2019';
  221.  
  222.   const replacements = [];
  223.  
  224.   for (let i = 0; i < oldText.length; i++) {
  225.     const oldChar = oldText.charAt(i);
  226.     const newChar = newText.charAt(i);
  227.  
  228.     if (oldChar === newChar) continue;
  229.  
  230.     if (oldChar === STRAIGHT_DOUBLE &&
  231.         (newChar === CURLY_DOUBLE_OPEN || newChar === CURLY_DOUBLE_CLOSE)) {
  232.       replacements.push({ index: i, oldChar, newChar });
  233.       continue;
  234.     }
  235.  
  236.     if (oldChar === STRAIGHT_SINGLE &&
  237.         (newChar === CURLY_SINGLE_OPEN || newChar === CURLY_SINGLE_CLOSE)) {
  238.       replacements.push({ index: i, oldChar, newChar });
  239.       continue;
  240.     }
  241.  
  242.     return {
  243.       success: false,
  244.       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')})`
  245.     };
  246.   }
  247.  
  248.   const textElement = paragraph.editAsText();
  249.  
  250.   for (let i = replacements.length - 1; i >= 0; i--) {
  251.     const r = replacements[i];
  252.     textElement.deleteText(r.index, r.index);
  253.     textElement.insertText(r.index, r.newChar);
  254.   }
  255.  
  256.   return { success: true, error: null };
  257. }
  258.  
  259. function findStraightQuotes() {
  260.   const ui = DocumentApp.getUi();
  261.   const doc = DocumentApp.getActiveDocument();
  262.   const body = doc.getBody();
  263.   const paragraphs = body.getParagraphs();
  264.  
  265.   const results = [];
  266.  
  267.   for (let i = 0; i < paragraphs.length; i++) {
  268.     const text = paragraphs[i].getText();
  269.     const straightDouble = (text.match(/"/g) || []).length;
  270.     const straightSingle = (text.match(/'/g) || []).length;
  271.  
  272.     if (straightDouble > 0 || straightSingle > 0) {
  273.       results.push(`Line ${i + 1}: ${straightDouble}" ${straightSingle}' → "${text.substring(0, 50)}..."`);
  274.    }
  275.  }
  276.  
  277.  if (results.length === 0) {
  278.    ui.alert('Find Straight Quotes', 'No straight quotes found!', ui.ButtonSet.OK);
  279.  } else {
  280.    const msg = `Found ${results.length} paragraphs with straight quotes:\n\n` +
  281.                results.slice(0, 20).join('\n') +
  282.                (results.length > 20 ? `\n\n...and ${results.length - 20} more` : '');
  283.    ui.alert('Find Straight Quotes', msg, ui.ButtonSet.OK);
  284.  }
  285. }
Add Comment
Please, Sign In to add comment