simonw / datasette-ripgrep

Web interface for searching your code using ripgrep, built as a Datasette plugin
https://ripgrep.datasette.io
Apache License 2.0
72 stars 1 forks source link

Search results should link to line in code #4

Closed simonw closed 3 years ago

simonw commented 3 years ago

You should be able to click the line number in a search result to view the line in context of the rest of the source code.

simonw commented 3 years ago

I'm going to do this by implementing a /-/ripgrep/view/path/to/file.txt#L150 URL scheme, serving content from the configured "path".

simonw commented 3 years ago

Useful pattern for CSS line numbers, inspired by https://www.sylvaindurand.org/using-css-to-add-line-numbering/

<style>
pre{
    counter-reset: line;
}
code{
    counter-increment: line;
}
code:before{
    content: counter(line);
    display: inline-block;
    width: 2em;
    -webkit-user-select: none;
    color: #666;
}
</style>

<pre>
<code>Line one</code>
<code>Line one</code>
<code>Line one</code>
<code>Line one</code>
<code>Line one</code>
<code>Line one</code>
<code>Line one</code>
<code>Line one</code>
<code>Line one</code>
<code>Line one</code>
<code>Line one</code>
<code>Line one</code>
<code>Line one</code>
<code>Line one</code>
<code>Line one</code>
<code>Line one</code>
</pre>
simonw commented 3 years ago

That width: 2em should be a number of ems equal to the width of the highest line number. Even better, use ch measure.

simonw commented 3 years ago

... except I need to also include id= attributes so I can link to lines - so those numbers should be embedded in the template, not generated by a CSS counter.

{% block extra_head %}
<style>
code:before {
    content: attr(data-line);
    display: inline-block;
    width: {{ widest_line_number + 1.5 }}ch;
    -webkit-user-select: none;
    color: #666;
}
</style>    
{% endblock %}

{% block content %}
<pre>{% for i, line in lines -%}
<code id="L{{ i + 1 }}" data-line="{{ i + 1 }}">{{ line if line else "&nbsp;"|safe }}</code>
{% endfor %}</pre>
simonw commented 3 years ago

Need to be sure this is protected against path traversal attacks, so you can only view files that are within the path directory hierarchy.

simonw commented 3 years ago

Demo: https://ripgrep.datasette.io/-/ripgrep/view/datasette-allow-permissions-debug/setup.py#L33

simonw commented 3 years ago

That last commit should not have referenced this issue.