diff --git a/app/components/simple_format_component.rb b/app/components/simple_format_component.rb index c9f6f8199..74819a002 100644 --- a/app/components/simple_format_component.rb +++ b/app/components/simple_format_component.rb @@ -21,12 +21,22 @@ class SimpleFormatComponent < ApplicationComponent no_images: true } + SIMPLE_URL_REGEX = %r{https?://\S+} + EMAIL_IN_TEXT_REGEX = Regexp.new(Devise.email_regexp.source.gsub(/\\A|\\z/, '\b')) + def initialize(text, allow_a: true, class_names_map: {}) + @allow_a = allow_a + @text = (text || "").gsub(/\R/, "\n\n") # force double \n otherwise a single one won't split paragraph .split("\n\n") # .map(&:lstrip) # this block prevent redcarpet to consider " text" as block code by lstriping - .join("\n\n") # - @allow_a = allow_a + .join("\n\n") + .gsub(EMAIL_IN_TEXT_REGEX) { _1.gsub('_', '\\_') } # Workaround for redcarpet bug on autolink email having _. Cf tests + + if !@allow_a + @text = @text.gsub(SIMPLE_URL_REGEX) { _1.gsub('_', '\\_') } # Escape underscores in URLs + end + @renderer = Redcarpet::Markdown.new( Redcarpet::BareRenderer.new(class_names_map:), REDCARPET_EXTENSIONS.merge(autolink: @allow_a) diff --git a/app/lib/redcarpet/bare_renderer.rb b/app/lib/redcarpet/bare_renderer.rb index e672ee39a..5e4e9850a 100644 --- a/app/lib/redcarpet/bare_renderer.rb +++ b/app/lib/redcarpet/bare_renderer.rb @@ -26,6 +26,7 @@ module Redcarpet when :url link(link, nil, link) when :email + # NOTE: As of Redcarpet 3.6.0, autolinking email containing is broken https://github.com/vmg/redcarpet/issues/402 content_tag(:a, link, { href: "mailto:#{link}" }) else link diff --git a/spec/components/simple_format_component_spec.rb b/spec/components/simple_format_component_spec.rb index 2028c8b52..dc6cf6cbb 100644 --- a/spec/components/simple_format_component_spec.rb +++ b/spec/components/simple_format_component_spec.rb @@ -90,4 +90,31 @@ TEXT it { expect(page).not_to have_selector("a") } end end + + context 'emphasis not in urls' do + let(:text) do + <<~TEXT + A _string emphased_ but https://example.fr/path_preserves_underscore + email: here_is_my@email.com + TEXT + end + + context "without autolink" do + let(:allow_a) { false } + it { expect(page).to have_selector("em", count: 1, text: "string emphased") } + it { expect(page).to have_text("https://example.fr/path_preserves_underscore") } + it { expect(page).to have_text("email: here_is_my@email.com") } + end + + context "with autolink" do + let(:allow_a) { true } + it { + expect(page).to have_link("https://example.fr/path_preserves_underscore") + + # NOTE: As of Redcarpet 3.6.0, autolinking email containing _ is broken https://github.com/vmg/redcarpet/issues/402 + # but we still want the email to be displayed + expect(page).to have_text("here_is_my@email.com") + } + end + end end