   setUpEditor "edit-chapter-heading-#{chapterId}", chapter.heading, (mutations, node) ->
     sync.getCurrentDocId().then (currentDocId) ->
       sync.getDoc(currentDocId).then (doc) ->
-        for chapter in doc.chapters
-          if chapter.id == targetChapterId
-            chapter.heading = node.textContent
+        for currentChapter in doc.chapters
+          if currentChapter.id == chapterId
+            currentChapter.heading = node.textContent
 
         sync.saveDoc(doc).then -> app.ports.loadAsCurrentDoc.send doc
 

          sync.saveSnapshot({id: chapter.snapshotId, html: node.innerHTML})
            .then (->) # TODO send a word count update


saveHtmlAndLoadDoc = (html) ->
  sync.saveFreshDoc(DocImport.docFromHtml html)
    .then app.ports.loadAsCurrentDoc.send

showFileChooser = ->
  new Promise (resolve, reject) ->


setUpEditor = (id, html, onMutate) ->
  whenPresent (-> document.getElementById id),
    ((elem) -> getEditorFor(elem, onMutate).writeHtml html, true),
    ((err) -> console.error "Could not write after 10,000 attempts:", id, html),
    10000

