<style>
    .button.toolbutton{
        margin: 0 3px 0 0 ;
        padding: 5px;
        font-variant: none;
    }
</style>
<div id="{{ widget.attrs.id }}_container">
<div style="margin:10px;">
    <a id="undo" class="button toolbutton" href="javascript:false"> undo </a>
    <a id="redo" class="button toolbutton" href="javascript:false"> redo </a>
    <a id="expand" data-action="expand()" class="button toolbutton" href="javascript:false"> fullscreen </a>
</div>
<textarea name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}>
{% if widget.value %}{{ widget.value }}{% endif %}</textarea>
</div>
<script>
    (function ($) {
        var editor;

        var handleSideBar = function(){
            if (editor.getOption("fullScreen")){
                $("#toggle-nav-sidebar").hide();
            }else{
                $("#toggle-nav-sidebar").show();
            }
        }
        var expand = function(){
            editor.setOption('fullScreen', true);
            editor.focus();
            handleSideBar();
        };
        $(".toolbutton").on("click", function () {
            var expression = $(this).data('action');
            if ( !expression ){
                var cmd = $(this).attr('id')
                expression = 'doc=editor.getDoc(); doc.'+ cmd + '()';
            }
            eval(expression);
        });

         $(document).ready(function () {
            editor = CodeMirror.fromTextArea(document.getElementById('{{widget.attrs.id}}'), {
                mode: "python",
                lineNumbers: true,
                lineWrapping: true,
                indentUnit: 4,
                styleActiveLine: true,
                theme: "{{ widget.attrs.theme }}",
                foldGutter: true,
                gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
                extraKeys: {
                    "F3": function (cm) {
                        cm.foldCode(cm.getCursor());
                    },
                    "F11": function (cm) {
                        cm.setOption("fullScreen", !cm.getOption("fullScreen"));
                        handleSideBar();
                    },
                    "Esc": function (cm) {
                        if (cm.getOption("fullScreen")) {
                            cm.setOption("fullScreen", false);
                        }
                        handleSideBar();
                    }
                }
            });
            editor.execCommand("unfoldAll");
            editor.foldCode(CodeMirror.Pos(0, 0));
            $('#{{widget.attrs.id}}').data('CodeMirror', editor);
         });
    })(django.jQuery);

</script>
