> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-docs-audit-content-webhooks.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Custom Text Formatter

> Extend the CometChatTextFormatter base class to implement custom inline text patterns with regex and callbacks in Flutter.

<Accordion title="AI Agent Component Spec">
  | Field          | Value                                                                                                                                                                                                                                                                        |
  | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  | Package        | `cometchat_chat_uikit`                                                                                                                                                                                                                                                       |
  | Key class      | `CometChatTextFormatter` (abstract base class for custom formatters)                                                                                                                                                                                                         |
  | Required setup | `CometChatUIKit.init(uiKitSettings: uiKitSettings)` then `CometChatUIKit.login("UID")`                                                                                                                                                                                       |
  | Purpose        | Extend to create custom inline text patterns with regex, styling, and callbacks                                                                                                                                                                                              |
  | Features       | Text formatting, customizable styles, dynamic text replacement, input field integration                                                                                                                                                                                      |
  | Sample app     | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app)                                                                                                                                                                                            |
  | Related        | [ShortCut Formatter](/ui-kit/flutter/v5/shortcut-formatter-guide) \| [Mentions Formatter](/ui-kit/flutter/v5/mentions-formatter-guide) \| [Custom Mentions Formatter](/ui-kit/flutter/v5/custom-mentions-formatter-guide) \| [All Guides](/ui-kit/flutter/v5/guide-overview) |
</Accordion>

`CometChatTextFormatter` is an abstract class for formatting text in the message composer and message bubbles. Extend it to build custom formatters — hashtags, keywords, or any regex-based pattern.

| Capability          | Description                                         |
| ------------------- | --------------------------------------------------- |
| Text formatting     | Auto-format text based on regex patterns and styles |
| Custom styles       | Set colors, fonts, and backgrounds for matched text |
| Dynamic replacement | Regex-based find-and-replace in user input          |
| Input integration   | Real-time monitoring of the composer input field    |
| Attributed text     | Build styled text spans for message bubbles         |

***

## Steps

### 1. Import the base class

```dart theme={null}
import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';
```

### 2. Extend CometChatTextFormatter

```dart theme={null}
class HashTagTextFormatter extends CometChatTextFormatter {
  HashTagTextFormatter() : super(
    trackingCharacter: '#',
    pattern: RegExp(r'\B#(\w+)\b'),
  );
  
  // Override required methods...
}
```

### 3. Configure tracking character and regex

Set the character that triggers formatting and the regex to match.

```dart theme={null}
HashTagTextFormatter() : super(
  trackingCharacter: '#',
  pattern: RegExp(r'\B#(\w+)\b'),
  showLoadingIndicator: false,
);
```

### 4. Implement required methods

```dart theme={null}
@override
void init() {
  // Initialize formatter
}

@override
void handlePreMessageSend(BuildContext context, BaseMessage baseMessage) {
  // Process message before sending
}

@override
TextStyle getMessageInputTextStyle(BuildContext context) {
  return TextStyle(color: Colors.blue);
}

@override
void onScrollToBottom(TextEditingController textEditingController) {
  // Handle scroll events
}

@override
void onChange(TextEditingController textEditingController, String previousText) {
  // Handle text changes
}
```

### 5. Customize message bubble styling

```dart theme={null}
@override
TextStyle getMessageBubbleTextStyle(
  BuildContext context, 
  BubbleAlignment? alignment,
  {bool forConversation = false}
) {
  return TextStyle(
    color: alignment == BubbleAlignment.right 
      ? Colors.white 
      : Colors.blue,
    fontWeight: FontWeight.bold,
    decoration: TextDecoration.underline,
  );
}
```

***

## Example

A hashtag formatter used with [CometChatMessageList](/ui-kit/flutter/v5/message-list) and [CometChatMessageComposer](/ui-kit/flutter/v5/message-composer).

<Tabs>
  <Tab title="HashTagTextFormatter.dart">
    ```dart theme={null}
    import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';
    import 'package:flutter/material.dart';

    class HashTagTextFormatter extends CometChatTextFormatter {
      HashTagTextFormatter() : super(
        trackingCharacter: '#',
        pattern: RegExp(r'\B#(\w+)\b'),
        showLoadingIndicator: false,
      );

      @override
      void init() {
        // Initialization logic
      }

      @override
      void handlePreMessageSend(BuildContext context, BaseMessage baseMessage) {
        // Process hashtags before sending
      }

      @override
      TextStyle getMessageInputTextStyle(BuildContext context) {
        CometChatColorPalette colorPalette = CometChatThemeHelper.getColorPalette(context);
        return TextStyle(
          color: colorPalette.primary,
          fontWeight: FontWeight.w500,
        );
      }

      @override
      TextStyle getMessageBubbleTextStyle(
        BuildContext context, 
        BubbleAlignment? alignment,
        {bool forConversation = false}
      ) {
        CometChatColorPalette colorPalette = CometChatThemeHelper.getColorPalette(context);
        return TextStyle(
          color: alignment == BubbleAlignment.right 
            ? colorPalette.white 
            : colorPalette.primary,
          fontWeight: FontWeight.bold,
          decoration: TextDecoration.underline,
        );
      }

      @override
      void onScrollToBottom(TextEditingController textEditingController) {
        // Handle scroll to bottom
      }

      @override
      void onChange(TextEditingController textEditingController, String previousText) {
        // Handle text changes - detect new hashtags
        String currentText = textEditingController.text;
        if (currentText.contains('#')) {
          // Process hashtag
        }
      }

      @override
      List<AttributedText> getAttributedText(
        String text, 
        BuildContext context, 
        BubbleAlignment? alignment,
        {List<AttributedText>? existingAttributes,
        Function(String)? onTap,
        bool forConversation = false}
      ) {
        return super.getAttributedText(
          text, 
          context, 
          alignment,
          existingAttributes: existingAttributes,
          onTap: onTap ?? (hashtag) {
            // Handle hashtag tap - e.g., search for hashtag
            print('Tapped hashtag: $hashtag');
          },
          forConversation: forConversation,
        );
      }
    }
    ```
  </Tab>

  <Tab title="Usage">
    Pass the formatter via the `textFormatters` property.

    ```dart theme={null}
    import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';
    import 'package:flutter/material.dart';

    class MessageListDemo extends StatefulWidget {
      const MessageListDemo({super.key});

      @override
      State<MessageListDemo> createState() => _MessageListDemoState();
    }

    class _MessageListDemoState extends State<MessageListDemo> {
      User? chatUser;

      @override
      void initState() {
        super.initState();
        CometChat.getUser("uid").then((user) {
          setState(() {
            chatUser = user;
          });
        });
      }

      @override
      Widget build(BuildContext context) {
        if (chatUser == null) {
          return const Center(child: CircularProgressIndicator());
        }
        
        return CometChatMessageList(
          user: chatUser,
          textFormatters: [HashTagTextFormatter()],
        );
      }
    }
    ```
  </Tab>
