memspace / zefyr

Soft and gentle rich text editing for Flutter applications.
https://zefyr-editor.gitbook.io
2.22k stars 551 forks source link

Built-in support for word count and character count? #334

Open Albert-Jan opened 4 years ago

Albert-Jan commented 4 years ago

Might be useful to include a built-in function for notus documents to get the character, word and paragraph count.

Albert-Jan commented 4 years ago

This is my current implementation: int characters = notusDocument.toPlainText().length - 1; int words = notusDocument.toPlainText().split(' ').length; int charactersNoSpaces = notusDocument.toPlainText().length - words;

Albert-Jan commented 4 years ago

Anyone any suggestions on how to implement a paragraph count?

kwestlund commented 4 years ago

Paragraphs are separated by newlines, so you could try extracting the text string from the document, then counting the number of newlines (perhaps counting consecutive newlines as one).

If you have the ZefyrController, you can extract the text string and count paragraphs with something like:

_controller.document.toPlainText().split(r'\n+').length

You may want to do something to account for embedded objects (e.g., images and horizontal separators). They should appear in the text string as EmbedNode.kPlainTextPlaceholder (character 0x200b).

_controller.document.toPlainText().split(r'[\n\u200b]+').length

And since there is always at least 1 newline at the end of a document, you may want to subtract that from the result:

_controller.document.toPlainText().split(r'[\n\u200b]+').length - 1

I have not tested any of this...