       failure: ->
         scroll_to_result $top
         ignore
-      set_code: (code) -> add_context notebook, code
+      set_code: (code) ->
+        cell = add_input_cell notebook, code: code, after: input_cell
+        add_context notebook, code
       run: (code) -> run_in_available_context notebook, code
       clear_output: -> clear_notebook notebook
       previously_run: -> input_cell_at_offset(input_cell, -1).editor.getValue()

    notebook.$document.empty()
    notebook.cells.length = 0

  input_cell_at_offset = (cell, offset) ->
    index = cell.notebook.cells.indexOf cell
    cell.notebook.cells[index + offset]

  get_available_input_cell = (notebook) ->
    last = notebook.cells[notebook.cells.length - 1]
    if last?.is_clean()
      return last
    else
      return null

  remove_cell = (cell) ->
    index = cell.notebook.cells.indexOf cell
    cell.$el.remove()
    cell.notebook.cells.splice index, 1

  add_context = (notebook, code='') ->
    cell = get_available_input_cell notebook
    if cell?
      cell.editor.setValue code
    else
      cell = create_input_cell notebook, code
      notebook.$document.append cell.$el
      cell.rendered()
      notebook.cells.push cell

    {editor} = cell
    editor.focus()
    editor.setCursor(line: editor.lineCount() - 1)
    cell

  run_in_available_context = (notebook, code) ->
    add_context(notebook, code).run()
    add_context notebook

  # Add an input cell above the last input cell
  run_in_info_context = (current_cell, code) ->
    cell = create_input_cell current_cell.notebook, code
    current_cell.$el.before cell.$el
    index = notebook.cells.indexOf cell
    cell.rendered()
    current_cell.notebook.cells.splice index, 0, cell
    cell.run code

  create_input_cell = (notebook, code) ->
    $el = $ '<div class="cell input"/>'
    $code = $ '<div class="code"/>'
    $el.append $code

    editor = CodeMirror $code.get(0),
      value: code
      mode: 'coffeescript'
      keyMap: 'lead'
      tabSize: 2
      viewportMargin: Infinity
      gutters: ['error']

    context =
      notebook: notebook
      used: false
      editor: editor


  graphite.load_docs()

  forwards = +1
  backwards = -1

  is_input = (cell) -> cell.type is 'input'
  is_output = (cell) -> cell.type is 'output'
  visible = (cell) -> cell.visible

  init_codemirror = ->
    CodeMirror.keyMap.lead = ed.key_map
    $.extend CodeMirror.commands, ed.commands
