跳到正文

科技·工程

洛谷 IDE 缺省源

a_small_OIer约 28 分钟
原文
文章信息与版本

文章信息

发布
2026年6月11日
收录
2026年6月12日
更新
2026年8月19日
篇幅
约 28 分钟

版本

  1. v2当前
  2. v1

你是否有被迫在艰苦环境在洛谷 IDE 写代码懒得敲缺省源的经历?

现隆重推出洛谷 IDE 缺省源!源代码复制后粘贴至油猴即可使用。

本代码使用 MIT License 开源协议,已经在源代码注明。这次学聪明了。

对于 IDE 自动保存

保证缺省源有 0%0\% 的概率上次写了一半的自动保存代码覆盖。

因为洛谷的 IDE 是基于 React 的,CodeMirror 6 的 EditorState 在组件挂载时同步创建,创建时必须传入初始文档字符串,而脚本是在页面完全加载完成后启动的,故不可能出现覆盖的情况。

源代码:

JavaScript
// ==UserScript==
// @name         洛谷 IDE 缺省源
// @namespace    http://tampermonkey.net/
// @version      2.2
// @description  自动填充洛谷 IDE 缺省源
// @author       a_small_OIer
// @include      *://www.luogu.com.cn/problem/*
// @include      *://www.luogu.com.cn/contest/*
// @run-at       document-end
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_addStyle
// ==/UserScript==

