Skip to content

feat: show selected text word count - #4457

Merged
Jocs merged 32 commits into
marktext:developfrom
Renakoni:feature/selected-text-word-count
Sep 19, 2026
Merged

Jocs merged 32 commits into
marktext:developfrom
Renakoni:feature/selected-text-word-count

Conversation

@Renakoni

Copy link
Copy Markdown
Contributor

Closes #4395

Summary

This adds selected text word-count feedback to the existing title-bar counter.

  • Keeps the existing document count display when no text is selected.
  • Shows document / selection counts when text is selected, e.g. W 89 / 14.
  • Updates the tooltip to compare Document / Selection counts.
  • Supports both WYSIWYG mode and source-code mode.
  • Initializes document word count when opening/creating documents so the counter does not show W 0 before edits.
  • Adds E2E coverage for selected text word count.

Type of change

  • Bug fix (non-breaking, fixes an issue)
  • New feature (non-breaking, adds functionality)
  • Breaking change (causes existing functionality to change)
  • Documentation update

Test plan

  • New tests added (or explain why not needed)
    • Added test/e2e/titlebar-selection-word-count.spec.ts.
  • Manually tested on: Windows
  • pnpm run lint
    • Passes with existing warnings.
  • pnpm --filter marktext typecheck
  • pnpm --filter marktext build
  • pnpm -C packages/desktop exec playwright test test/e2e/titlebar-selection-word-count.spec.ts

Screenshots

test

Notes for reviewers [optional]

The compact title-bar counter keeps the existing document count as the first value and appends the selected text count when there is a non-empty selection, e.g. W 89 / 14.


By submitting this pull request, I confirm that my contribution is made under the terms of the MIT license.

Copilot AI review requested due to automatic review settings June 11, 2026 20:02

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Adds selection-aware word count reporting and surfaces it in the title bar (including tooltip details), with an E2E test to validate the displayed “Document / Selection” ordering.

Changes:

  • Track and reset selectionWordCount in the editor store and propagate it through the app to the title bar.
  • Compute wordCount for new/created documents at state creation time.
  • Add E2E coverage verifying title bar text and tooltip content for document vs selection counts.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
packages/desktop/test/e2e/titlebar-selection-word-count.spec.ts New E2E test asserting title bar and tooltip behavior for selection counts
packages/desktop/src/renderer/src/store/help.ts Seed wordCount field when constructing file state
packages/desktop/src/renderer/src/store/editor.ts Add selectionWordCount to store state, setter action, and reset points
packages/desktop/src/renderer/src/pages/app.vue Pass selectionWordCount down into the title bar component
packages/desktop/src/renderer/src/components/titleBar/index.vue Display “document / selection” pair counts in title bar text + tooltip
packages/desktop/src/renderer/src/components/editorWithTabs/sourceCode.vue Update selection word count from CodeMirror selection
packages/desktop/src/renderer/src/components/editorWithTabs/editor.vue Update selection word count from Muya + native selectionchange

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@Renakoni
Renakoni requested a review from Copilot June 11, 2026 20:53

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 16 out of 16 changed files in this pull request and generated 7 comments.

@Jocs

Jocs commented Jun 15, 2026

Copy link
Copy Markdown
Member

Please solve Copilot inline comments.

@Jocs

Jocs commented Jun 15, 2026

Copy link
Copy Markdown
Member

Please solve Copilot inline comments. @Renakoni

@Renakoni
Renakoni requested a review from Copilot June 17, 2026 07:29

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 16 out of 16 changed files in this pull request and generated 5 comments.

@Renakoni
Renakoni requested a review from Copilot June 17, 2026 07:46

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 16 out of 16 changed files in this pull request and generated 1 comment.

@Renakoni
Renakoni requested a review from Copilot June 17, 2026 07:54

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 16 out of 16 changed files in this pull request and generated 4 comments.

@Renakoni
Renakoni requested a review from Copilot June 17, 2026 08:03

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 16 out of 16 changed files in this pull request and generated 2 comments.

@Renakoni

Copy link
Copy Markdown
Contributor Author

@Jocs Thanks for the review. I addressed the Copilot inline comments in the latest commits.
Changes made:

-Guarded native selected text so it is only used when the selection is inside the editor container.
-Preserved the original source-mode cursor/selection when switching back to WYSIWYG.
-Cleared selected word count on editor teardown.
-Added/updated E2E coverage for WYSIWYG selection, source-code selection, tab switching, and source-mode handoff
Please let me know if anything else should be adjusted.Thanks a Lot.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 17 out of 17 changed files in this pull request and generated 2 comments.

