danielsaidi / RichTextKit

RichTextKit is a Swift SDK that helps you use rich text in Swift and SwiftUI.
MIT License
944 stars 126 forks source link

Markdown-inspired formatting (as you type) #81

Open henningko opened 1 year ago

henningko commented 1 year ago

First off, thanks for providing such a comprehensive tool, it's been really helpful so far.

I am currently looking at ways to implement Markdown-inspired formatting, e.g checking for **text to make it bold**, or # to create headlines, similar to how Bear does it:

https://github.com/danielsaidi/RichTextKit/assets/5890910/b209a9a9-51e6-4061-8b3f-f9065d2ca35b

HighlightedTextEditor does this for sticking to Markdown stored as Strings (but it actually keeps the formatting symbols, which I'd like to remove) and has a good overview of the regex-patterns one would need to cover.

My initial approach was to

  1. Watch for changes in the text
  2. Match the regex's and apply bold formatting by creating a new NSAttributedString
  3. Replace the "old" context.attributedString with the newly created one

But this seemed expensive, and would be "jumpy" whenever you added formatting in the middle of the text.

My current approach is to watch the text, match the regex's, and use selectRange and toggle(_ style) to apply the modifications, but this doesn't remove the symbols (**) and still seems rather quirky.

While implementing something like this may be outside of the scope of this project, allowing to easily match & replace text, like #47 , would make this a lot easier. There might already be an easier way that I'm missing, too.

danielsaidi commented 1 year ago

Hi @henningko

Thank you for the video.

I've been considering Markdown support, but think they're two quite different challenges.

Not sure if a separate library would be better for the Markdown case?

henningko commented 1 year ago

Yeah, I've been contemplating both approaches, too. It does seem like most note-taking tool gravitate towards using Markdown commands as a trigger to apply formatting, e.g. typing ``` triggers code block formatting, > triggers quote formatting, # a heading etc. It's more of a way for power users to quickly apply formatting while typing. Bear, Craft, and Notion all handle it his way, and I have not yet found an open source editor for iOS that delivers that functionality, let alone combining it with "hotkey" support: Craft and Notion use typing / as a way to open a menu, for example.

Fully writing & keeping Markdown while also allowing rich text editing seems like it will become very challenging, particularly when in comes to handling tables or images. I think the good middle ground here is HighlightedTextEditor where everything is in Markdown, but styling gets applied. Things' comment section does the same. For the best experience, you will likely want to switch between a view and edit mode on these—for which you could use Down and aforementioned HTE, respectively.