about summary refs log tree commit diff stats
path: root/dwm.1
Commit message (Expand)AuthorAgeFilesLines
* bugfix of bugfix (thx to Sander)Anselm R. Garbe2007-02-121-1/+1
* fixed a bugAnselm R. Garbe2007-02-121-1/+1
* during writing 2wm.1 I noticed some bugs in dwm.1Anselm R. Garbe2007-02-121-3/+3
* regarding to http://plan9.bell-labs.com/sources/contrib/rsc/man.ps the BUGS s...Anselm R. Garbe2007-01-261-2/+2
* renamed CAVEATS into BUGSAnselm R. Garbe2007-01-261-1/+1
* moved BORDERPX to config.*.hAnselm R. Garbe2007-01-171-1/+1
* removed client title barAnselm R. Garbe2007-01-141-1/+0
* added Button{4,5} description to dwm.1Anselm R. Garbe2007-01-101-0/+6
* small grammar fix of dwm.1Anselm R. Garbe2007-01-071-2/+2
* changed a term in dwm.1Anselm R. Garbe2007-01-071-1/+1
* removed the term clients from dwm.1Anselm R. Garbe2007-01-051-3/+3
* changed shortcuts to M-i and M-dAnselm R. Garbe2007-01-051-2/+2
* changed plus key to MODKEY-Shift-plus (US-layout restrictions ;)Anselm R. Garbe2007-01-051-1/+1
* added MODKEY-{plus,minus} shortcuts (increasing/decreasing master clients)Anselm R. Garbe2007-01-051-0/+6
* applied Sanders patch 2.7arg@mig292006-12-131-3/+3
* fixed man page, status bar displays EOF instead of "broken pipe"arg@mig292006-12-131-1/+1
* added the java odyssee to CAVEATS sectionarg@mig292006-12-131-2/+10
* we don't use the term clients anymore, windows is the better termarg@mig292006-12-071-1/+1
* and the winner isarg@mig292006-12-011-2/+3
* less obtrusive indicator (only a top line)arg@mig292006-12-011-1/+1
* final2 indicatorarg@mig292006-12-011-1/+1
* final indicatorsarg@mig292006-12-011-2/+1
* removed viewall(), replaced with view(-1); added tag(-1) to tag a client with...arg@mig292006-11-301-0/+3
* extended dwm.1 with last change 2.4arg@mig292006-11-281-1/+1
* added man page entryarg@mig292006-11-271-0/+3
* applied Manuels patch (thanks to Manuel!)arg@mig292006-11-251-1/+1
* small fix of man pagearg@mig292006-11-241-1/+1
* using the term 'indicated' instead of 'higlighted' 2.3arg@mig292006-11-231-3/+3
* updated man page with the bottom right corner indicatorarg@mig292006-11-231-2/+4
* applied Gottox patch to simplify the resizing of col, instead of resizing the...arg@mig292006-10-311-2/+2
* removed the stack position stuffAnselm R. Garbe2006-10-051-5/+1
* final fix for man pageAnselm R. Garbe2006-10-051-3/+3
* Button3 click on mode label toggles stack position nowAnselm R. Garbe2006-10-051-2/+3
* documented the new behavior in man pageAnselm R. Garbe2006-09-291-0/+3
* renamed column into areaAnselm R. Garbe2006-09-281-7/+7
* man page fixarg@mmvi2006-09-221-1/+1
* fixed issue pointed out by Jukkaarg@mmvi2006-09-221-1/+1
* small man page fixarg@mmvi2006-09-221-0/+1
* updated man pagearg@mmvi2006-09-221-5/+1
* fixed a nuance in dwm.1arg@mmvi2006-09-201-1/+1
* really small changes to dwm.1Anselm R. Garbe2006-09-081-4/+3
* made markups in dwm.1 more consistentAnselm R. Garbe2006-09-071-95/+38
* small addition to dwm.1Anselm R. Garbe2006-09-071-4/+4
* well ok, added Mod-s to default bindings (however, I don't need it)Anselm R. Garbe2006-09-051-0/+6
* I really need column growing, now pushing upstreamAnselm R. Garbe2006-09-051-0/+6
* applied sanders patchAnselm R. Garbe2006-09-011-6/+12
* changed shortcut into Mod1-0Anselm R. Garbe2006-08-311-5/+5
* added viewall to mainstream (only Ross Mohns version, not the toggle)Anselm R. Garbe2006-08-311-0/+4
* implemented Button2 press on tags for toggletag on the focused clientAnselm R. Garbe2006-08-311-0/+6
* applied sanders somepatches.patchAnselm R. Garbe2006-08-281-1/+6
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                                                                                                                                                                                                                        
<!DOCTYPE html>
<html lang="en">
<head>
    <!--
MIT License

Copyright (c) m15o

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.
-->
    <meta charset="utf-8">
    <title>squine</title>
</head>
<style>
    html, body, #app, .column, textarea, table, td {
        height: 100%;
    }

    body {
        padding: 0;
        margin: 0;
        background: linear-gradient(to bottom, #e4d16f, #d5363d);
    }

    header {
        display: flex;
        border-bottom: 1px solid;
        border-top: 1px solid;
    }

    header > * {
        border-right: 1px solid;
    }

    .column {
        display: flex;
        flex-direction: column;
        min-width: 10px;
    }

    article, section {
        display: flex;
        flex-direction: column;
        overflow: hidden;
    }

    .name {
        box-sizing: border-box;
        width: 100%;
        padding: 2px 5px;
        margin: 0;
        outline: none;
        border: 0;
        border-right: 1px solid;
        background-color: #fffad6;
    }

    #search {
        display: none;
    }

    #search.searching {
        display: block;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        background-color: darkblue;
        color: white;
    }

    textarea {
        box-sizing: border-box;
        padding: 5px;
        margin: 0;
        border: 0;
        outline: none;
        resize: none;
        background-color: #fff9e9;
    }

    .action {
        padding: 2px 5px;
        cursor: pointer;
    }

    .back, .forward {
        background-color: silver;
    }

    .hist {
        background-color: inherit;
    }

    .folded article, .folded .h-resize, .maxed .h-resize {
        display: none;
    }

    .maxed article {
        display: flex;
    }

    .folded .maxed, .maxed article {
        flex-grow: 1;
    }

    section:last-child, section:last-child article {
        flex-grow: 1;
    }

    .folded section {
        flex-grow: 0;
    }

    table {
        width: 100%;
        border-collapse: collapse;
    }

    td {
        padding: 0;
        border: 1px solid;
    }

    .menu > * {
        padding: 0 4px;
        cursor: pointer;
    }

    .menu > *:hover {
        background-color: #dfad6a;
    }

    .active-p .content {
        background-color: white;
    }

    .active {
        background-color: #e5d575;
    }

    .col {
        position: relative;
    }

    .h-resize:hover, .resize:hover {
        background-color: rebeccapurple;
    }

    .resize {
        width: 2px;
        background-color: silver;
        cursor: col-resize;
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
    }

    #settings {
        display: none;
    }

    #settings.visible {
        display: table-row;
    }

    .dirty .save {
        background-color: aquamarine;
    }

    .h-resize {
        height: 2px;
        background-color: darkgrey;
        cursor: row-resize;
    }

    .parse {
        background-color: #dfad6a;
    }