@Jocs

Jocs commented Jul 7, 2026

Copy link
Copy Markdown
Member

@Jocs Hello, may I ask when it can be merged? I need this feature.

I'm currently traveling and don't have much time to maintain the open-source project recently. I'll be able to get back to it in a week or two.

Renakoni and others added 2 commits July 9, 2026 21:21
…-text-word-count

# Conflicts:
#	packages/desktop/src/renderer/src/components/titleBar/index.vue
@Jocs

Jocs commented Sep 4, 2026

Copy link
Copy Markdown
Member

Is there a way to completely remove the native selectionchange handler? If we can’t calculate the character count of the selected text using Muya’s selection change event right now, shouldn’t we fix Muya instead? @Renakoni

@Renakoni

Copy link
Copy Markdown
Contributor Author

@Jocs I've addressed this in 44378fe by fixing Muya and removing the desktop's native selectionchange handler.

editor.vue now updates the selected count from Muya's selection-change event using the public muya.getSelectedText() API. Selected text comes from the document model, including rectangular table selections, so the desktop no longer clones DOM ranges or accesses table-selection internals.

Muya now reports selection changes during dragging and maps paragraph/element boundaries and rendered math/ruby endpoints to source offsets. The browser event is still observed inside Muya, with listener cleanup owned by its event center. These live notifications do not rewrite the DOM selection or overwrite the committed editing cursor, preserving dragging and keyboard format-marker updates. Table clearing and document replacement also update the selected count.

Added regression coverage for these paths, selection direction, editor isolation, IME composition, listener cleanup, source mode, and tab switching.

Local validation on Windows passed:

  • Full Muya unit suite: 1,467 tests; related desktop unit tests: 36.
  • Chromium regression tests: 28; Electron title-bar tests: 14.
  • Muya and desktop type checks and builds, lint (no errors; existing warnings remain), and Muya's circular-dependency check.

The Electron tests ran with their windows hidden and renderer-error assertions enabled. Cross-platform CI will provide the remaining platform checks.

@Renakoni

Copy link
Copy Markdown
Contributor Author

Fixed the CI failures in ec2e512 and synced the branch with develop:

  • The clipboard key handler now respects handled events and requires a real text range before cross-block replacement. Space/Escape image preview preserves the image; explicit deletion and cut remain covered by regression tests.
  • Source mode retains control of Paragraph/Format menu availability.
  • Added the missing Dutch counter translations and made the Escape search test wait for the new query's actual highlight.

I reviewed the text/image/table selection boundaries and source-mode transitions. Desktop selection counting continues to use Muya's events and getSelectedText().

All 14 test/check/build jobs now pass on b63fb92: 812 desktop unit tests, 1,606 Muya unit tests, 239 desktop E2E tests (4 skipped), and 293 Muya Chromium E2E tests (3 passed on automatic retry). Local regression coverage also passed: 71 Muya tests and 36 Electron tests.

The empty follow-up commit only retriggered CI after an electron-builder Snap/AppImage race deleted the shared chrome-sandbox during packaging. All five installer builds passed on the rerun. Muya E2E still has occasional retries around reading Markdown immediately after edits; no test assertions, timeouts, or retry settings were relaxed.

Jocs and others added 9 commits September 18, 2026 19:30
…ion model

The Selection modules are due a rework, so this keeps the engine side of the
feature to what a word counter needs: a read-only `getSelectedText()` that
walks the committed selection.

Reverted, to be revisited with that rework:

- the `document`-level `selectionchange` listener. It moved notification from
  "the selection was committed" to "the native range moved", so a drag emitted
  one `selection-change` per mousemove instead of one on release. Each reaches
  the desktop as an application-menu rebuild over IPC, a cursor persist and a
  recount, and re-entered the marktext#628/marktext#3329 auto-scroll mid-drag.
- the `getSelection()` endpoint rework (container boundaries, `data-start` /
  `data-end` on rendered previews, collapsed direction). `getSelection()` is
  what cut, copy and typing resolve against; widening it belongs in its own
  change, with its own cut/paste coverage.
- `Selection.getSelection()` returning null outside a text selection, and the
  guards it forced in turn: the clipboard keydown fallthrough that deleted a
  selected image on Space, `TableRectSelection.hasSelection` gating on
  `_isSelecting`, and `ScrollPage.updateState` activating a selection type.
