Modern Apps git

← Modern-Apps.git

securemail: render [text](url) and light markup in plain-text mail

Commit
426f2162d577de47d5ce631096547d947e1d210a
Author
Vayun Mathur <[email protected]>
When
2026-11-02 06:10 UTC (1 month ago)
Parents
1125841
Plain-text bodies showed Proton's markup literally, e.g.
"[the docs](https://proton.me/support)". Proton derives its text/plain
part from rich text using Markdown-style syntax; the reader only
linkified bare URLs, so every link and bold run showed raw. This is
what you see for any message without a stored HTML part: mail that
arrived before HTML rendering (0f8569617), and plain-text-only mail.

New domain/mail/PlainTextMarkup (pure Kotlin, unit tested) parses a
body into styled runs:
- [text](url) and <url> become links; ![alt](url) becomes a link to
  the image (never loaded); bare http(s) URLs and email addresses are
  linked as before, with trailing punctuation kept out of the link.
- **bold** / __bold__, *italic* / _italic_ (not inside words, so
  snake_case and 2*3*4 are left alone), "# heading" lines as bold.
- "* item" / "- item" bullets render as "•", indentation kept.
- Only http(s) and mailto targets become tappable; anything else
  (javascript:, file:, ...) stays as literal text.
- Line breaks are kept exactly as sent: unlike the editor's markdown
  renderers, nothing is reflowed and no LaTeX/$...$ processing is
  applied, so ordinary prose can't be mangled.

MessageBodyView's plain-text path builds its AnnotatedString from these
runs (LinkAnnotation.Url for links, SpanStyle for bold/italic),
replacing the URL-only linkify.

Verified: PlainTextMarkupTest (6: Proton-style link, unsafe scheme kept
literal, bold/italic/heading, bullets + preserved line breaks, bare URL
punctuation + email, snake_case/math not italicised); all securemail
unit tests; :securemail:lint clean; detekt unchanged at 40. Not yet
viewed on a device.

Diff

