> ## 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 Formatter Base Class

> Conform to CometChatTextFormatter to add your own tracking character, suggestion list and text formatting to the CometChat iOS UI Kit v6 composer and lists.

> [accordion] AI Integration Quick Reference
>
> ```json theme={null}
> {
>   "products": ["CometChatSwiftUI", "CometChatUIKit"],
>   "protocol": "CometChatTextFormatter (CometChatCore, @MainActor, AnyObject)",
>   "required": ["formatterState: CometChatTextFormatterState", "search(_:)", "onScrollToBottom()"],
>   "optional": ["onItemClick(_:user:group:)", "handlePreMessageSend(_:)", "prepareConversationSpan(_:_:)", "preparePreviewSpan(_:_:)", "prepareLeftMessageBubbleSpan(_:_:)", "prepareRightMessageBubbleSpan(_:_:)", "prepareComposerSpan(_:_:)", "getOriginalText(_:)", "observeSelectionList(_:)"],
>   "composer": "CometChatMessageComposer(textFormatters:) replaces the list (SwiftUI) / set(textFormatter:) appends after the mentions formatter (UIKit)",
>   "suggestion": "SuggestionItem(id:name:promptText:underlyingText:) — promptText shows in the input, underlyingText is sent"
> }
> ```

`CometChatTextFormatter` is the protocol behind the Kit's mentions. Conform to it to add your
own trigger — `#` for hashtags, `!` for shortcuts — with a suggestion list in the composer, and
to rewrite how message text reads in the lists that run formatters.

It is one protocol for both toolkits, in `CometChatCore`. The stored state lives in a `CometChatTextFormatterState` your formatter owns.

## How a formatter works

| Moment | What the Kit calls |
| - | - |
| The user types the tracking character, then more | `search(_:)` with the text after it — `nil` when the query ends |
| The suggestion list scrolls to its end | `onScrollToBottom()` — load more |
| The user picks a suggestion | the item's `promptText` goes into the input; `onItemClick(_:user:group:)` |
| The message is sent | `promptText` is replaced by `underlyingText` on the wire; `handlePreMessageSend(_:)` |
| A conversation's last message, a quoted reply, a pinned or saved message, a search result, Copy and Share | `prepare…Span` for that surface |

> [!NOTE]
>
> The message **bubbles** do not run your formatter. They draw mentions and markdown from the
> message itself, so a custom `prepareLeftMessageBubbleSpan` / `prepareRightMessageBubbleSpan`
> does not change a bubble. 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).

## Steps

### 1. Conform to CometChatTextFormatter

Hold one `CometChatTextFormatterState`, created with your tracking character:

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

final class HashtagFormatter: CometChatTextFormatter {
    let formatterState = CometChatTextFormatterState(trackingCharacter: "#")

    private let tags = ["launch", "design", "standup", "release", "retro"]

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

    func onScrollToBottom() {}
}
```

### 2. Fill the suggestion list from `search(_:)`

`search(_:)` runs as the user types after the tracking character. Answer with
`setSuggestionItemList(_:)`; show a spinner while you fetch with `setShowLoadingIndicator(_:)`;
put a line above the list with `setInfoText(_:)` and `setInfoVisibility(_:)`.

A `SuggestionItem`:

| Field | Meaning |
| - | - |
| `id` | your identifier |
| `name` | the row's title |
| `leadingIconUrl` | an avatar for the row; `hideLeadingIcon: true` drops it |
| `promptText` | what the input shows once picked — start it with your tracking character |
| `underlyingText` | what is sent in its place |
| `data` | anything you want back in `onItemClick` |

### 3. Load more in `onScrollToBottom()`

Called when the list reaches its end. Fetch the next page and append to
`suggestionItemList` with `setSuggestionItemList(_:)`. Leave it empty if you load everything at
once.

### 4. Rewrite text in the lists (optional)

The `prepare…Span` methods take the message and the text so far and return the text to show.
Every one defaults to returning the text unchanged. `prepareConversationSpan` changes the last
message line in Conversations:

```swift TagStripper.swift theme={null}
import Foundation
import CometChatCore
import CometChatSDK

final class TagStripper: CometChatTextFormatter {
    let formatterState = CometChatTextFormatterState(trackingCharacter: "#")
    func search(_ queryString: String?) {}
    func onScrollToBottom() {}