- `getTextContent()` counting an `<img>` as its `data-raw`, which changes
  `getOffsetOfParagraph()` for every caller.
- the six `selection-change` emits in `TableRectSelection`, which fired per
  mousemove and carried `{kind}` alone — a payload the desktop reads as an
  empty selection.

A frozen rectangular table selection drops the native range, so it now reports
no text rather than its cells.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`nativeSelectionChange.spec.ts` and the drag-time halves of the E2E suite
asserted the live notification path that is no longer there. What remains
covers the API itself: the separator rules per container as unit tests, and
the real browser interactions a host counts words for — drag, keyboard,
caret, a rendered formula, and a selection outside the editor.

The `parityPreviewImage` additions guarded the clipboard keydown fallthrough,
which is also gone.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…cations

`selection-change` now arrives once per committed selection, so the counter no
longer needs a text cache to absorb a per-mousemove storm: a caret reports no
text and returns early, and a real selection is recounted when it changes.
Dropping the cache also drops the full selected string each editor was holding
until it unmounted, and the cross-component coupling where two copies of
`lastSelectedText` wrote one store field.

Source mode keys its own dedup on CodeMirror's ranges instead, since
`cursorActivity` does fire per drag step and reading the ranges is cheaper
than copying the selection.

A block commits only a selection it owns both ends of, so growing one across
blocks with Shift+arrows fires nothing; the existing keyup listener covers
that case.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The tooltip's `:content` binding was replaced by a slot, and `HASH[*].full`
was read only by that binding — including `(with space)character`, which
existed for the pluralizing template around it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`docState.wordCount` is a zeroed object, not a sentinel, so it cannot tell a
caller-supplied count from an absent one — which is why the check has to look
at `src` even though `documentStateKeys` already copied the value across.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The spec drove selections by building a range over `p.mu-paragraph` and firing
a synthetic `selectionchange`; it now drags and types like a user, which is
also what the engine reports on. The table cases go with the rectangular
selection support, except one that pins the current no-count behaviour.

`find-replace` gets its `.mu-highlight` count assertion back — it was relaxed
for the timing the per-mousemove notifications introduced — and the
`image-viewer` guards for the clipboard keydown fallthrough go with it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A rendered preview is `contenteditable="false"`, so a range that starts or
ends on one resolves to no content block — which a paragraph holding nothing
but a formula always does. The formula case now covers a mixed paragraph,
where the endpoints do land in text, and a second test records the gap the
Selection rework has to close.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Jocs

Jocs commented Sep 18, 2026

Copy link
Copy Markdown
Member

Thanks for sticking with this one — three months and a dozen review rounds, and moving the extraction into the engine in the last round was the right instinct. The problem isn't the work; it's that the feature landed on a module we're about to rebuild.

I've merged develop and pushed a reduction to your branch (b63fb928..190b3e0a). Nothing about the feature changed — what changed is how much of Selection it touches.

Why

The Selection modules are getting reworked (TextSelection / TableRectSelection / ImageSelection currently share one getSelection() exit with no agreement about what each should return, which is what made this PR grow the way it did). Anything invasive there now has to be rewritten in a few weeks, so the goal for this PR is: ship #4395, keep the engine surface to a read-only API.

The chain in the last revision is what convinced me — Selection.getSelection() returning null outside a text selection made Space delete a selected image, which needed the clipboard guard, which needed TableRectSelection.hasSelection to gate on _isSelecting, which needed ScrollPage.updateState to activate a selection type. Each fix was correct; the chain is the signal.

What the engine keeps

Three files, ~80 lines, all additive:

  • TextSelection.getSelectedText() + a getTextSeparator() helper (blank line between blocks; single newline inside code, tables and tight lists)
  • Selection.getSelectedText() — delegates
  • Muya.getSelectedText() — the public API

What was reverted, to revisit with the rework

  • The document-level selectionchange listener. It moved reporting from "the selection was committed" to "the native range moved", so a drag emitted one selection-change per mousemove instead of one on release. On the desktop side each of those is an application-menu rebuild over IPC (mt::editor-selection-changed → updateSelectionMenus, unthrottled), a cursor persist, a full selected-text extraction and a word count. It also re-entered the Improvement for auto scroll #628/scrolling up with arrow key doesn't scroll text in document #3329 auto-scroll mid-drag, so the document scrolled away under a held pointer.
  • The getSelection() endpoint rework — container boundaries, data-start/data-end on rendered previews, collapsed direction. getSelection() is what cut, copy and typing resolve against; widening it deserves its own PR with its own cut/paste coverage. (The preview branch also needs parseRange from utils/getLinkInfo.ts rather than bare Number() — a missing attribute silently becomes offset 0.)
  • getTextContent() counting an <img> as its data-raw, which changes getOffsetOfParagraph() for every caller.
  • The six TableRectSelection emits — per mousemove, and carrying {kind} alone, which the desktop reads as an empty selection.

