helpers.ex (2219B)
1 defmodule EarmarkParser.Helpers do 2 3 @moduledoc false 4 @doc """ 5 Expand tabs to multiples of 4 columns 6 """ 7 def expand_tabs(line) do 8 Regex.replace(~r{(.*?)\t}, line, &expander/2) 9 end 10 11 @trailing_ial_rgx ~r< (\s* \S .*?) {: \s* ([^}]+) \s* } \s* \z>x 12 @doc ~S""" 13 Returns a tuple containing a potentially present IAL and the line w/o the IAL 14 15 iex(1)> extract_ial("# A headline") 16 {nil, "# A headline"} 17 18 iex(2)> extract_ial("# A classy headline{:.classy}") 19 {".classy", "# A classy headline"} 20 21 An IAL line, remains an IAL line though 22 23 iex(3)> extract_ial("{:.line-ial}") 24 {nil, "{:.line-ial}"} 25 """ 26 def extract_ial(line) do 27 case Regex.run(@trailing_ial_rgx, line) do 28 nil -> {nil, line} 29 [_, line_, ial] -> {ial, line_} 30 end 31 end 32 33 defp expander(_, leader) do 34 extra = 4 - rem(String.length(leader), 4) 35 leader <> pad(extra) 36 end 37 38 @doc """ 39 Remove newlines at end of line and optionally annotations 40 """ 41 # def remove_line_ending(line, annotation \\ nil) 42 def remove_line_ending(line, nil) do 43 _trim_line({line, nil}) 44 end 45 def remove_line_ending(line, annotation) do 46 case Regex.run(annotation, line) do 47 nil -> _trim_line({line, nil}) 48 match -> match |> tl() |> List.to_tuple |> _trim_line() 49 end 50 end 51 52 defp _trim_line({line, annot}), do: {line |> String.trim_trailing("\n") |> String.trim_trailing("\r"), annot} 53 54 defp pad(1), do: " " 55 defp pad(2), do: " " 56 defp pad(3), do: " " 57 defp pad(4), do: " " 58 59 @doc """ 60 `Regex.replace` with the arguments in the correct order 61 """ 62 63 def replace(text, regex, replacement, options \\ []) do 64 Regex.replace(regex, text, replacement, options) 65 end 66 67 @doc """ 68 Replace <, >, and quotes with the corresponding entities. If 69 `encode` is true, convert ampersands, too, otherwise only 70 convert non-entity ampersands. 71 """ 72 73 @amp_rgx ~r{&(?!#?\w+;)} 74 75 def escape(html), do: _escape(Regex.replace(@amp_rgx, html, "&")) 76 77 78 defp _escape(html) do 79 html 80 |> String.replace("<", "<") 81 |> String.replace(">", ">") 82 |> String.replace("\"", """) 83 |> String.replace("'", "'") 84 end 85 end 86 87 # SPDX-License-Identifier: Apache-2.0