+ // If the last page is ragged, set its force to zero. This way, we will leave
+ // the last page half-empty rather than trying to balance things out
+ // (which only makes sense in non-ragged situations).
+ if (line == lines_.size () - 1 && ragged && last && space.force_ > 0)
+ space.force_ = 0;
+
+ Real demerits = space.force_ * space.force_;
+
+ // Clamp the demerits at BAD_SPACING_PENALTY, even if the page
+ // is overfull. This ensures that TERRIBLE_SPACING_PENALTY takes
+ // precedence over overfull pages.
+ demerits = min (demerits, BAD_SPACING_PENALTY);
+ demerits += (prev ? prev->demerits_ : 0);
+
+ Real penalty = breaker_->line_count_penalty (line_count);
+ if (page_start > 0)
+ penalty += lines_[page_start-1].page_penalty_
+ + (page % 2 == 0) ? lines_[page_start-1].turn_penalty_ : 0;
+
+ /* Deal with widow/orphan lines */
+ /* Last line of paragraph is first line on the new page */
+ if ((page_start > 0) &&
+ (page_start < lines_.size ()) &&
+ (lines_[page_start].last_markup_line_))
+ penalty += breaker_->orphan_penalty ();
+ /* First line of paragraph is last line on the previous page */
+ if ((page_start > 0) &&
+ (page_start < lines_.size ()) &&
+ (lines_[page_start-1].first_markup_line_))
+ penalty += breaker_->orphan_penalty ();
+
+ demerits += penalty;
+ if (demerits < cur.demerits_ || page_start == line)