    /// Conversations show "Ship it" for "Ship it #release".
    func prepareConversationSpan(_ baseMessage: BaseMessage, _ text: AttributedString) -> AttributedString {
        let plain = String(text.characters)
        let kept = plain.split(separator: " ").filter { !$0.hasPrefix("#") }.joined(separator: " ")
        return AttributedString(kept)
    }
}
```

The other hooks: `preparePreviewSpan` (the composer's reply and edit previews; by default
`prepareComposerSpan`), `getOriginalText` (your display markup back to its wire text) and
`handlePreMessageSend` (change the message — its metadata, say — just before it is sent).

### 5. Give it to a component

> [tab] SwiftUI
>
> `textFormatters` **replaces** the composer's list. `nil`, the default, means one mentions
> formatter — include a `CometChatMentionsFormatter` to keep mentions. Keep the formatters in
> `@State` so they are not rebuilt on every render:
>
> ```swift TaggedComposer.swift theme={null}
> import SwiftUI
> import CometChatSwiftUI
> import CometChatSDK
>
> final class HashtagFormatter: CometChatTextFormatter {
>     let formatterState = CometChatTextFormatterState(trackingCharacter: "#")
>     func search(_ queryString: String?) {
>         let tag = queryString ?? ""
>         setSuggestionItemList(queryString == nil ? [] :
>             [SuggestionItem(id: tag, name: "#\(tag)", promptText: "#\(tag)", underlyingText: "#\(tag)")])
>     }
>     func onScrollToBottom() {}
> }
>
> struct TaggedComposer: View {
>     let group: CometChatSDK.Group
>     @State private var formatters: [any CometChatTextFormatter] = [CometChatMentionsFormatter(), HashtagFormatter()]
>
>     var body: some View {
>         CometChatMessageComposer(group: group, textFormatters: formatters)
>     }
> }
> ```
>
> `CometChatConversations(textFormatters:)`, `CometChatMessageList(textFormatters:)`,
> `CometChatThreadHeader(textFormatters:)`, `CometChatPinnedMessages(textFormatters:)` and
> `CometChatSavedMessages(textFormatters:)` take a list too. Give each component **its own**
> instances — formatters hold state.

> [tab] UIKit
>
> `set(textFormatter:)` **appends** after the composer's mentions formatter. With the `HashtagFormatter` from step 1:
>
> ```swift theme={null}
> let composer = CometChatMessageComposer()
> composer.set(group: guideGroup)
> composer.set(textFormatter: [HashtagFormatter()])
> ```
>
> `CometChatConversations`, `CometChatMessageList`, `CometChatThreadHeader` and
> `CometChatSavedMessages` take `set(textFormatters:)`, which **replaces** their list. Give each
> component its own instances.

> [!WARNING]
>
> The SwiftUI composer's `disableMentions: true` removes **every** formatter, yours included.
> To keep yours without mentions, pass a list with no mentions formatter.

## Methods Reference

| Member | Default | Purpose |
| - | - | - |
| `formatterState` | — (required) | your state: tracking character, suggestions, selection, info, loading, user, group |
| `search(_:)` | — (required) | answer a query with suggestions |
| `onScrollToBottom()` | — (required) | load more suggestions |
| `onItemClick(_:user:group:)` | nothing | a suggestion was picked |
| `handlePreMessageSend(_:)` | nothing | change the message before it is sent |
| `prepareConversationSpan(_:_:)` | text unchanged | Conversations' last-message line |
| `preparePreviewSpan(_:_:)` | `prepareComposerSpan` | the reply and edit previews |
| `prepareComposerSpan(_:_:)` | text unchanged | text put back in the composer |
| `prepareLeftMessageBubbleSpan(_:_:)`, `prepareRightMessageBubbleSpan(_:_:)` | text unchanged | quoted replies, pinned messages, Copy and Share |
| `getOriginalText(_:)` | text unchanged | display markup back to wire text |
| `observeSelectionList(_:)` | nothing | the picked suggestions changed |
| `setUser(_:)`, `setGroup(_:)` | store them | the chat the composer is in |
| `setSuggestionItemList(_:)`, `setShowLoadingIndicator(_:)`, `setInfoText(_:)`, `setInfoVisibility(_:)`, `setSelectedList(_:)`, `setDisableSuggestions(_:)` | — | write `formatterState` |

## Next Steps

> [card] [Mentions Formatter](https://www.cometchat.com/docs/ui-kit/ios/v6/mentions-formatter-guide.md)
>
> The built-in formatter, configured

> [card] [ShortCut Formatter](https://www.cometchat.com/docs/ui-kit/ios/v6/shortcut-formatter-guide.md)
>
> A formatter over the message-shortcuts extension

> [card] [Message Composer](https://www.cometchat.com/docs/ui-kit/ios/v6/message-composer.md)
>
> Where suggestions appear

> [card] [All Guides](https://www.cometchat.com/docs/ui-kit/ios/v6/guide-overview.md)
>
> Browse the other guides


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