def edit():
    """ File edit handler """
    # Load json only if it is ajax edited...
    app = get_app(request.vars.app)
    app_path = apath(app, r=request)
    preferences={'theme':'web2py', 'editor': 'default', 'closetag': 'true', 'codefolding': 'false', 'tabwidth':'4', 'indentwithtabs':'false', 'linenumbers':'true', 'highlightline':'true'}
    config = Config(os.path.join(request.folder, 'settings.cfg'),
                    section='editor', default_values={})
    preferences.update(config.read())

    if not(request.ajax) and not(is_mobile):
        # return the scaffolding, the rest will be through ajax requests
        response.title = T('Editing %s') % app
        return response.render ('default/edit.html', dict(app=app, editor_settings=preferences))

    # show settings tab and save prefernces
    if 'settings' in request.vars:
        if request.post_vars:        #save new preferences
            post_vars = request.post_vars.items()
            # Since unchecked checkbox are not serialized, we must set them as false by hand to store the correct preference in the settings 
            post_vars+= [(opt, 'false') for opt in preferences if opt not in request.post_vars ]
            if config.save(post_vars):
                response.headers["web2py-component-flash"] = T('Preferences saved correctly')
            else:
                response.headers["web2py-component-flash"] = T('Preferences saved on session only')
            response.headers["web2py-component-command"] = "update_editor(%s);$('a[href=#editor_settings] button.close').click();" % response.json(config.read())
            return
        else:
            details = {'realfilename':'settings', 'filename':'settings', 'id':'editor_settings', 'force': False}
            details['plain_html'] = response.render('default/editor_settings.html', {'editor_settings':preferences})
            return response.json(details)

    """ File edit handler """
    # Load json only if it is ajax edited...
    app = get_app(request.vars.app)
    filename = '/'.join(request.args)
    realfilename = request.args[-1]
    if request.vars.app:
        path = abspath(filename)
    else:
        path = apath(filename, r=request)
    # Try to discover the file type
    if filename[-3:] == '.py':
        filetype = 'python'
    elif filename[-5:] == '.html':
        filetype = 'html'
    elif filename[-5:] == '.load':
        filetype = 'html'
    elif filename[-4:] == '.css':
        filetype = 'css'
    elif filename[-3:] == '.js':
        filetype = 'javascript'
    else:
        filetype = 'html'

    # ## check if file is not there
    if ('revert' in request.vars) and os.path.exists(path + '.bak'):
        try:
            data = safe_read(path + '.bak')
            data1 = safe_read(path)
        except IOError:
            session.flash = T('Invalid action')
            if 'from_ajax' in request.vars:
                return response.json({'error': str(T('Invalid action'))})
            else:
                redirect(URL('site'))

        safe_write(path, data)
        file_hash = md5_hash(data)
        saved_on = time.ctime(os.stat(path)[stat.ST_MTIME])
        safe_write(path + '.bak', data1)
        response.flash = T('file "%s" of %s restored', (filename, saved_on))
    else:
        try:
            data = safe_read(path)
        except IOError:
            session.flash = T('Invalid action')
            if 'from_ajax' in request.vars:
                return response.json({'error': str(T('Invalid action'))})
            else:
                redirect(URL('site'))

        lineno_old = count_lines(data)
        file_hash = md5_hash(data)
        saved_on = time.ctime(os.stat(path)[stat.ST_MTIME])

        if request.vars.file_hash and request.vars.file_hash != file_hash:
            session.flash = T('file changed on disk')
            data = request.vars.data.replace('\r\n', '\n').strip() + '\n'
            safe_write(path + '.1', data)
            if 'from_ajax' in request.vars:
                return response.json({'error': str(T('file changed on disk')),
                                      'redirect': URL('resolve',
                                                      args=request.args)})
            else:
                redirect(URL('resolve', args=request.args))
        elif request.vars.data:
            safe_write(path + '.bak', data)
            data = request.vars.data.replace('\r\n', '\n').strip() + '\n'
            safe_write(path, data)
            lineno_new = count_lines(data)
            log_progress(
                app, 'EDIT', filename, progress=lineno_new - lineno_old)
            file_hash = md5_hash(data)
            saved_on = time.ctime(os.stat(path)[stat.ST_MTIME])
            response.flash = T('file saved on %s', saved_on)

    data_or_revert = (request.vars.data or request.vars.revert)

    # Check compile errors
    highlight = None
    if filetype == 'python' and request.vars.data:
        import _ast
        try:
            code = request.vars.data.rstrip().replace('\r\n', '\n') + '\n'
            compile(code, path, "exec", _ast.PyCF_ONLY_AST)
        except Exception, e:
            # offset calculation is only used for textarea (start/stop)
            start = sum([len(line) + 1 for l, line
                         in enumerate(request.vars.data.split("\n"))
                         if l < e.lineno - 1])
            if e.text and e.offset:
                offset = e.offset - (len(e.text) - len(
                    e.text.splitlines()[-1]))
            else:
                offset = 0
            highlight = {'start': start, 'end': start +
                         offset + 1, 'lineno': e.lineno, 'offset': offset}
            try:
                ex_name = e.__class__.__name__
            except:
                ex_name = 'unknown exception!'
            response.flash = DIV(T('failed to compile file because:'), BR(),
                                 B(ex_name), ' ' + T('at line %s', e.lineno),
                                 offset and ' ' +
                                 T('at char %s', offset) or '',
                                 PRE(str(e)))
    if data_or_revert and request.args[1] == 'modules':
        # Lets try to reload the modules
        try:
            mopath = '.'.join(request.args[2:])[:-3]
            exec 'import applications.%s.modules.%s' % (
                request.args[0], mopath)
            reload(sys.modules['applications.%s.modules.%s'
                               % (request.args[0], mopath)])
        except Exception, e:
            response.flash = DIV(
                T('failed to reload module because:'), PRE(str(e)))

    edit_controller = None
    editviewlinks = None
    view_link = None
    if filetype == 'html' and len(request.args) >= 3:
        cfilename = os.path.join(request.args[0], 'controllers',
                                 request.args[2] + '.py')
        if os.path.exists(apath(cfilename, r=request)):
            edit_controller = URL('edit', args=[cfilename.replace(os.sep, "/")])
            view = request.args[3].replace('.html', '')
            view_link = URL(request.args[0], request.args[2], view)
    elif filetype == 'python' and request.args[1] == 'controllers':
        ## it's a controller file.
        ## Create links to all of the associated view files.
        app = get_app()
        viewname = os.path.splitext(request.args[2])[0]
        viewpath = os.path.join(app, 'views', viewname)
        aviewpath = apath(viewpath, r=request)
        viewlist = []
        if os.path.exists(aviewpath):
            if os.path.isdir(aviewpath):
                viewlist = glob(os.path.join(aviewpath, '*.html'))
        elif os.path.exists(aviewpath + '.html'):
            viewlist.append(aviewpath + '.html')
        if len(viewlist):
            editviewlinks = []
            for v in viewlist:
                vf = os.path.split(v)[-1]
                vargs = "/".join([viewpath.replace(os.sep, "/"), vf])
                editviewlinks.append(A(vf.split(".")[0],
                                       _class="editor_filelink",
                                       _href=URL('edit', args=[vargs])))

    if len(request.args) > 2 and request.args[1] == 'controllers':
        controller = (request.args[2])[:-3]
        functions = find_exposed_functions(data)
    else:
        (controller, functions) = (None, None)

    if 'from_ajax' in request.vars:
        return response.json({'file_hash': file_hash, 'saved_on': saved_on, 'functions': functions, 'controller': controller, 'application': request.args[0], 'highlight': highlight})
    else:
        file_details = dict(app=request.args[0],
                    lineno=request.vars.lineno or 1,
                    editor_settings=preferences,
                    filename=filename,
                    realfilename=realfilename,
                    filetype=filetype,
                    data=data,
                    edit_controller=edit_controller,
                    file_hash=file_hash,
                    saved_on=saved_on,
                    controller=controller,
                    functions=functions,
                    view_link=view_link,
                    editviewlinks=editviewlinks,
                    id=IS_SLUG()(filename)[0],
                    force= True if (request.vars.restore or 
                                    request.vars.revert) else False)
        plain_html = response.render('default/edit_js.html', file_details)
        file_details['plain_html'] = plain_html
        if is_mobile:
            return response.render('default.mobile/edit.html', 
                                   file_details, editor_settings=preferences)
        else:
            return response.json(file_details)
dataset/ETHPy150Open uwdata/termite-data-server/web2py/applications-original/admin/controllers/default.py/edit/original