What this costs, honestly

Two gaps, both pinned by tests so the rework has to decide about them deliberately:

  1. Rectangular table selections report no count. They drop the native range, and nothing notifies a host that they changed.
  2. A paragraph that is only a rendered formula reports no count. The preview is contenteditable="false", so both endpoints land on it and resolve to no content block. A mixed paragraph (mass energy $E = mc^2$ equivalence) works fine.

The count now updates when a selection is committed — mouse release, key release, Select All — rather than during the drag. For a title-bar counter that reads the same.

Cross-block Shift+arrow selections needed one extra touch: a block only commits a selection it owns both ends of, so growing one across blocks fires nothing. The desktop's existing keyup listener covers it.

Also in this push

  • editor.vue / sourceCode.vue: dropped the duplicated lastSelectedText cache. It existed to absorb the per-mousemove storm, and it pinned the entire selected string in memory until unmount. Source mode keys its dedup on CodeMirror's ranges instead, since cursorActivity genuinely does fire per drag step.
  • HASH[*].full in titleBar/index.vue — dead once the :content binding became a slot.
  • find-replace.spec.ts got its .mu-highlight count assertion back; it was relaxed for timing the removed notifications introduced.
  • nl.json / tr.json counter key order, to match the other locales.

Diff is now +663 / −66 across 23 files, down from +1318 / −47 across 31.

Verified locally

pnpm lint · pnpm typecheck · muya 1842 unit tests · desktop 820 unit tests · titlebar-selection-word-count 8/8 · muya selected-text e2e 6/6 · find-replace + image-viewer e2e.

Please take a look and tell me if I cut something you think should stay — happy to put any of it back. And the table/preview support isn't dropped, just queued behind the rework.

Jocs and others added 3 commits September 19, 2026 19:05
It exists for one engine gap — growing a selection across blocks reports
nothing — and comes out with the Selection rework, so say which change
removes it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Say the non-obvious fact and stop; the mechanism behind it reads from the
code itself.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Jocs
Jocs merged commit ba5d71d into marktext:develop Sep 19, 2026
16 checks passed
@Jocs Jocs mentioned this pull request Sep 19, 2026
1 task done
@Renakoni
Renakoni deleted the feature/selected-text-word-count branch September 19, 2026 16:01
Jocs added a commit to rkristelijn/marktext-fork that referenced this pull request Sep 22, 2026
Resolve three conflicts introduced since the branch point (marktext#4874):

- store/editor.ts: keep both new state fields — `activeHeadingSlug` from
  this branch and `selectionWordCount` from develop (marktext#4457).
- editor.vue: keep both `@/util/tocNavigation` imports — develop's
  `getTocHeadingScrollTop` (marktext#5292 TOC scroll alignment) alongside
  `TOP_LEVEL_HEADINGS_SELECTOR`, which is still exported from there.

The locale additions in this branch (`sideBar.toc.expandAll` /
`collapseAll`) already landed on develop via marktext#5137, so all twelve locale
files merged to identical content — including the `nl` and `ru` files
added after this branch point.

Verified on the merge result: `vue-tsc --noEmit` clean, eslint clean
(warnings only), 875/875 desktop unit tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Wangqkoe pushed a commit to Wangqkoe/marktext that referenced this pull request Oct 21, 2026
Port of upstream ba5d71d. The muya side
(`getSelectedText()` and its unit / e2e specs) applies as-is. Upstream
showed the count in the title bar from a single editor-store field; here
the count lives in the status bar and the window can hold several panes,
so the selection rides on the existing caret report instead:

- the focused pane's WYSIWYG or CodeMirror editor adds the counts of its
  selection to each caret report; unfocused panes leave them out, so they
  cannot clear the focused pane's count;
- a new caret session (switching document or mode) clears it with the
  caret position;
- the status bar shows "W Selected 12 / Total 345" while text is selected,
  and the tooltip shows the same pair for each counter.

Also translates the tooltip's hard-coded "All characters" label.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] 增加选中文本的字数统计

4 participants