Internals of the
| |
The highr package is based on the function |
|
The first step is to filter out the rows that we do not need: |
|
There is a column |
|
These command data frames are connected to the tokens in the R code via their row names: |
|
Now we know how to wrap up the R tokens. The next big question is how to
restore the white spaces in the source code, since they were not directly
available in the parsed data, but the parsed data contains column numbers,
and we can derive the positions of white spaces from them. For example,
| |
A small trick is used to fill in the gaps of white spaces: |
|
Now the two columns indicate the starting and ending positions of spaces, and we can easily figure out how many white spaces are needed for each row: |
|
So we have successfully restored the white spaces in the source code. Let's paste all pieces together (suppose we highlight for LaTeX): |
|
So far so simple. That is one line of code, after all. A next challenge comes when there are multiple lines, and a token spans across multiple lines: |
|
Take a look at the third row. It says that the character string starts from line 1, and ends on line 2. In this case, we just pretend as if everything on line 1 were on line 2. Then for each line, we append the missing spaces and apply markup commands to text symbols. |
|
Do not worry about the column Why do we need to highlight line by line instead of applying highlighting commands to all text symbols (a.k.a vectorization)? Well, the margin of this paper is too small to write down the answer. |