securemail/src/main/java/com/vayunmathur/securemail/domain/mail/PlainTextMarkup.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/PlainTextMarkup.kt b/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/PlainTextMarkup.ktnew file mode 100644index 0000000000..078b67d0e1--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/PlainTextMarkup.kt@@ -0,0 +1,98 @@+package com.vayunmathur.securemail.domain.mail++/**+ * Light markup for plain-text mail bodies. Proton (and other clients that+ * derive text/plain from rich text) write links as `[text](url)`, bold as+ * `**x**`, italics as `*x*`/`_x_`, bullets as `* item`, headings as `# x`.+ * This turns those into styled runs without reflowing anything: line breaks+ * are kept exactly as sent, and only http(s)/mailto targets become links.+ * Bare URLs and email addresses are linked too.+ */+object PlainTextMarkup {++    /** One styled stretch of text; [url] set when it should be tappable. */+    data class Run(+        val text: String,+        val url: String? = null,+        val bold: Boolean = false,+        val italic: Boolean = false,+    )++    fun parse(text: String): List<Run> {+        val runs = mutableListOf<Run>()+        text.split("\n").forEachIndexed { index, rawLine ->+            if (index > 0) runs += Run("\n")+            val heading = HEADING.matchEntire(rawLine)+            val bullet = BULLET.matchEntire(rawLine)+            when {+                heading != null -> inline(heading.groupValues[1], runs, bold = true)+                bullet != null -> {+                    runs += Run(bullet.groupValues[1] + "\u2022 ")+                    inline(bullet.groupValues[2], runs, bold = false)+                }+                else -> inline(rawLine, runs, bold = false)+            }+        }+        return merge(runs)+    }++    private fun inline(line: String, out: MutableList<Run>, bold: Boolean) {+        var pos = 0+        for (m in TOKEN.findAll(line)) {+            if (m.range.first > pos) out += Run(line.substring(pos, m.range.first), bold = bold)+            val g = m.groupValues+            when {+                m.value.startsWith("![") -> out += linkOrRaw(g[1].ifBlank { "image" }, g[2], m.value, bold)+                g[3].isNotEmpty() -> out += linkOrRaw(g[3], g[4], m.value, bold)+                g[5].isNotEmpty() -> out += Run(g[5].removePrefix("mailto:"), g[5], bold = bold)+                g[6].isNotEmpty() || g[7].isNotEmpty() -> out += Run(g[6] + g[7], bold = true)+                g[8].isNotEmpty() || g[9].isNotEmpty() -> out += Run(g[8] + g[9], bold = bold, italic = true)+                g[10].isNotEmpty() -> {+                    val url = g[10].trimEnd('.', ',', ';', ':', '!', '?', ')', ']', '\'', '"')+                    out += Run(url, url, bold = bold)+                    if (url.length < g[10].length) out += Run(g[10].substring(url.length), bold = bold)+                }+                g[11].isNotEmpty() -> out += Run(g[11], "mailto:${g[11]}", bold = bold)+            }+            pos = m.range.last + 1+        }+        if (pos < line.length) out += Run(line.substring(pos), bold = bold)+    }++    /** A markdown link only becomes tappable for safe schemes; anything else stays literal. */+    private fun linkOrRaw(label: String, target: String, raw: String, bold: Boolean): Run =+        if (SAFE_SCHEME.containsMatchIn(target)) Run(label, target, bold = bold) else Run(raw, bold = bold)++    /** Joins adjacent runs with identical styling so the UI builds fewer spans. */+    private fun merge(runs: List<Run>): List<Run> {+        val out = mutableListOf<Run>()+        for (r in runs) {+            if (r.text.isEmpty()) continue+            val last = out.lastOrNull()+            if (last != null && last.joinsWith(r)) {+                out[out.lastIndex] = last.copy(text = last.text + r.text)+            } else {+                out += r+            }+        }+        return out+    }++    /** Two plain (non-link) runs with the same weight and slant render identically. */+    private fun Run.joinsWith(next: Run): Boolean =+        url == null && next.url == null && bold == next.bold && italic == next.italic++    private val HEADING = Regex("""^#{1,6}\s+(.+?)\s*#*\s*$""")+    private val BULLET = Regex("""^(\s*)[*+-]\s+(.*)$""")+    private val SAFE_SCHEME = Regex("""^(https?://|mailto:)""", RegexOption.IGNORE_CASE)+    private val TOKEN = Regex(+        """!\[([^\]\n]*)]\(([^)\s]+)\)""" + // 1,2 image: shown as a link, never loaded+            """|\[([^\]\n]+)]\(([^)\s]+)\)""" + // 3,4 link+            """|<((?:https?://|mailto:)[^>\s]+)>""" + // 5 autolink+            """|\*\*([^*\n]+)\*\*|__([^_\n]+)__""" + // 6,7 bold+            """|(?<![\w*])\*([^*\s](?:[^*\n]*[^*\s])?)\*(?![\w*])""" + // 8 italic+            """|(?<![\w_])_([^_\s](?:[^_\n]*[^_\s])?)_(?![\w_])""" + // 9 italic+            """|(https?://[^\s<>"]+)""" + // 10 bare URL+            """|([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})""", // 11 email address+    )+}
securemail/src/main/java/com/vayunmathur/securemail/ui/MessageBodyView.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/ui/MessageBodyView.kt b/securemail/src/main/java/com/vayunmathur/securemail/ui/MessageBodyView.ktindex 8c4b59d4da..f10d07226e 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/ui/MessageBodyView.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/ui/MessageBodyView.kt@@ -17,6 +17,8 @@ import androidx.compose.ui.text.LinkAnnotation import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextLinkStyles import androidx.compose.ui.text.buildAnnotatedString+import androidx.compose.ui.text.font.FontStyle+import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.HtmlText@@ -24,6 +26,7 @@ import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton import com.vayunmathur.securemail.data.StoredMessage+import com.vayunmathur.securemail.domain.mail.PlainTextMarkup  /**  * Message body: the sender's HTML part when there is one (links, lists,@@ -81,7 +84,7 @@ private fun PlainBody(msg: StoredMessage) {     val (main, quoted) = remember(body) { splitQuotedText(body) }     val linkColor = MaterialTheme.colorScheme.primary     val shown = if (showQuotes || quoted.isEmpty()) body else main-    val annotated = remember(shown, linkColor) { linkify(shown, linkColor) }+    val annotated = remember(shown, linkColor) { styled(shown, linkColor) }     Text(         annotated,         style = MaterialTheme.typography.bodyMedium,@@ -94,14 +97,23 @@ private fun PlainBody(msg: StoredMessage) {     } } -/** Plain text with http(s) URLs and email addresses turned into tappable links. */-private fun linkify(text: String, color: androidx.compose.ui.graphics.Color): AnnotatedString = buildAnnotatedString {-    append(text)-    val style = TextLinkStyles(SpanStyle(color = color, textDecoration = TextDecoration.Underline))-    URL.findAll(text).forEach { m ->-        val raw = m.value.trimEnd('.', ',', ')', ']', ';', ':', '!', '?')-        val target = if (raw.contains('@') && !raw.startsWith("http", ignoreCase = true)) "mailto:$raw" else raw-        addLink(LinkAnnotation.Url(target, style), m.range.first, m.range.first + raw.length)+/** Plain text with light markup ([text](url), **bold**, bullets...) applied; see [PlainTextMarkup]. */+private fun styled(text: String, linkColor: androidx.compose.ui.graphics.Color): AnnotatedString = buildAnnotatedString {+    val linkStyle = TextLinkStyles(SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline))+    for (run in PlainTextMarkup.parse(text)) {+        val start = length+        append(run.text)+        if (run.bold || run.italic) {+            addStyle(+                SpanStyle(+                    fontWeight = if (run.bold) FontWeight.Bold else null,+                    fontStyle = if (run.italic) FontStyle.Italic else null,+                ),+                start,+                length,+            )+        }+        run.url?.let { addLink(LinkAnnotation.Url(it, linkStyle), start, length) }     } } @@ -118,6 +130,5 @@ private fun splitQuotedText(body: String): Pair<String, String> {     return body to "" } -private val URL = Regex("""https?://[^\s<>"]+|[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}""") private val REMOTE_REF = Regex("""(?i)(src|background|srcset)\s*=\s*["']?\s*https?://|url\(\s*["']?https?://""") private val QUOTE_MARKERS = listOf("protonmail_quote", "gmail_quote", "yahoo_quoted", "moz-cite-prefix", "<blockquote")
securemail/src/test/java/com/vayunmathur/securemail/domain/mail/PlainTextMarkupTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/PlainTextMarkupTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/PlainTextMarkupTest.ktnew file mode 100644index 0000000000..4aa7f382c4--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/PlainTextMarkupTest.kt@@ -0,0 +1,58 @@+package com.vayunmathur.securemail.domain.mail++import com.vayunmathur.securemail.domain.mail.PlainTextMarkup.Run+import kotlin.test.Test+import kotlin.test.assertEquals++class PlainTextMarkupTest {++    @Test+    fun protonStyleLink() {+        assertEquals(+            listOf(Run("See "), Run("the docs", "https://proton.me/support"), Run(" please")),+            PlainTextMarkup.parse("See [the docs](https://proton.me/support) please"),+        )+    }++    @Test+    fun unsafeSchemeStaysLiteral() {+        assertEquals(+            listOf(Run("[click](javascript:alert(1))")),+            PlainTextMarkup.parse("[click](javascript:alert(1))"),+        )+    }++    @Test+    fun boldItalicAndHeading() {+        assertEquals(+            listOf(Run("Title", bold = true), Run("\nis "), Run("big", bold = true), Run(" and "), Run("slanted", italic = true)),+            PlainTextMarkup.parse("# Title\nis **big** and *slanted*"),+        )+    }++    @Test+    fun bulletsAndLineBreaksPreserved() {+        assertEquals(+            listOf(Run("Items:\n\u2022 one\n  \u2022 two\n\nbye")),+            PlainTextMarkup.parse("Items:\n* one\n  - two\n\nbye"),+        )+    }++    @Test+    fun bareUrlTrailingPunctuationAndEmail() {+        assertEquals(+            listOf(+                Run("Go to "),+                Run("https://maemail.org/x", "https://maemail.org/x"),+                Run(". Mail "),+                Run("[email protected]", "mailto:[email protected]"),+            ),+            PlainTextMarkup.parse("Go to https://maemail.org/x. Mail [email protected]"),+        )+    }++    @Test+    fun snakeCaseAndMathAreNotItalic() {+        assertEquals(listOf(Run("my_var_name and 2*3*4")), PlainTextMarkup.parse("my_var_name and 2*3*4"))+    }+}