about summary refs log tree commit diff
path: root/app/lib/command_tag/command/text_tools.rb
blob: 2c44167b4df926ad0ffa9c0bdea58ca80e9e0441 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# frozen_string_literal: true

module CommandTag::Command::TextTools
  def handle_code_at_start(args)
    return if args.count < 2

    name = normalize(args[0])
    value = args.last.presence || ''
    @vars[name] = case @status.content_type
                  when 'text/markdown'
                    ["```\n#{value}\n```"]
                  when 'text/html'
                    ["<pre><code>#{html_encode(value).gsub("\n", '<br/>')}</code></pre>"]
                  else
                    ["----------\n#{value}\n----------"]
                  end
  end

  def handle_code_with_return(args)
    return if args.count > 1

    value = args.last.presence || ''
    case @status.content_type
    when 'text/markdown'
      ["```\n#{value}\n```"]
    when 'text/html'
      ["<pre><code>#{html_encode(value).gsub("\n", '<br/>')}</code></pre>"]
    else
      ["----------\n#{value}\n----------"]
    end
  end

  def handle_prepend_before_save(args)
    args.each { |arg| @text = "#{arg}\n#{text}" }
  end

  def handle_append_before_save(args)
    args.each { |arg| @text << "\n#{arg}" }
  end

  def handle_replace_before_save(args)
    @text.gsub!(args[0], args[1] || '')
  end

  alias handle_sub_before_save handle_replace_before_save

  def handle_regex_replace_before_save(args)
    flags     = normalize(args[2])
    re_opts   = (flags.include?('i') ? Regexp::IGNORECASE : 0)
    re_opts  |= (flags.include?('x') ? Regexp::EXTENDED : 0)
    re_opts  |= (flags.include?('m') ? Regexp::MULTILINE : 0)

    @text.gsub!(Regexp.new(args[0], re_opts), args[1] || '')
  end

  alias handle_resub_before_save handle_replace_before_save
  alias handle_regex_sub_before_save handle_replace_before_save
end