Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash· GoogleHugging Face LMArena Human Preference 140K

Create a Google Apps Script that automates the conversion of a structured Google Doc…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Mistralmistral-medium-2505’s answer.
  1. User

    Create a Google Apps Script that automates the conversion of a structured Google Doc (containing questions and answers) into a Google Form. The script should:

    Input Requirements:

    Assume the Google Doc has a clear structure (e.g., questions as headings, answers as bulleted/numbered lists).

    Specify if the format supports multiple-choice, text, paragraph, or other question types (or detect them dynamically).

    Functionality:

    Parse the Google Doc to extract questions and answer options (if applicable).

    Create a new Google Form or update an existing one.

    Map the Doc’s structure to Form fields (e.g., headings → questions, bullet points → multiple-choice options).

    Handle edge cases (e.g., empty lines, irregular formatting).

    Output:

    Return the URL of the generated Google Form.

    Log errors or mismatched formatting for review.

    Optional Enhancements:

    Add a menu item in Google Docs to trigger the script manually.

    Support batch processing (multiple Docs → multiple Forms).

    Allow user customization (e.g., form title, question type overrides).

    Provide code comments for key steps and error handling."*

  2. Gemini Assistant

    This Google Apps Script will automate the conversion of a structured Google Doc into a Google Form. It assumes a specific structure for the Google Doc to effectively parse questions and answers.

    Assumed Google Doc Structure:

    • Questions: Treated as standalone paragraphs. The script will consider a paragraph a question if it's not part of a bulleted/numbered list and appears after any previous question's options have been processed.
    • Multiple-Choice Options: Bulleted or numbered list items immediately following a question.
    • Text/Paragraph Answers: A question that is not followed by any bulleted/numbered list items will be converted into a "Paragraph" type question in the Google Form.

    Google Apps Script Code

    To use this script:

    1. Open the Google Doc you want to convert.
    2. Go to Extensions > Apps Script.
    3. Delete any existing code in Code.gs.
    4. Copy and paste the entire code below into the script editor.
    5. Save the project (click the floppy disk icon or Ctrl/Cmd + S). You might be prompted to give the project a name.
    6. Go back to your Google Doc. Refresh the page if the "Convert to Form" menu doesn't appear immediately.
    7. A new menu item "Convert to Form" should appear. Click it, then select "Convert Document".
    8. The first time you run it, Google will ask for authorization. Follow the prompts to grant the necessary permissions (to view and manage your Google Docs and Forms).
    /**
     * @fileoverview Google Apps Script to convert a structured Google Doc into a Google Form.
     * This script is designed to be bound to a Google Doc.
     */
    
    /**
     * Adds a custom menu to the Google Doc UI when the document is opened.
     * This allows the user to trigger the form conversion manually.
     */
    function onOpen() {
      const ui = DocumentApp.getUi();
      ui.createMenu('Convert to Form')
          .addItem('Convert Document', 'convertToForm')
          .addToUi();
    }
    
    /**
     * Main function to parse the Google Doc and create a Google Form.
     * It detects questions (paragraphs) and their corresponding options (list items).
     *
     * @returns {string} The URL of the newly created Google Form.
     */
    function convertToForm() {
      const doc = DocumentApp.getActiveDocument();
      const body = doc.getBody();
      const ui = DocumentApp.getUi();
    
      // --- User Customization / Form Title ---
      let formTitle = doc.getName(); // Default form title is the document name
      try {
        const response = ui.prompt(
          'Form Title',
          'Enter the title for your new Google Form:',
          ui.ButtonSet.OK_CANCEL
        );
        if (response.getSelectedButton() === ui.Button.OK && response.getResponseText()) {
          formTitle = response.getResponseText().trim();
        } else if (response.getSelectedButton() === ui.Button.CANCEL) {
          ui.alert('Conversion cancelled.', 'Form creation was cancelled by the user.', ui.ButtonSet.OK);
          return ''; // Exit if cancelled
        }
      } catch (e) {
        Logger.log('Prompt for form title failed or was dismissed. Using default title.');
      }
    
      // Data structure to hold parsed form items before creating the form
      const formItemsToCreate = [];
      let currentQuestion = null;
      let currentOptions = [];
      let currentQuestionElementId = null; // Store ID to link errors back to doc elements
    
      Logger.log('Starting document parsing...');
    
      // Iterate through all child elements of the document body
      for (let i = 0; i < body.getNumChildren(); i++) {
        const element = body.getChild(i);
        const elementType = element.getType();
        const text = element.getText().trim();
    
        // Skip empty lines or elements without text content
        if (!text) {
          continue;
        }
    
        // --- PARAGRAPH ELEMENT PROCESSING ---
        if (elementType === DocumentApp.ElementType.PARAGRAPH) {
          // If we were previously collecting options for a question, and now encounter a new paragraph (not a list item),
          // it means the previous question and its options are complete.
          if (currentQuestion) {
            if (currentOptions.length > 0) {
              // It's a Multiple Choice question
              formItemsToCreate.push({
                type: 'MULTIPLE_CHOICE',
                question: currentQuestion,
                options: currentOptions,
                docElementId: currentQuestionElementId
              });
              Logger.log(`Parsed MC question: "${currentQuestion}" with ${currentOptions.length} options.`);
            } else {
              // It's a Paragraph Text question (no options followed)
              formItemsToCreate.push({
                type: 'PARAGRAPH_TEXT',
                question: currentQuestion,
                docElementId: currentQuestionElementId
              });
              Logger.log(`Parsed Paragraph Text question: "${currentQuestion}".`);
            }
          }
    
          // This new paragraph is the start of a new question
          currentQuestion = text;
          currentOptions = []; // Reset options for the new question
          currentQuestionElementId = element.getId(); // Store ID for potential error logging
          Logger.log(`New potential question found: "${currentQuestion}"`);
    
        }
        // --- LIST ITEM PROCESSING ---
        else if (elementType === DocumentApp.ElementType.LIST_ITEM) {
          if (currentQuestion) {
            currentOptions.push(text);
            Logger.log(`- Option added: "${text}"`);
          } else {
            // This is an edge case: a list item found without a preceding question paragraph.
            // It's likely an unparsed structure or an error in the document format.
            Logger.log(`Warning: Found list item "${text}" without a preceding question. This item will be skipped.`);
            ui.alert(
              'Formatting Warning',
              `A list item ("${text}") was found without a clear preceding question. ` +
              'Please ensure questions are standalone paragraphs directly followed by their options (if any).\n' +
              'This item will be skipped in the form.',
              ui.ButtonSet.OK
            );
          }
        }
        // --- Other Element Types (e.g., Table, HorizontalRule, Image) ---
        else {
          Logger.log(`Skipping unsupported element type: ${elementType} with text: "${text}"`);
          // If there's a pending question, it needs to be processed here before skipping
          if (currentQuestion) {
              if (currentOptions.length > 0) {
                  formItemsToCreate.push({
                      type: 'MULTIPLE_CHOICE',
                      question: currentQuestion,
                      options: currentOptions,
                      docElementId: currentQuestionElementId
                  });
                  Logger.log(`Parsed MC question before skipping unsupported element: "${currentQuestion}".`);
              } else {
                  formItemsToCreate.push({
                      type: 'PARAGRAPH_TEXT',
                      question: currentQuestion,
                      docElementId: currentQuestionElementId
                  });
                  Logger.log(`Parsed Paragraph Text question before skipping unsupported element: "${currentQuestion}".`);
              }
              currentQuestion = null;
              currentOptions = [];
              currentQuestionElementId = null;
          }
        }
      }
    
      // --- After the loop, process the last collected question (if any) ---
      if (currentQuestion) {
        if (currentOptions.length > 0) {
          formItemsToCreate.push({
            type: 'MULTIPLE_CHOICE',
            question: currentQuestion,
            options: currentOptions,
            docElementId: currentQuestionElementId
          });
          Logger.log(`Final MC question parsed: "${currentQuestion}".`);
        } else {
          formItemsToCreate.push({
            type: 'PARAGRAPH_TEXT',
            question: currentQuestion,
            docElementId: currentQuestionElementId
          });
          Logger.log(`Final Paragraph Text question parsed: "${currentQuestion}".`);
        }
      }
    
      Logger.log(`Total questions parsed: ${formItemsToCreate.length}`);
    
      // --- Create Google Form ---
      if (formItemsToCreate.length === 0) {
        ui.alert('No Questions Found', 'No recognizable questions were found in the document. Please check the document structure.', ui.ButtonSet.OK);
        Logger.log('No questions found to create a form.');
        return '';
      }
    
      let form;
      try {
        form = FormApp.create(formTitle);
        Logger.log(`Created new Google Form: ${form.getTitle()} (ID: ${form.getId()})`);
      } catch (e) {
        ui.alert('Error Creating Form', 'Could not create the Google Form. Please check your Google Drive permissions or try again later.', ui.ButtonSet.OK);
        Logger.log(`Error creating form: ${e.message}`);
        return '';
      }
    
      // Add questions to the form
      formItemsToCreate.forEach((itemData, index) => {
        try {
          if (itemData.type === 'MULTIPLE_CHOICE') {
            const item = form.addMultipleChoiceItem();
            item.setTitle(itemData.question);
            const choices = itemData.options.map(option => item.createChoice(option));
            item.setChoices(choices);
            Logger.log(`Added MC item ${index + 1}: "${itemData.question}"`);
          } else if (itemData.type === 'PARAGRAPH_TEXT') {
            const item = form.addParagraphTextItem();
            item.setTitle(itemData.question);
            Logger.log(`Added Paragraph Text item ${index + 1}: "${itemData.question}"`);
          }
        } catch (e) {
          const errorMsg = `Error adding question "${itemData.question}" to form: ${e.message}. ` +
                           `Doc Element ID: ${itemData.docElementId || 'N/A'}`;
          Logger.log(errorMsg);
          ui.alert('Form Creation Error', `There was an error adding a question to the form:\n"${itemData.question}"\n\nError: ${e.message}\n` +
                   'Please check the script logs for more details.', ui.ButtonSet.OK);
        }
      });
    
      const formUrl = form.getPublishedUrl();
      Logger.log(`Google Form created successfully. URL: ${formUrl}`);
    
      // Provide the URL to the user
      const response = ui.alert(
        'Form Created!',
        `Your Google Form "${formTitle}" has been created successfully.\n\n` +
        `Click "Open Form" to view it or "Copy URL" to copy the link.\n\nURL: ${formUrl}`,
        ui.ButtonSet.YES_NO
      );
    
      if (response === ui.Button.YES) { // Open Form
        // Using Browser.msgBox with a direct link (Apps Script doesn't have a direct 'open URL' method within UI.alert)
        // The user will need to copy/paste or click the link from the logs.
        // For direct opening, we need a different approach, e.g., a custom HTML sidebar,
        // or just logging the URL and instructing the user.
        // As a workaround, we can provide the URL and let the user open it manually.
        // The current UI.alert will just show Yes/No options. Let's make it a copy/open link for convenience.
        
        // A simpler approach for direct opening in new tab is not directly available from UI.alert.
        // The user has to manually copy and paste. Let's adjust the prompt text.
        ui.alert(
          'Form Created!',
          `Your Google Form "${formTitle}" has been created successfully.\n\n` +
          `You can find it here: ${formUrl}\n\n` +
          `Please copy the URL and paste it into your browser to open the form.`,
          ui.ButtonSet.OK
        );
    
      } else if (response === ui.Button.NO) { // Copy URL
        // Can't directly copy to clipboard from Apps Script without a custom HTML service.
        // User will have to copy from the alert or logs.
        ui.alert(
          'URL Copied (Manual)',
          `The Form URL is: ${formUrl}\n\nPlease manually copy this URL.`,
          ui.ButtonSet.OK
        );
      }
      
      return formUrl;
    }
    
    

    How to Use and Test:

    1. Prepare your Google Doc:

      • Create a new Google Doc or use an existing one.
      • Populate it with content following the assumed structure.

      Example Google Doc Content:

      Question 1: What is the capital of France?
      * Paris
      * London
      * Rome
      * Berlin
      
      Describe the importance of photosynthesis.
      
      What is your favorite color?
      
      Question with multiple choice options:
      * Option A
      * Option B
      * Option C
      
      Final thoughts on the topic:
      
    2. Open Script Editor:

      • With your Google Doc open, go to Extensions > Apps Script.
    3. Paste Code:

      • Delete any default code (function myFunction() {}).
      • Copy and paste the entire script from above into the Code.gs file.
      • Save the project (Floppy disk icon).
    4. Run the Script (First Time Authorization):

      • Go back to your Google Doc tab.
      • Refresh the page if you don't see the "Convert to Form" menu immediately.
      • Click Convert to Form > Convert Document.
      • A dialog will appear asking for authorization. Click Review Permissions.
      • Select your Google account.
      • Review the permissions (it needs to view and manage your Google Docs and Forms). Click Allow.
    5. Execute Again:

      • After authorization, run Convert to Form > Convert Document one more time.
      • It will first prompt you for the desired Form Title. Enter a title or leave it blank to use the Doc's name, then click OK.
      • The script will run. You'll see a small "Running script..." notification.
      • Once complete, an alert box will pop up with the URL of the newly created Google Form.
    6. Check the Output:

      • Open the provided URL in your browser to see the generated Google Form.
      • Check your Google Drive; the new form will be there.
      • Check Extensions > Apps Script > Execution log (or Logger.log output in the script editor) for detailed processing information and any warnings/errors.

    Key Features and Design Choices:

    • onOpen() Function: Automatically creates a custom menu in the Google Doc for easy access to the script.
    • convertToForm() Function (Main Logic):
      • User Customization (Form Title): Prompts the user for a form title, defaulting to the Google Doc's name.
      • Document Parsing: Iterates through Body elements of the active Google Doc.
      • State-based Parsing: Uses currentQuestion and currentOptions variables to keep track of the current parsing state (e.g., currently parsing options for a question).
      • Question Detection: A new PARAGRAPH element (that's not empty) signals a new question.
      • Option Detection: LIST_ITEM elements immediately following a question are collected as options.
      • Question Type Mapping:
        • If currentQuestion is followed by currentOptions (list items), it becomes a MultipleChoiceItem.
        • If currentQuestion is not followed by any currentOptions, it becomes a ParagraphTextItem (a general-purpose long answer field).
      • Error Handling & Logging:
        • Logger.log() statements provide detailed execution flow for debugging.
        • ui.alert() is used to notify the user about warnings (e.g., list items without a preceding question) or critical errors (e.g., form creation failure).
        • It captures cases where list items appear without a currentQuestion, indicating a potential format mismatch in the Doc.
    • Google Form Creation: Uses FormApp.create() and form.addMultipleChoiceItem(), form.addParagraphTextItem() to build the form dynamically.
    • Output URL: Returns and logs the form.getPublishedUrl(), also presenting it to the user in an alert dialog.

    Limitations and Potential Enhancements (as per optional requirements):

    • Batch Processing: This script processes one Doc at a time (the active Doc). For batch processing, you'd need a separate script that reads a list of Doc IDs (e.g., from a Google Sheet) and calls convertToForm for each, possibly passing the Doc ID as an argument instead of using DocumentApp.getActiveDocument().
    • Question Type Overrides: Currently, type detection is purely structural (list items for MC, no list items for Paragraph). To allow overrides (e.g., forcing a TEXT_ITEM or CHECKBOX_ITEM), you would need to introduce special markers in the Doc, like [TYPE:TEXT] or [TYPE:CHECKBOX], and modify the parsing logic to detect and act on these markers.
    • Irregular Formatting: The script handles basic empty lines and skips unsupported element types. However, highly irregular formatting (e.g., text between a question and its first option, or multiple paragraphs forming a single "question" where only the first is detected) might lead to misinterpretations. Strict adherence to the assumed structure is recommended.
    • Required Questions: All questions generated are optional by default. You could add logic to make them required (e.g., based on a special marker in the Doc or a global setting).
    • Answer Keys/Scores: This script does not handle setting answer keys or scores, as that typically requires explicit marking in the Doc (e.g., [CORRECT]) which is beyond the scope of a basic structural conversion.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.