{{def shortcut(combo, description):
    return XML('<li><span class="teletype-text">%s</span><span>%s</span></li>' % (combo, description))
}}

<form action="{{=URL('edit', args=filename)}}" method="post" name="editform" id="editform" class="form-inline row-fluid">
<div class="span12 well well-small">
    <label class="">{{=T('Save file:')}}</label>
    <a value="save" title="{{=T('Save file: %s', filename)}}" href="#" name="save" onclick="return doClickSave();" class="icon saveicon" style="background-image: -webkit-linear-gradient(top,white,#E6E6E6);">{{=IMG(_src=URL('static', 'images/save_icon.png'), _alt=T('Save'))}}</a>
    <label class="">{{=T('Saved file hash:')}}</label>
    <input type="input" name="file_hash" value="{{=file_hash}}" class="input-long uneditable-input" readonly="readonly"/>
    <label>{{=T('Last saved on:')}}</label>
    <input type="input" name="saved_on" value="{{=saved_on}}" class="input-normal uneditable-input" readonly="readonly"/>
{{if filetype=='python':}}
      {{=A(SPAN(T('toggle breakpoint')),
           _value="breakpoint", _name="breakpoint",
           _onclick="return doToggleBreakpoint('%s','%s://%s%s',null);" % (filename,
                request.env['wsgi_url_scheme'], request.env['http_host'],
                URL(c='debug', f='toggle_breakpoint')),
           _class="button special btn btn-inverse")}}
{{pass}}
{{if view_link:}}
    {{=button(view_link, T('try view'))}}
{{pass}}
{{if functions or edit_controller:}}
    <p class="formfield">
    {{if functions:}}
        <span style="text-align:left;" class="exposed">
        {{=B(T('exposes:'))}} {{=XML(b', '.join([A(f,_target="_blank", _href=URL(a=app,c=controller,f=f)).xml() for f in functions]))}}
        </span>
        {{if editviewlinks:}}<br/>
            {{=B(T('edit views:'))}}
            {{=XML(b', '.join([v.xml() for v in editviewlinks]))}}
        {{pass}}
    {{pass}}
    {{if edit_controller:}}
        {{=B(T('edit controller:'))}}
        {{=A(request.args[2]+'.py', _class="editor_filelink", _target="_blank", _href=edit_controller)}}
    {{pass}}
    </p>
{{pass}}
</div>

    <textarea style=" height:100%; direction:ltr;" id="textarea_{{=id}}" class="input-block-level" name="data" >{{=data}}</textarea>
    <script>
    var editor = CodeMirror.fromTextArea(document.getElementById("textarea_{{=id}}"),{
    {{if filetype=='html':}}
        mode : "text/html",
        profile: 'xhtml',
    {{else:}}
        mode: { name: '{{=filetype}}'{{if filetype=='python':}},version: 2,singleLineStringErrors: false, {{pass}} },
    {{pass}}
        lineNumbers: {{=editor_settings['linenumbers']}},
        indentUnit: {{=editor_settings['tabwidth']}},
        indentWithTabs: {{=editor_settings['indentwithtabs']}},
        tabSize: {{=editor_settings['tabwidth']}},
        styleActiveLine: {{=editor_settings['highlightline']}},
        autoCloseTags: {{=editor_settings['closetag']}},
        theme: "{{=editor_settings['theme']}}",
        lineWrapping: true,
        foldGutter: {{=editor_settings['codefolding']}},
        gutters: ["CodeMirror-linenumbers", "breakpoints", "CodeMirror-foldgutter"],
        keyMap: "{{=editor_settings['editor']}}",
        matchBrackets: true,
        autofocus: false,
        height: "350px",
        showTrailingSpace: true
    });

    editor.on("gutterClick", function(cm, n, gutter) {
        if (gutter !== "breakpoints" ) return;
        var info = cm.lineInfo(n);
        cm.setGutterMarker(n, "breakpoints", info.gutterMarkers ? null : makeMarker());
        sel = {start: n, end: n, data: ''};
        doToggleBreakpoint({{=XML("'%s','%s://%s%s'" % (filename,
                             request.env['wsgi_url_scheme'], request.env['http_host'],
                             URL(c='debug', f='toggle_breakpoint')))}}, sel);
    });
    function makeMarker() {
        var marker = document.createElement("div");
        marker.style.color = "#822";
        marker.innerHTML = "●";
        marker.className = "breakpoint";
        return marker;
    }

    {{if filetype in ('html', 'javascript', 'css'):}}
        // must be here or break emmet/zencoding 
        CodeMirror.defaults.extraKeys["Ctrl-S"] =
            function(instance) {
                doClickSave();};
        CodeMirror.defaults.extraKeys["Tab"] = "indentMore";
        CodeMirror.defaults.extraKeys["Ctrl-F11"] = function(cm) {
            cm.setOption("fullScreen", !cm.getOption("fullScreen"));
        },
        CodeMirror.defaults.extraKeys["Shift-Esc"] = function(cm) {
            if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
        }
    {{pass}}
    {{if filetype=='python':}}
        // must be here or break emmet/zencoding for python
        CodeMirror.defaults.extraKeys["Ctrl-S"] =
            function(instance) {
                doClickSave();};
        CodeMirror.defaults.extraKeys["Ctrl-Space"] = "autocomplete";
        CodeMirror.defaults.extraKeys["Tab"] = "indentMore";
        CodeMirror.defaults.extraKeys["Shift-Tab"] = "indentLess";
        CodeMirror.defaults.extraKeys["Ctrl-F11"] = function(cm) {
	        cm.setOption("fullScreen", !cm.getOption("fullScreen"));
	    },
	    CodeMirror.defaults.extraKeys["Shift-Esc"] = function(cm) {
	        if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
	    }
        //for autocomplete
        CodeMirror.commands.autocomplete = function(cm) {
            CodeMirror.showHint(cm, CodeMirror.pythonHint);
        }
    {{pass}}
    CodeMirror.defaults.extraKeys["Ctrl-/"] = "toggleComment";
    store_changes_function = function(instance, changeObj) {
        jQuery(instance).data('saved', false);
        instance.off("change", store_changes_function);
    }
    editor.on("change", store_changes_function);
        // save the editor as textarea data attribute
        jQuery("#{{=id}} textarea").data('editor', editor);
        var hlLine = editor.addLineClass(0, "background", "activeline");
        window.mirror = editor; 	//backward compatibility
        set_font(editor, current_font_incr);
        doListBreakpoints({{=XML("'%s','%s://%s%s'" % (filename,
                request.env['wsgi_url_scheme'], request.env['http_host'],
                URL(c='debug', f='list_breakpoints')))}}, editor);

    // TODO move it in a separated file
    CodeMirror.defineExtension("centerOnCursor", function(limit) {
        var coords = this.cursorCoords(null, "local");
        if (this.getScrollerElement().clientHeight === 0 && limit !== 10) {
            if (limit === undefined) limit = 1;
            else limit += 1;
            editor = this;
            setTimeout(function() {editor.centerOnCursor()}, 100);
            return;
        }
        clientHeight = (this.getScrollerElement().clientHeight / 2)
        this.scrollTo(null, (coords.top + coords.bottom)/2 - 10);
    });
    CodeMirror.commands.save = function () {
        doClickSave();
    }
    </script>

    <div class="editor-bar-bottom" style="margin-top:9px;">
        <a class="editbutton btn" href="{{=URL('edit', args=request.args, vars={'restore':True})}}" id="restore">{{=T('restore')}}</a>
        {{=T('currently saved or')}}
        <a class="editbutton btn" href="{{=URL('edit', args=request.args, vars={'revert':True})}}" id="revert">{{=T('revert')}}</a>
        {{=T('to  previous version.')}}
    </div>
    <br/>
  </form>
