       hide: -> $el.hide()
       is_clean: -> editor.getValue() is '' and not @.used
       run: ->
-        context.used = true
-        context.output_cell?.$el.remove()
-        context.output_cell = run context, editor.getValue()
-        context.input_number = notebook.input_number++
-        context.$el.attr 'data-cell-number', context.input_number
-
-    editor.lead_cell = context
+        cell.used = true
+        cell.output_cell?.$el.remove()
+        cell.output_cell = run cell, editor.getValue()
+        cell.input_number = notebook.input_number++
+        cell.$el.attr 'data-cell-number', cell.input_number
+
+    editor.lead_cell = cell
 
     error_marks = []
 

    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

      failure: ->
        scroll_to_result $top
        ignore
      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()