</Tabs>

***

## Methods Reference

| Field                    | Description                                            |
| ------------------------ | ------------------------------------------------------ |
| `trackingCharacter`      | Character that starts tracking (e.g. `#` for hashtags) |
| `pattern`                | Regex pattern to match text for formatting             |
| `showLoadingIndicator`   | Whether to show loading indicator during search        |
| `messageBubbleTextStyle` | Function to style message bubble text                  |
| `messageInputTextStyle`  | Function to style composer input text                  |
| `message`                | Current message being processed                        |
| `user`                   | User context for the formatter                         |
| `group`                  | Group context for the formatter                        |

***

## Override Methods

<Tabs>
  <Tab title="init">
    Initialize the formatter. Called when the formatter is first used.

    ```dart theme={null}
    @override
    void init() {
      // Setup any initial state
    }
    ```
  </Tab>

  <Tab title="handlePreMessageSend">
    Process the message before it's sent. Use this to modify message metadata.

    ```dart theme={null}
    @override
    void handlePreMessageSend(BuildContext context, BaseMessage baseMessage) {
      // Add hashtag metadata to message
      if (baseMessage is TextMessage) {
        final hashtags = pattern?.allMatches(baseMessage.text)
          .map((m) => m.group(1))
          .toList();
        // Store hashtags in message metadata
      }
    }
    ```
  </Tab>

  <Tab title="getMessageBubbleTextStyle">
    Returns the TextStyle for formatted text in message bubbles.

    ```dart theme={null}
    @override
    TextStyle getMessageBubbleTextStyle(
      BuildContext context, 
      BubbleAlignment? alignment,
      {bool forConversation = false}
    ) {
      return TextStyle(
        color: Colors.blue,
        fontWeight: FontWeight.bold,
      );
    }
    ```
  </Tab>

  <Tab title="getAttributedText">
    Returns styled text spans for the message bubble.

    ```dart theme={null}
    @override
    List<AttributedText> getAttributedText(
      String text, 
      BuildContext context, 
      BubbleAlignment? alignment,
      {List<AttributedText>? existingAttributes,
      Function(String)? onTap,
      bool forConversation = false}
    ) {
      // Return attributed text with styling
      return super.getAttributedText(
        text, context, alignment,
        existingAttributes: existingAttributes,
        onTap: onTap,
        forConversation: forConversation,
      );
    }
    ```
  </Tab>

  <Tab title="onChange">
    Called when text changes in the composer.

    ```dart theme={null}
    @override
    void onChange(TextEditingController textEditingController, String previousText) {
      // Detect and process new patterns
    }
    ```
  </Tab>
</Tabs>

***

## Built-in Formatters

Flutter UI Kit includes these pre-built formatters:

| Formatter                       | Description                           |
| ------------------------------- | ------------------------------------- |
| `CometChatMentionsFormatter`    | @mentions with user suggestions       |
| `CometChatUrlFormatter`         | Auto-detect and style URLs            |
| `CometChatEmailFormatter`       | Auto-detect and style email addresses |
| `CometChatPhoneNumberFormatter` | Auto-detect and style phone numbers   |

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Mentions Formatter" href="/ui-kit/flutter/v5/mentions-formatter-guide">
    Add @mentions with styled tokens.
  </Card>

  <Card title="Custom Mentions Formatter" href="/ui-kit/flutter/v5/custom-mentions-formatter-guide">
    Build a custom mentions formatter with filtered suggestions.
  </Card>

  <Card title="Message Composer" href="/ui-kit/flutter/v5/message-composer">
    Customize the message input component.
  </Card>

  <Card title="All Guides" href="/ui-kit/flutter/v5/guide-overview">
    Browse all feature and formatter guides.
  </Card>

  <Card title="Sample App" href="https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app">
    Full working sample application on GitHub.
  </Card>
</CardGroup>
