Stranger Than Fiction
(2006)

Short version:
Harold Crick gets the girl and doesn't die.

Longer version:
Harold Crick (Will Ferrel) realizes that he is a character in a story, and overhears his author (Kay Eiffel, played by Emma Thompson) narrating that he's going to die. He manages to track down Eiffel based on her IRS records, just as she manages to overcome her writer's block and write down his death scene. But it seems that until she types it on her typewriter, it won't happen to Harlod. Harold shows up at her door, and, distraught at the revelation that he's a real person, she gives him the manuscript (including the handwritten death scene). Harold then gives the manuscript to Professor Hilbert (Dustin Hoffman), who reads it and tells him that it is a masterpiece, and that the death in the end is necessary. He tries to convince Harold that he's going to die some day anyway, and this way at least his death will be very meaningful. Harold then decides to read the manuscript to himself. He finishes reading it, and agrees with Hilbert. He goes back to Eiffel, hands it back, and tells her to type the scene.

We then see him wrapping up loose ends in his life. He arranges that his friend Dave can fulfill his lifelong dream of going to space camp. He finishes all the work he has left. He tells his girlfriend Ana (Maggie Gyllenhaal) how much he loves her, and that she can avoid going to jail for tax evasion by deducting all the free food she gives the homeless. The next morning, he gets up and goes to work. The narration then resumes, saying that because of his wristwatch (which kept being mentioned in the narrative) briefly stopping a few days earlier, he had the wrong time, and instead of arriving to the bus at the last moment, he arrives there early. Just in time to see a young boy fall of his bike in the bus's path. He jumps and pushes the boy out of the way, and is hit by the bus himself.

At that very moment, Eiffel is writing the death scene. She stops halfway in the middle of writing "Harold was dead". We then see that Harold wakes up, massively injured but alive. A shard from his wristwatch somehow blocked his artery and prevented massive bloodloss. It will take him several months, but he will be ok, though the shard can never be removed. Ana shows up and it is clear that they will live happily ever after togther. We then see Eiffel visiting prof. Hilbert and giving him the revised manuscript. He reads it and tells her it's good, but not as good as the original ending. She says that she's fine with that, and that she realized that Harold's willingness to save the boy even though he knew that he'll die meant that he was worth keeping alive.

Thanks Eytan!