Formatting for WordPress

One of the things I found was that I couldn’t copy scripts directly to WordPress, especially python scripts, since the indents all got treated as the same in conversion to html. The consequence – a python script, which takes a file and converts it to a format that is coped with by WordPress. This is then copied directly to the clipboard, ready to paste into the raw code section of the page.

The script is fully documented, and has one dependency: pyperclip:

#!/usr/bin/env python3
"""
WordPress Classic Editor Code Inserter (BSOD Edition)
=====================================================
This script prepares raw code files (like Python scripts) to be pasted directly
into the 'Text' (HTML) tab of the WordPress Classic Editor.

It solves three critical issues:
1. Prevents WordPress from stripping Python's structural indentation.
2. Stops WordPress (wpautop) from breaking the code into multiple separate boxes on empty lines.
3. Applies a custom retro BSOD theme container via a specific CSS class wrapper.

Dependencies:
    pip install pyperclip
"""

import sys
import os
import html
import pyperclip  # Used because it strictly handles raw text data without OS interference


def copy_for_code_tab(file_path):
    """
    Reads a code file, protects its characters, wraps it in a target HTML block,
    and copies the final output directly to the system clipboard.
    """

    # STEP 1: SAFETY CHECK
    # Verify that the file the user specified actually exists before doing anything else.
    if not os.path.isfile(file_path):
        print(f"[-] Error: File '{file_path}' not found.")
        # Exit with a failure status code (1)
        sys.exit(1)

    try:
        # STEP 2: FILE READING
        # Open and read the target file using safe UTF-8 encoding to preserve special characters.
        with open(file_path, 'r', encoding='utf-8') as f:
            raw_code = f.read()

        # STEP 3: HTML ENTITY ENCODING
        # Python code uses characters like '<', '>', and '&' (e.g., 'if x < y:').
        # If we paste raw '<' into WordPress text view, the browser tries to parse it as an HTML tag,
        # which breaks the code display. html.escape turns them into safe codes like '&lt;', '&gt;', and '&amp;'.
        escaped_code = html.escape(raw_code)

        # STEP 4: STRUCTURAL HTML WRAPPING
        # We explicitly wrap the code inside a <pre> tag with our custom class 'bsod-code'.
        # Why <pre>? Because WordPress is strictly forbidden from parsing or breaking up a <pre> block.
        # Why the class? It tells our child theme's style.css to activate the blue screen look
        # on this block specifically, while leaving standard standalone <pre> tags completely plain.
        formatted_html = f'<pre class="bsod-code">{escaped_code}</pre>'

        # STEP 5: SYSTEM CLIPBOARD INJECTION
        # We push the fully constructed raw text string right onto the system clipboard buffer.
        # Using pyperclip ensures that no extra rich-text metadata or formatting gets attached.
        pyperclip.copy(formatted_html)

        # STEP 6: USER CONFIRMATION
        # Print feedback directly to the terminal so you know the script ran successfully.
        print(f"[+] Success! Wrapped '{os.path.basename(file_path)}' cleanly in a class-targeted pre block.")
        print("[+] Click the 'Text' (Code) tab in your WordPress Classic Editor and paste.")

    except Exception as e:
        # CATCH-ALL ERROR HANDLING
        # If anything goes wrong (file permissions, clipboard locks, etc.), print the exact error message.
        print(f"[-] An unexpected error occurred: {e}")
        sys.exit(1)


# APPLICATION ENTRY POINT
# This block ensures the code only runs if executed directly from the command line, not when imported.
if __name__ == "__main__":

    # Check if the user forgot to supply the target file name in the terminal argument
    if len(sys.argv) < 2:
        print("Usage: python wp_bsod_pre.py <path_to_your_script>")
        sys.exit(1)

    # Pass the command line file argument (sys.argv[1]) straight into our processing function
    copy_for_code_tab(sys.argv[1])