> ## Documentation Index
> Fetch the complete documentation index at: https://www.cometchat.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Text Formatters

> Process message text in the CometChat iOS UI Kit v6 — hashtags, custom mentions, any pattern — with the CometChatTextFormatter protocol, in SwiftUI and UIKit.

Text formatters process message text: they react to a tracking character typed in the
composer, offer suggestions, and mark up the text in the conversation list and the composer. Use them for hashtags, custom mentions or any pattern.

There is **one protocol** in `CometChatCore`, used by both toolkits. A formatter you write works in SwiftUI
and UIKit unchanged.

***

## CometChatTextFormatter API

A formatter is a `@MainActor` class that holds one `CometChatTextFormatterState` — created
with the `trackingCharacter` that triggers it (`@` for mentions, `#` for hashtags) — and
implements `search(_:)` and `onScrollToBottom()`. Every other requirement has a default.
Formatters work on Foundation `AttributedString`.

### Key Methods

| Method | Purpose |
| - | - |
| `search(_ queryString: String?)` | the user typed after the tracking character; fetch and publish suggestions. `nil` when no query is active |
| `onScrollToBottom()` | the suggestion list reached its end; load more |
| `onItemClick(_:user:group:)` | the user picked a suggestion |
| `prepareLeftMessageBubbleSpan(_:_:)` | the text of an incoming message for the quoted-reply preview and Copy; plain characters only, and the text bubble itself does not call it |
| `prepareRightMessageBubbleSpan(_:_:)` | the same for an outgoing message |
| `prepareComposerSpan(_:_:)` | mark up text in the composer |
| `prepareConversationSpan(_:_:)` | mark up the last-message line in Conversations |
| `preparePreviewSpan(_:_:)` | the reply and edit previews — `prepareComposerSpan` by default |
| `handlePreMessageSend(_:)` | change a message before it is sent — attach metadata, rewrite text |
| `getOriginalText(_:)` | strip your display markup back to the stored token form; identity by default |
| `applyComposerSpans(_:)` | style your tokens live in the composer, attributes only |
| `setUser(_:)`, `setGroup(_:)` | the chat the formatter is used in |

### Suggestion System

| Method | Description |
| - | - |
| `setSuggestionItemList(_:)` | publish the suggestions to show |
| `setShowLoadingIndicator(_:)` | show or hide the spinner in the suggestion list |
| `setDisableSuggestions(_:)` | turn the suggestion list off |
| `setInfoText(_:)`, `setInfoVisibility(_:)` | the info row under the suggestions |

`CometChatTextFormatterState` is `@Observable`: the composer redraws when you change it.

### Marking up text

Mark a run with the Kit's attributes and both toolkits draw it: `RichTextFormatsAttribute`
takes a set of `RichTextFormat` — `.bold`, `.italic`, `.underline`, `.strikethrough`,
`.inlineCode`, `.link`.

***

## Example: Custom Hashtag Formatter

One implementation for both toolkits:

```swift theme={null}
import CometChatCore
import CometChatSDK

// Main-actor isolated, like the protocol it adopts.
final class HashtagFormatter: CometChatTextFormatter {
    let formatterState = CometChatTextFormatterState(trackingCharacter: "#")
    private let tags = ["launch", "design", "standup"]

    func search(_ queryString: String?) {
        let query = (queryString ?? "").lowercased()
        setSuggestionItemList(tags.filter { query.isEmpty || $0.hasPrefix(query) }.map { tag in
            SuggestionItem(id: tag, name: "#\(tag)", promptText: "#\(tag)", underlyingText: "#\(tag)")
        })
    }

    func onScrollToBottom() {}

    func prepareConversationSpan(_ baseMessage: BaseMessage, _ text: AttributedString) -> AttributedString {
        boldHashtags(text)
    }

    private func boldHashtags(_ text: AttributedString) -> AttributedString {
        var out = text
        let plain = String(text.characters)
        for match in plain.matches(of: #/#\w+/#) {
            guard let lower = AttributedString.Index(match.range.lowerBound, within: out),
                  let upper = AttributedString.Index(match.range.upperBound, within: out) else { continue }
            out[lower..<upper][RichTextFormatsAttribute.self] = [.bold]
        }
        return out
    }
}
```

> [!NOTE]
>
> Formatters render **live in the composer while typing** through `applyComposerSpans(_:)`, and
> the `prepare…Span` methods are applied to the reply and edit previews and the conversation
> list's preview — register the formatter on each component that shows the text. The message
> **bubbles** do not run your formatter: they draw mentions and markdown from the message itself.
> To change how a text bubble draws, replace its bubble — see
> [Message Template](https://www.cometchat.com/docs/ui-kit/ios/v6/message-template.md).

***

## Registering Formatters

> [tab] SwiftUI
>
> `textFormatters` **replaces** the default list, which is one `CometChatMentionsFormatter`.
> Include one to keep mentions:
>
> ```swift theme={null}
> @State private var formatters: [any CometChatTextFormatter] = [CometChatMentionsFormatter(), HashtagFormatter()]
>
> CometChatMessageList(user: user, textFormatters: formatters)
> CometChatMessageComposer(user: user, textFormatters: formatters)
> ```
>
> To put the two on a screen, host the composer over the list as [Conversation List + Message View](https://www.cometchat.com/docs/ui-kit/ios/v6/conversation-message-view.md#step-2-set-up-the-message-screen) shows.
>
> ```swift theme={null}
> CometChatConversations(textFormatters: [CometChatMentionsFormatter(), HashtagFormatter()])
> ```

> [tab] UIKit
>
> `set(textFormatters:)` on Conversations and the message list **replaces** the default
> list; `set(textFormatter:)` on the composer **appends** after its mentions formatter:
>
> ```swift theme={null}
> conversations.set(textFormatters: [CometChatMentionsFormatter(), hashtagFormatter])
> messageList.set(textFormatters: [CometChatMentionsFormatter(), hashtagFormatter])
> composer.set(textFormatter: [hashtagFormatter])
> ```

| Component | SwiftUI | UIKit |
| - | - | - |
| Conversations | `textFormatters:` | `set(textFormatters:)` |
| Message List | `textFormatters:` | `set(textFormatters:)` |
| Message Composer | `textFormatters:` | `set(textFormatter:)` — appends |
| Thread Header, Message Information, Pinned / Saved Messages | `textFormatters:` | `set(textFormatters:)` |
| Search | — | `set(textFormatters:)` |

***

## Built-in Formatter: CometChatMentionsFormatter

`CometChatMentionsFormatter` handles `@` mentions: user and group-member suggestions,
`<@uid:…>` tokens on the wire shown as `@Name`, mention-all, and the mention colours. It is in
`CometChatCore` and is each component's default formatter.

```swift theme={null}
let mentions = CometChatMentionsFormatter()
mentions.mentionLimit = 5
mentions.disableMentionAll = true
mentions.setMentionAllLabel("all", "everyone")
```

See the [Mentions Formatter Guide](https://www.cometchat.com/docs/ui-kit/ios/v6/mentions-formatter-guide.md) for every option.

***

## Related

* [Custom Text Formatter Guide](https://www.cometchat.com/docs/ui-kit/ios/v6/custom-text-formatter-guide.md) — a formatter step by step.
* [Customization Overview](https://www.cometchat.com/docs/ui-kit/ios/v6/customization-overview.md) — every customization category.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.