mozilla/pdf.js — pull request #5545 by speedplane (2014-12-16 17:32:05+00:00)
Title: Improved Text Selection By Padding Text Elements

## The Problem
Text selection in pdf.js does not work so well. If while dragging, your cursor is not directly on top of a text element, then you get unexpected results. This occurs with nearly all examples, including [the tracemonkey example](http://mozilla.github.io/pdf.js/web/viewer.html). Try starting a selection, then dragging the mouse to a blank whitespace area beneath the initial selection. You'll see the selection gets reversed. If you keep moving your mouse, it flickers and is generally a horrible experience. I'm not the first to report this, it is the subject of at least #4629 and #4843.

## The Solution
The reason why selection doesn't work is because most browsers rely on padding between text to detect text flow. The solution, therefore, is to increase padding of each text element so that each element runs right up next to the next element.

### Other Solutions
Adding padding to each text element was recognized as a possible solution by @mitar in #4843. However, in #4843, the suggested solution was relatively complex, which included modifying the padding dynamically whenever a mouse moves. It was also written in CoffeeScript for a completely separate viewer and porting it seemed difficult.

### This Solution
In this solution, the padding is calculated when the text elements are added. For each added text element, we find the nearest neighbor to the right that is on the same line. We then set the `padding-right` of the text element to that distance. Similarly, for `padding-bottom` we find the next line that is underneath the text element, and set the padding to the difference between lines. Setting `padding-bottom` is especially helpful for PDFs that are double spaced (lots of space between lines).

The solution isn't all milk and honey though. The computation is `O(N^2)`, which could be bad for complex PDFs. There are [fancier algorithms to find the nearest neighbor](http://en.wikipedia.org/wiki/Nearest_neighbor_search), but for now, for each text element, we look at every other text element to see if it's nearest.