/*
 * MIT License
 *
 * Copyright (c) 2026 a_small_OIer
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

(function() {
    'use strict';
    function isIdePage() {
        return location.hash.startsWith('#ide');
    }
    const DEFAULT_TEMPLATE = `#include <bits/stdc++.h>
using namespace std;
int main() {

    return 0;
}`;
    function getTemplate() {
        return GM_getValue('defaultCodeTemplate', DEFAULT_TEMPLATE);
    }
    function setTemplate(code) {
        GM_setValue('defaultCodeTemplate', code);
    }
    //怎么还要穿透啊/ll
    function querySelectorAllDeep(selector, root = document){
        const results = [];
        if (root.querySelectorAll)
            results.push(...root.querySelectorAll(selector));
        const allNodes = root.querySelectorAll ? root.querySelectorAll('*') : [];
        for(const node of allNodes)
            if(node.shadowRoot)
                results.push(...querySelectorAllDeep(selector, node.shadowRoot));
        return results;
    }
    function fillCM6(el){
        if(!el)
            return false;
        if(el.cmView && el.cmView.view){
            const view = el.cmView.view;
            if(view.state.doc.length === 0){
                view.dispatch({
                    changes: { from: 0, to: 0, insert: getTemplate() }
                });
                return true;
            }
        }
        const editable = el.querySelector('[contenteditable="true"]');
        if(editable && editable.textContent.trim() === ''){
            editable.focus();
            document.execCommand('insertText', false, getTemplate());
            return true;
        }
        return false;
    }
    function tryFillEditor(el){
        if(!el || el.dataset.autofilled === 'true')
            return false;
        if(fillCM6(el)){
            el.dataset.autofilled = 'true';
            return true;
        }
        return false;
    }
    function startObserver(){
        querySelectorAllDeep('.cm-editor').forEach(tryFillEditor);
        const observer = new MutationObserver(mutations => {
            for(const mutation of mutations){
                for(const node of mutation.addedNodes){
                    if(node.nodeType !== 1)
                        continue;
                    if(node.matches && node.matches('.cm-editor'))
                        tryFillEditor(node);
                    querySelectorAllDeep('.cm-editor', node).forEach(tryFillEditor);
                }
            }
        });
        observer.observe(document.body, { childList: true, subtree: true });
        return observer;
    }
    let ui = null;
    function findButtonByText(text){
        const candidates = document.querySelectorAll('button, a, span, div');
        for(const el of candidates)
            if(el.textContent.trim() === text)
                return el;
        return null;
    }
    function findToolbar(){
        const selectors = [
            '.ide-toolbar', '.toolbar', '.editor-toolbar',
            '.code-toolbar', '.ide-header', '.lfe-ide-toolbar',
            'div[class*="toolbar"]', 'div[class*="Toolbar"]',
            'header.ide-header'
        ];
        for(const sel of selectors){
            const bar = document.querySelector(sel);
            if(bar)
                return bar;
        }
        return null;
    }
    function createUI(){
        if(ui)
            return ui;
        GM_addStyle(`
            .autofill-inline-btn {
                display: inline-flex;
                align-items: center;
                cursor: pointer;
                font-size: 14px;
                color: #3498db;
                background: transparent;
                border: 1px solid #3498db;
                border-radius: 4px;
                padding: 4px 12px;
                margin-left: 6px;
                transition: all 0.2s;
                white-space: nowrap;
                vertical-align: middle;
                line-height: 1.4;
            }
            .autofill-inline-btn:hover {
                background: #3498db;
                color: white;
            }
            .autofill-fab {
                position: fixed; bottom: 80px; right: 90px;
                width: 48px; height: 48px; border-radius: 50%;
                background: #3498db; color: white; font-size: 22px;
                display: flex; align-items: center; justify-content: center;
                cursor: pointer; box-shadow: 0 4px 12px rgba(52,152,219,0.3);
                z-index: 10000; user-select: none; transition: transform 0.2s;
                border: none;
            }
            .autofill-fab:hover {
                transform: scale(1.1);
                box-shadow: 0 6px 16px rgba(52,152,219,0.4);
            }
            .autofill-overlay {
                display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0;
                background: rgba(0,0,0,0.4); z-index: 10001;
                justify-content: center; align-items: center; backdrop-filter: blur(3px);
            }
            .autofill-overlay.active { display: flex; }
            .autofill-modal {
                background: white; border-radius: 16px; width: 700px;
                max-width: 90vw; max-height: 80vh; display: flex; flex-direction: column;
                box-shadow: 0 12px 40px rgba(0,0,0,0.2); overflow: hidden;
            }
            .autofill-modal-header {
                padding: 20px 24px; border-bottom: 1px solid #f0f0f0;
                font-size: 18px; font-weight: 600; display: flex;
                justify-content: space-between; align-items: center; color: #111827;
            }
            .autofill-modal-close {
                cursor: pointer; font-size: 24px; color: #9ca3af;
                width: 32px; height: 32px; display: flex; align-items: center; justify-content: center;
                border-radius: 8px; transition: background 0.15s;
            }
            .autofill-modal-close:hover { background: #f3f4f6; color: #111827; }
            .autofill-modal-body { padding: 24px; flex: 1; overflow-y: auto; }
            .autofill-modal-body textarea {
                width: 100%; height: 360px; font-family: 'Fira Code', 'Cascadia Code', Consolas, monospace;
                font-size: 14px; line-height: 1.6; padding: 16px;
                border: 1px solid #e5e7eb; border-radius: 12px; resize: vertical;
                background: #fafafa; outline: none; transition: border 0.15s;
            }
            .autofill-modal-body textarea:focus { border-color: #3498db; }
            .autofill-modal-footer {
                padding: 16px 24px; border-top: 1px solid #f0f0f0;
                display: flex; justify-content: flex-end; gap: 12px; background: #fafafa;
            }
            .btn-primary {
                padding: 10px 24px; border-radius: 10px; border: none;
                cursor: pointer; font-weight: 500; font-size: 15px;
                background: #3498db; color: white; transition: background 0.2s;
            }
            .btn-primary:hover { background: #2980b9; }
            .btn-secondary {
                padding: 10px 24px; border-radius: 10px; border: 1px solid #d1d5db;
                cursor: pointer; font-weight: 500; font-size: 15px;
                background: white; color: #374151; transition: background 0.2s;
            }
            .btn-secondary:hover { background: #f9fafb; }
        `);
        //额啊 UI 真是一点都不会设计
        const settingsBtn = document.createElement('button');
        settingsBtn.className = 'autofill-inline-btn';
        settingsBtn.textContent = '编辑缺省源';
        settingsBtn.title = '修改 IDE 自动填充的代码模板';
        const overlay = document.createElement('div');
        overlay.className = 'autofill-overlay';
        overlay.innerHTML = `
            <div class="autofill-modal">
                <div class="autofill-modal-header">
                    <span>编辑缺省源模板</span>
                    <span class="autofill-modal-close">&times;</span>
                </div>
                <div class="autofill-modal-body">
                    <textarea id="autofill-template-textarea" spellcheck="false"></textarea>
                </div>
                <div class="autofill-modal-footer">
                    <button class="btn-secondary autofill-cancel-btn">取消</button>
                    <button class="btn-primary autofill-save-btn">保存</button>
                </div>
            </div>
        `;
        document.body.appendChild(overlay);
        const textarea = overlay.querySelector('#autofill-template-textarea');
        const closeBtn = overlay.querySelector('.autofill-modal-close');
        const cancelBtn = overlay.querySelector('.autofill-cancel-btn');
        const saveBtn = overlay.querySelector('.autofill-save-btn');
        function openModal(){
            textarea.value = getTemplate();
            overlay.classList.add('active');
        }
        function closeModal(){
            overlay.classList.remove('active');
        }
        settingsBtn.addEventListener('click', openModal);
        closeBtn.addEventListener('click', closeModal);
        cancelBtn.addEventListener('click', closeModal);
        overlay.addEventListener('click', e => { if (e.target === overlay) closeModal(); });
        saveBtn.addEventListener('click', () => {
            setTemplate(textarea.value);
            const toast = document.createElement('div');
            toast.textContent = '✅ 缺省源已保存';
            Object.assign(toast.style, {
                position: 'fixed', bottom: '20px', left: '50%', transform: 'translateX(-50%)',
                background: '#3498db', color: 'white', padding: '10px 24px', borderRadius: '8px',
                zIndex: '99999', fontSize: '14px', opacity: '1', transition: 'opacity 0.3s'
            });
            document.body.appendChild(toast);
            setTimeout(() => { toast.style.opacity = '0'; setTimeout(() => toast.remove(), 300); }, 1500);
            closeModal();
        });
        document.addEventListener('keydown', e => {
            if (e.key === 'Escape' && overlay.classList.contains('active')) closeModal();
        });
        const observer = startObserver();
        ui = {
            settingsBtn,
            overlay,
            textarea,
            observer,
            placement: 'none'
        };
        return ui;
    }
    function placeNextTo(target) {
        if(!ui || !target || !target.parentNode)
            return false;
        if(ui.settingsBtn.previousElementSibling === target)
            return true;
        target.parentNode.insertBefore(ui.settingsBtn, target.nextSibling);
        ui.settingsBtn.style.display = '';
        return true;
    }
    function tryPlaceButton() {
        if(!ui)
            return;
        const selfTest = findButtonByText('自测');
        if(selfTest){
            if(placeNextTo(selfTest)){
                ui.placement = 'selfTest';
                return;
            }
        }
    }
    function onRouteChange(){
        if (isIdePage()){
            createUI();
            tryPlaceButton();
            //监听
            const domObserver = new MutationObserver(() => {
                if (ui.placement !== 'selfTest') {
                    const st = findButtonByText('自测');
                    if(st){
                        if(placeNextTo(st)){
                            ui.placement = 'selfTest';
                            domObserver.disconnect();
                        }
                    }
                }
            });
            domObserver.observe(document.body, { childList: true, subtree: true });
            setTimeout(() => domObserver.disconnect(), 10000);
        }else{
            if (ui){
                if (ui.settingsBtn.parentNode) ui.settingsBtn.parentNode.removeChild(ui.settingsBtn);
                ui.settingsBtn.style.display = 'none';
                ui.overlay.classList.remove('active');
            }
        }
    }
    function init(){
        createUI();
        onRouteChange();
        window.addEventListener('hashchange', onRouteChange);
    }
    if(document.readyState === 'loading'){
        document.addEventListener('DOMContentLoaded', init);
    }else{
        init();
    }
})();

正常人谁用洛谷 IDE 啊。

原文