Sublocator v0.2.0 Sublocator View Source

An Elixir library for identifying the location(s) of a pattern in a given string.

Using Sublocator.locate/3, the pattern can be a string, a list of strings, or a regular expression, and the result is a list of simple line and column data or an empty list.

Multiline pattern support added in version 0.2.0

Link to this section Summary

Functions

Finds line and column location(s) of a pattern in a given string

Creates a simple location map from line and column integers

Link to this section Functions

Link to this function locate(string, pattern, opts \\ []) View Source
locate(binary(), pattern(), keyword()) :: {atom(), [t()] | binary()}

Finds line and column location(s) of a pattern in a given string.

Returns a list of these locations or an empty list if not found. The pattern can be a string, a list of strings, or a regular expression, including multiline patterns.

The returned locations are listed in the order found, from top to bottom, left to right.

All locations are reported in the list by default but can be controlled via the :at_most option.

By default, the pattern is located from the beginning of the string, but the :start option can be used to report locations starting at a later point.

Options

  • :at_most (positive integer or :all) - the number of locations returned is at most as many as this option specifies. If :all, all found locations are returned. Defaults to :all.

  • :start (%{line: integer, col: integer}) - only locations >= the starting point specified by this option are returned; otherwise, the string is searched from the beginning.

Examples

Locating with a string:

iex> Sublocator.locate("<h2>\n  <span class=\"a\"", "a")
{:ok, [%{line: 2, col: 6}, %{line: 2, col: 11}, %{line: 2, col: 16}]}

iex> Sublocator.locate("<h2>\n  <span class=\"a\"", "a", at_most: 1)
{:ok, [%{line: 2, col: 6}]}

iex> Sublocator.locate("<h2>\n  <span class=\"a\"", "a", [start: %{line: 2, col: 10}])
{:ok, [%{line: 2, col: 11}, %{line: 2, col: 16}]}

A list of strings:

iex> Sublocator.locate("<h2>\n  <span class=\"a\"", ["h", "l"])
{:ok, [%{line: 1, col: 2}, %{line: 2, col: 10}]}

A regular expression:

iex> Sublocator.locate("<h2>\n  <span class=\"a\"", ~r{<(?!h)})
{:ok, [%{line: 2, col: 3}]}
Link to this function new_loc(line, col) View Source
new_loc(integer(), integer()) :: t()

Creates a simple location map from line and column integers.

Example

iex> Sublocator.new_loc(42, 12)
%{line: 42, col: 12}