</style>
<body>
<div id="app"></div>
<script>
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Helpers

    function $(elt) {
        return document.querySelector(elt);
    }

    function $$(elt) {
        return document.querySelectorAll(elt);
    }

    function $$active(elt) {
        return $panel => ($panel && $panel.querySelector(elt)) || $('.active-p ' + elt);
    }

    function $name($panel) {
        return $$active('.name')($panel);
    }

    function $content($panel) {
        return $$active('.content')($panel);
    }

    function t$(e) {
        return e.target;
    }

    function closest$(e, sel) {
        return t$(e).closest(sel);
    }

    function $search() {
        return $('#search');
    }

    function $panel() {
        return $('.active-p');
    }

    function hasCls($elt, cls) {
        return $elt.classList.contains(cls);
    }

    function date() {
        return (new Date()).toLocaleDateString('en-CA');
    }

    function makeElt(elt, cls, attrs, html, value) {
        let e = document.createElement(elt);
        cls.forEach(c => e.classList.add(c));
        Object.keys(attrs).forEach(k => e.setAttribute(k, attrs[k]));
        html && (e.innerHTML = html);
        value && (e.value = value);
        return e;
    }

    function togCls(cls, sel, $elt) {
        $$(sel).forEach((e) => e.classList.remove(cls));
        $elt.classList.add(cls);
    }

    function setActive($section) {
        togCls('active-p', 'section', $section);
    }

    function closeSearch() {
        $search().classList.remove('searching');
        $content().focus();
    }

    function refPane(name) {
        let p;
        $$('section').forEach(e => e.querySelector('.name').value.startsWith('+ref') && (p = e));
        if (!p) {
            p = createPane();
        }
        setActive(p);
        load(name);
        return p;
    }

    function runPane(content) {
        let p;
        save();
        let old = $panel();
        $$('section').forEach(e => e.querySelector('.name').value.startsWith('+run') && (p = e));
        let err, rv;
        storeKeys().forEach(k => {
            if (k === 'main') return;
            try {
                global[k] = eval(global, parse(storeGet(k)), true);
            } catch (e) {
                err = `in ${k}: ${e}`
            }
        });
        if (!p) {
            p = createPane();
            load('+run');
        }
        setActive(p);
        if (err) {
            $content().value = err;
            return;
        }
        try {
            $content().value = asString(exec(storeGet('main')));
        } catch (e) {
            $content().value = e;
        }
        setActive(old);
        $content().focus();
    }


    // function runPane(content) {
    //     let p;
    //     $$('section').forEach(e => e.querySelector('.name').value.startsWith('+run') && (p = e));
    //     let err, rv;
    //     try {
    //         if ($name().value !== 'main') {
    //             global[$name().value] = eval(global, parse(content), true);
    //             rv = asString(global[$name().value]);
    //         }
    //     } catch (e) {
    //         err = e;
    //     }
    //
    //     if (!p) {
    //         p = createPane();
    //         load('+run');
    //     }
    //     setActive(p);
    //     if (err) {
    //         $content().value = err;
    //         return;
    //     }
    //     if (rv) {
    //         $content().value = rv;
    //         return;
    //     }
    //     try {
    //         $content().value = asString(exec(content));
    //     } catch (e) {
    //         $content().value = e;
    //     }
    // }

    function isChordNav(e) {
        return e.metaKey || e.ctrlKey;
    }

    function isChordNavBlank(e) {
        return isChordNav(e) && e.altKey;
    }

    function navBlank(name) {
        findOrCreatePane(name);
    }

    function debounce(fn, ms) {
        let timeout;
        return (...args) => {
            clearTimeout(timeout);
            timeout = setTimeout(() => fn(...args), ms);
        }
    }

    function basename(path) {
        const n = path.split('/').pop();
        return n.split('.').shift();
    }

    function download(data, name, mime) {
        const link = document.createElement('a');
        link.download = name;
        link.href = window.URL.createObjectURL(new Blob([data], {type: mime}));
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // storage

    let store = {};

    function storeSet(k, v) {
        if (isStoreKey(k) && v === storeGet(k, v)) return;
        $('#app').classList.add('dirty');
        store[k] = v;
    }

    function storeGet(k) {
        return store[k] || '';
    }

    function storeDel(k) {
        delete store[k];
    }

    function storeKeys(sorted) {
        let rv = Object.keys(store);
        if (sorted) return rv.sort();
        return rv;
    }

    function isStoreKey(k) {
        return storeKeys().includes(k);
    }

    function storeClear() {
        store = {};
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Core

    function save() {
        let name = $name().value;
        let content = $content().value;
        $panel().dataset['name'] = name;
        if (!name || name === '+run') return;
        storeSet(name, content);
        refresh();
    }

    const saveD = debounce(save, 200);

    function updateHistory(name) {
        let cname = $panel().dataset['name'];
        if (!name || name === cname) return;
        hpush(hist().back, cname);
        hist().forward = [];
    }

    function ls(prefix) {
        return storeKeys(true).filter(k => !prefix || k.startsWith(prefix)).join('\n');
    }

    function orph() {
        return storeKeys().map(k => {
            const v = storeGet(k);
            const m = [...v.matchAll(/\[\[([\w\.\-]+)\]\]/g)].map(match => match[1]);
            const r = m.filter(e => !storeGet(e));
            if (!r.length) return null;
            return ['[[' + k + ']]', '----------', ...r.map(e => '[[' + e + ']]'), ''].join('\n');
        }).filter(Boolean).join('\n');
    }

    function load(name, noHist) {
        if (!name) {
            $name().value = '';
            $content().value = '';
            return;
        }
        !noHist && updateHistory(name)
        if (name === '+orph') {
            $content().value = orph();
        } else if (name.startsWith('+ls')) {
            $content().value = ls(name.split(':')[1]);
        } else if (name.startsWith('+search')) {
            $content().value = name.split(':')[1] ? lookup(name.split(':')[1]) : '';
        } else if (name.startsWith('+ref')) {
            $content().value = name.split(':')[1] ? lookup('[[' + name.split(':')[1] + ']]') : '';
        } else {
            $content().value = storeGet(name);
        }
        $name().value = name;
        $panel().dataset['name'] = name;
        $panel().querySelector('.back').classList.toggle('hist', !!hist().back.length);
        $panel().querySelector('.forward').classList.toggle('hist', !!hist().forward.length);
    }

    function refresh() {
        let $elt = $('#files');
        $elt.innerHTML = '';
        storeKeys().forEach(k => $elt.appendChild(makeElt('option', [], {}, null, k)));
        $elt = $('#globals');
        $elt.innerHTML = '';
        Object.keys(global).forEach(k => $elt.appendChild(makeElt('option', [], {}, null, k)));
    }

    let paneID = 0;

    function createHistory(paneID) {
        history[paneID] = {back: [], forward: []};
    }

    function removeHistory(paneID) {
        delete history[paneID];
    }

    function deletePane($pane) {
        removeHistory($pane.dataset['id']);
        $pane.remove();
    }

    function createPane() {
        const header = document.createElement('header');
        header.append(
            makeElt('span', ['back', 'action'], {}, '<'),
            makeElt('span', ['forward', 'action'], {}, '>'),
            makeElt('input', ['name'], {list: 'files', autocomplete: 'off'}),
            makeElt('span', ['max', 'action'], {}, '+'),
            makeElt('span', ['move', 'action'], {}, '~'),
            makeElt('span', ['close', 'action'], {}, 'x')
        );
        const id = paneID++;
        const section = document.createElement('section');
        const article = document.createElement('article');
        article.append(makeElt('textarea', ['content'], {spellcheck: false, onkeyup: 'saveD()'}));
        section.setAttribute('data-id', '' + id);
        section.append(
            header,
            makeElt('div', ['parse'], {}),
            article,
            makeElt('div', ['h-resize'], {})
        );
        createHistory(id);
        $(".column.active").appendChild(section);
        setActive(section);
        $content().focus();
        return section;
    }

    function lookup(str) {
        return storeKeys(true).map(k => {
            const v = storeGet(k);
            const m = v.split('\n').filter(l => l.includes(str));
            if (!m.length) return null;
            return ['[[' + k + ']]', '----------', ...m, ''].join('\n');
        }).filter(Boolean).join('\n');
    }

    function mv(before, after) {
        return storeKeys().forEach(k => {
            const v = storeGet(k);
            storeSet(k, v.replaceAll('[[' + before + ']]', '[[' + after + ']]'))
        })
    }

    function link(textarea) {
        const text = textarea.value;
        const pos = textarea.selectionStart;
        let start, end;

        for (start = pos - 1; start > -1 && /[^\s\(\)]/.test(text[start]); start--) {
        }

        for (end = pos; end < text.length && /[^\s\(\)]/.test(text[end]); end++) {
        }

        return text.substring(start + 1, end);
    }

    function insert(textarea, text) {
        const start = textarea.selectionStart;
        const end = textarea.selectionEnd;
        const before = textarea.value.substring(0, start);
        const after = textarea.value.substring(end, textarea.value.length);

        textarea.value = before + text + after;
        textarea.selectionStart = textarea.selectionEnd = start + text.length;
    }

    const write = text => document.execCommand('insertText', false, text);

    const history = {};

    function hist() {
        return history[$panel().dataset['id']];
    }

    function hpush(h, name) {
        if (h[h.length - 1] === name) return;
        h.push(name);
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Menu

    function menuNew() {
        createPane();
    }

    function menuLs() {
        $name() || createPane();
        load('+ls');
    }

    function menuReset() {
        if (confirm('delete everything?')) {
            storeClear();
        }
    }

    function menuRun() {
        runPane($content().value);
    }

    function menuMv() {
        let prev = $panel().dataset['name'];
        if (prev === $name().value) return;
        mv(prev, $name().value);
        save();
        storeDel(prev);
        $prevPanel = $panel();
        $$('section').forEach($pane => {
            setActive($pane);
            load($name().value, false);
        })
        setActive($prevPanel);
        refresh();
    }

    function quine() {
        const regex = /let store = (.*)/;
        return ['<!DOCTYPE html>',
            `<head>${document.head.innerHTML}</head>`,
            '<body>',
            '<div id="app"></div>',
            `<script>${$('script').innerHTML.replace(regex, "let store = " + JSON.stringify(store)
                .replaceAll('</' + 'script', "' + '</' + 'script' + '") + ';') + '</'}script>`,
            '</body>'].join('\n');
    }

    function menuSave() {
        $('#app').classList.remove('dirty');
        download(quine(), basename(window.location.href) + '.html', 'text/html');
    }

    function menuExport() {
        download(JSON.stringify(store), basename(window.location.href) + '.json', 'text/json');
    }

    function menuDel() {
        let name = $name().value;
        if (name && confirm('delete ' + name + '?')) {
            storeDel(name);
            refresh();
            deletePane($panel());
        }
    }

    function menuSettings() {
        $('#settings').classList.toggle('visible');
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Pane actions

    function paneFold(e) {
        closest$(e, 'section').classList.toggle('folded');
    }

    function paneMax(e) {
        if (closest$(e, 'section').classList.contains('maxed')) {
            closest$(e, 'section').classList.remove('maxed');
            closest$(e, '.column').classList.remove('folded');
        } else {
            closest$(e, '.column').querySelectorAll('section').forEach(e => e.classList.remove("maxed"));
            closest$(e, 'section').classList.add("maxed");
            closest$(e, '.column').classList.add('folded');
        }
    }

    function paneMove(e) {
        let $c;
        $$('.column').forEach(c => {
            if (c !== closest$(e, '.column')) $c = c;
        });
        $c.appendChild(closest$(e, 'section'));
    }

    function paneClose(e) {
        deletePane(closest$(e, 'section'));
        if ($('section')) {
            setActive($('section'));
            $content().focus;
        }
    }

    function paneHist(from, to) {
        return function (e) {
            if (!from.length) return;
            let name = from.pop();
            if (isChordNavBlank(e)) {
                from.push(name);
                createPane();
            } else if (isChordNav(e)) {
                from.push(name);
                setActive($prevPanel);
                load(name);
                $content().focus();
            } else {
                hpush(to, $panel().dataset['name']);
            }
            load(name, true);
        }
    }

    function findOrCreatePane(name) {
        let p;
        $$('section').forEach(e => e.querySelector('.name').value === name && (p = e));
        if (!p) {
            p = createPane();
        }
        setActive(p);
        load(name);
        return p;
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Scheme interpreter

    const global = {};
    const arity = (fn, n) => (s, env) => {
        if (collect(cdr(s)).length !== n) throw new Error(`${asString(car(s))}: Wrong number of arguments`);
        return fn(s, env);
    }
    const primitive = {
        define: arity((s, env) => {
            return env[cadr(s)] = eval(env, cadr(cdr(s)));
        }, 2),
        quote: arity((s, env) => cadr(s), 1),
        car: arity((s, env) => {
            let rv = eval(env, cadr(s));
            if (rv === null) throw new Error('You cannot ask for the car of the empty list');
            else if (isAtom(rv)) throw new Error('You cannot ask for the car of an atom');
            return car(rv)
        }, 1),
        cdr: arity((s, env) => {
            let rv = eval(env, cadr(s));
            if (rv === null) throw new Error('You cannot ask for the cdr of the empty list');
            if (isAtom(rv)) throw new Error('You cannot ask for the cdr of an atom');
            return cdr(rv)
        }, 1),
        cons: arity((s, env) => {
            let r = eval(env, cadr(cdr(s)));
            if (!isList(r)) throw new Error('Second argument of cons must be a list');
            return cons(eval(env, cadr(s)), r);
        }, 2),
        'null?': arity((s, env) => {
            let r = eval(env, cadr(s));
            if (!isList(r)) throw new Error('null? is defined only for lists');
            return r === null;
        }, 1),
        'zero?': arity((s, env) => {
            let r = eval(env, cadr(s));
            if (!isAtom(r)) throw new Error('zero? is defined only for atoms');
            return r === 0;
        }, 1),
        'atom?': arity((s, env) => {
            return isAtom(eval(env, cadr(s)));
        }, 1),
        'number?': arity((s, env) => {
            return isNumber(eval(env, cadr(s)));
        }, 1),
        'eq?': arity((s, env) => {
            let l = eval(env, cadr(s));
            let r = eval(env, cadr(cdr(s)));
            if (!isAtom(l) || isNumber(l) || !isAtom(r) || isNumber(r)) throw new Error('eq? takes two non-numeric atoms');
            return l === r;
        }, 2),
        or: arity((s, env) => {
            return eval(env, cadr(s)) || eval(env, cadr(cdr(s)));
        }, 2),
        and: arity((s, env) => {
            return eval(env, cadr(s)) && eval(env, cadr(cdr(s)));
        }, 2),
        add1: arity((s, env) => eval(env, cadr(s)) + 1, 1),
        sub1: arity((s, env) => eval(env, cadr(s)) - 1, 1),
        lambda: arity((s, env) => {
            return {
                args: collect(cadr(s)), body: cadr(cdr(s)),
                env: Object.fromEntries(Object.entries(env))
            }
        }, 2),
        letrec: arity((s, env) => {
            let f = eval(env, car(cdr(car(cadr(s)))));
            f.env[car(car(car(cdr(s))))] = f;
            return eval(f.env, car(cdr(cdr(s))));
        }, 2),
        cond: (s, env) => {
            let b = collect(cdr(s));
            for (let i = 0; i < b.length; i++) {
                if (car(b[i]) === 'else' || eval(env, car(b[i])))
                    return eval(env, cadr(b[i]));
            }
        }
    }
    const cons = (car, cdr) => [car, cdr];
    const car = c => c[0];
    const cdr = c => c[1];
    const cadr = c => car(cdr(c));
    const isAtom = s => s !== null && !Array.isArray(s);
    const isList = s => Array.isArray(s) || s === null;
    const isNumber = s => typeof s === 'number';
    const parse = src => ast(src.replaceAll('(', ' ( ').replaceAll(')', ' ) ').replaceAll(/;.*$/gm, '').split(/\s/).filter(Boolean));
    const exec = src => eval(global, parse(src), true);

    function ast(tokens, d = {depth: 0}) {
        if (!tokens.length) {
            if (d.depth > 0) throw new Error('Unexpected EOF!');
            else return null;
        }
        let t = tokens.shift();
        if (t === ')') {
            if (d.depth-- === 0) throw new Error('Unexpected closing parenthesis');
            return null;
        } else if (t === '(') {
            d.depth++;
            return cons(ast(tokens, d), ast(tokens, d));
        } else if (t[0] === '#') {
            if (tokens.length) return cons(t[1] === 't', ast(tokens, d));
            return t[1] === 't';
        } else if (isNaN(t)) {
            if (tokens.length) return cons(t, ast(tokens, d));
            return t;
        }
        if (tokens.length) return cons(+t, ast(tokens, d));
        return +t;
    }

    function collect(s) {
        if (!s) return [];
        return [car(s), ...collect(cdr(s))];
    }

    function eval(env, s, isSrc) {
        if (s === null) throw new Error('Evaluating empty list');
        if (isAtom(s)) {
            if (isNaN(s)) {
                if (env[s] !== undefined) return env[s];
                else if (Object.keys(primitive).includes(s)) return s;
                throw new Error('Undefined variable ' + s);
            }
            return s;
        } else if (isSrc) {
            let rv = eval(env, car(s));
            if (cdr(s)) return eval(env, cdr(s), isSrc);
            return rv;
        }
        let proc = eval(env, car(s));
        if (Object.keys(primitive).includes(proc || car(s))) {
            return primitive[proc || car(s)](s, env)
        }
        try {
            let args = {};
            collect(cdr(s)).forEach((a, i) => {
                args[proc.args[i]] = eval(env, a);
            });
            return arity((_, env) => eval(env, proc.body), proc.args.length)(s, Object.assign({}, env, proc.env, args));
        } catch (e) {
            throw new Error(`${asString(car(s))}: ${e}`);
        }
    }

    function asString(s) {
        function build(s, acc = [], nl = true) {
            if (s === null) {
                acc.push('()');
                return acc;
            } else if (s.body) {
                acc.push('<proc (' + s.args.join(' ') + ')>');
                return acc;
            } else if (isAtom(s)) {
                acc.push(s);
                return acc;
            } else {
                nl && acc.push('(');
                build(s[0], acc, true);
                s[1] && build(s[1], acc, false);
                nl && acc.push(')');
            }
            return acc;
        }

        return build(s).join(' ').replaceAll('( ', '(').replaceAll(' )', ')');
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Listeners

    let $prevPanel;
    let $resize;
    let $hresize;

    function handleSearch(e) {
        e.preventDefault();
        e.stopPropagation();
        if (isChordNavBlank(e)) {
            navBlank(t$(e).value);
            closeSearch();
        } else if (isChordNav(e)) {
            if (!$content()) createPane();
            closeSearch();
            load(t$(e).value);
        } else {
            if (!$content()) return;
            closeSearch();
            if (!isStoreKey(t$(e).value)) {
                storeSet(t$(e).value, '');
                refresh();
            }
            write(t$(e).value);
        }
    }

    document.getElementById('app').innerHTML = `
 <datalist id="files"></datalist>
 <datalist id="globals"></datalist>
<table>
    <tr>
        <td colspan="2" class="menu" style="height: 0;">
            <span class="new">new</span><span class="ls">ls</span><span class="mv">mv</span><span class="del">del</span><span class="save">save</span><span class="run">run</span><span class="settings">import</span><span class="export">export</span><span class="reset">reset</span>
        </td>
    </tr>
    <tr id="settings">
        <td colspan="2" class="menu" style="height: 0;">
            <input type="file" id="import" value="">
        </td>
    </tr>
    <tr>
        <td class="col">
            <div class="active column"></div>
            <div class="resize"></div>
        </td>
        <td>
            <div class="column"></div>
        </td>
    </tr>
</table>
<input list="files" spellcheck="false" id="search" autocomplete="off"/>
    `;

    document.addEventListener('mousedown', function (e) {
        if (hasCls(t$(e), 'resize')) {
            e.preventDefault();
            $resize = closest$(e, 'td');
        } else if (hasCls(t$(e), 'h-resize')) {
            e.preventDefault();
            $hresize = closest$(e, 'section').querySelector('article');
        }
        $prevPanel = $panel() || $prevPanel;
        let section = closest$(e, 'section');
        section && setActive(section);
        let column = closest$(e, '.column');
        if (column && (!e.altKey && !e.metaKey && !e.ctrlKey)) {
            togCls('active', '.column', column);
        }
    });

    document.addEventListener('mousemove', function (e) {
        if ($resize) $resize.width = e.clientX;
        else if ($hresize) {
            const $sib = $hresize.closest('section').nextSibling;
            const rect = $hresize.getBoundingClientRect();
            let h = e.y - rect.top < 0 ? 0 : e.y - rect.top;
            let diff = h - rect.height;
            if ($sib && $sib.nextSibling) {
                const $sArt = $sib.querySelector('article');
                const sRect = $sArt.getBoundingClientRect();
                if (sRect.height - diff <= 0) {
                    $hresize.style.height = `${+$hresize.style.height.split('px')[0] + sRect.height}px`;
                    $sArt.style.height = `0px`;
                    return;
                }
                $sArt.style.height = `${sRect.height - diff}px`;
            }
            $hresize.style.height = `${h}px`;
        }
    })

    document.addEventListener('mouseup', () => {
        $resize = null;
        $hresize = null;
    });

    document.addEventListener('click', function (e) {
        // @formatter:off
        switch (t$(e).classList[0]) {
            case 'new': menuNew(); return;
            case 'ls': menuLs(); return;
            case 'reset': menuReset(); return;
            case 'save': menuSave(); return;
            case 'mv': menuMv(); return;
            case 'del': menuDel(); return;
            case 'settings': menuSettings(); return;
            case 'run': menuRun(); return;
            case 'export': menuExport(); return;
            case 'close': paneClose(e); return;
            case 'max': paneMax(e); return;
            case 'move': paneMove(e); return;
            case 'back': paneHist(hist().back, hist().forward)(e); return;
            case 'forward': paneHist(hist().forward, hist().back)(e); return;
        }
        // @formatter:on
        if (isChordNavBlank(e) && e.button === 0) {
            link($content()) && navBlank(link($content()));
        } else if (isChordNav(e) && e.button === 0) {
            let name = link($content());
            if (name) {
                setActive($prevPanel);
                load(name);
                $content().focus();
            }
        }
    });

    window.addEventListener('beforeunload', e => {
        if ($('.dirty')) {
            e.preventDefault();
            e.returnValue = true;
        }
    })

    function offset(text) {
        const stack = [];
        let o = 0;
        text.split('').forEach((c, i) => {
            if (c === '(') stack.push({spaces: i - o, total: i});
            else if (c === ')') stack.pop();
            else if (c === '\n') o = i + 1;
        });
        return stack.pop() || 0;
    }

    const move = (e, pos) => e.setSelectionRange(pos, pos);
    const caret = e => e.value.substring(0, e.selectionStart);
    let last;

    document.addEventListener('keydown', function (e) {
        if (e.key === 'Enter') {
            if (t$(e).id === 'search') {
                handleSearch(e);
            } else if (isChordNav(e)) {
                $search().value = '';
                $search().classList.add('searching');
                $search().focus();
            } else if (hasCls(e.target, 'name')) {
                load($name().value);
            } else {
                e.preventDefault();
                let s = offset(caret(t$(e)));
                if (s.spaces === undefined) write('\n')
                else write('\n' + Array(s.spaces + 3).join(' '));
            }
        } else if (e.key === 'Escape' && e.target.id === 'search') {
            $search().classList.remove('searching');
            $content().focus();
        } else if (t$(e).classList[0] === 'content') {
            const textarea = t$(e);
            if (e.key === '(') {
                e.preventDefault();
                write('()');
                move(textarea, textarea.selectionStart - 1);
            }
            if (e.key === '\'') {
                e.preventDefault();
                write('(quote )');
                move(textarea, textarea.selectionStart - 1);
            } else if (e.key === 'Tab') {
                e.preventDefault();
                let c = caret(textarea);
                if (c[c.length - 1] === '(') {
                    return move(textarea, last);
                }
                let o = offset(c);
                if (o.spaces === undefined) return;
                last = c.length;
                move(textarea, o.total + 1);
            } else if (e.key === 'r' && (e.metaKey || e.ctrlKey)) {
                runPane(textarea.value);
            }
        }
    });

    document.getElementById('import').addEventListener('change', function (e) {
        const file = e.target.files[0];
        const r = new FileReader();
        r.onload = e => {
            let data = JSON.parse('' + e.target.result);
            Object.keys(data).forEach(k => storeSet(k, data[k]));
            refresh();
        }
        r.readAsText(file);
        refresh();
    });

    document.addEventListener('keyup', function (e) {
        if (t$(e).className === 'content') {
            let $parse = closest$(e, 'section').querySelector('.parse');
            try {
                parse($content().value);
                $parse.innerHTML = '';
            } catch (e) {
                $parse.innerHTML = e;
            }
        }
    })

    refresh();
    createPane();
    load((location.hash && location.hash.substring(1)) || 'main');
</script>
</body>
</html>