Thank you for reporting this, and for the recipe for reproducing this important bug in Emacs. I installed the attached patches into the GNU Emacs master to fix the problem. The 1st patch doesn't actually fix the bug, but it fixes some related ones. The 2nd patch fixes the bug -- at least, it worked for me on your test case. I generated the 2nd patch with "diff -b" so its indenting won't match the source code; you can pick up the full gory details in savannah git master, around commit ab27722721afca4647a7eec0933ac9209e0eac30.