Merge branch 'master' into master

This commit is contained in:
Luke Leppan 2023-03-30 00:38:07 +02:00 committed by GitHub
commit 66c00b24c2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 142 additions and 17 deletions

View file

@ -1,13 +1,11 @@
# Better Word Count # Better Word Count
![GitHub Workflow Status](https://img.shields.io/github/workflow/status/lukeleppan/better-word-count/Build%20Release?logo=github&style=for-the-badge) ![GitHub release (latest by date)](https://img.shields.io/github/v/release/lukeleppan/better-word-count?style=for-the-badge) ![Obsidian Downloads](https://img.shields.io/badge/dynamic/json?logo=obsidian&color=%23483699&label=downloads&query=%24%5B%22better-word-count%22%5D.downloads&url=https%3A%2F%2Fraw.githubusercontent.com%2Fobsidianmd%2Fobsidian-releases%2Fmaster%2Fcommunity-plugin-stats.json&style=for-the-badge) ![GitHub manifest version](https://img.shields.io/github/manifest-json/v/lukeleppan/better-word-count?color=magenta&label=version&style=for-the-badge) ![GitHub Release Date](https://img.shields.io/github/release-date/lukeleppan/better-word-count?style=for-the-badge) ![Lines of code](https://img.shields.io/tokei/lines/github/lukeleppan/better-word-count?style=for-the-badge) ![Obsidian Downloads](https://img.shields.io/badge/dynamic/json?logo=obsidian&color=%23483699&label=downloads&query=%24%5B%22better-word-count%22%5D.downloads&url=https%3A%2F%2Fraw.githubusercontent.com%2Fobsidianmd%2Fobsidian-releases%2Fmaster%2Fcommunity-plugin-stats.json&style=for-the-badge)
**IMPORTANT NOTICE:** Due to the introduction of the new Live Preview feature, this plugin needed to be almost entirely rewritten. It will be unstable for a while so please report bugs on github.
This plugin is the same as the built-in **Word Count** plugin, except when you select text, it will count the selected word instead of the whole document. I recommend turning off the built-in **Word Count** because this plugin is designed to replace that. This plugin also has the ability to store statistics about your vault.
![Better Count Word](https://raw.githubusercontent.com/lukeleppan/better-word-count/master/assets/better-word-count.gif) ![Better Count Word](https://raw.githubusercontent.com/lukeleppan/better-word-count/master/assets/better-word-count.gif)
This plugin is the same as the built-in **Word Count** plugin, except when you select text, it will count the selected word instead of the whole document. I recommend turning off the built-in **Word Count** because this plugin is designed to replace that. This plugin also has the ability to store statistics about your vault.
## Features ## Features
- Allows you to store statistics about your vault. - Allows you to store statistics about your vault.

View file

@ -1,3 +1,4 @@
import { Transaction } from "@codemirror/state";
import { import {
ViewUpdate, ViewUpdate,
PluginValue, PluginValue,
@ -22,9 +23,19 @@ class EditorPlugin implements PluginValue {
} }
const tr = update.transactions[0]; const tr = update.transactions[0];
if (!tr) return;
if (!tr) {
return;
}
// When selecting text with Shift+Home the userEventType is undefined.
// This is probably a bug in codemirror, for the time being doing an explict check
// for the type allows us to update the stats for the selection.
const userEventTypeUndefined =
tr.annotation(Transaction.userEvent) === undefined;
if ( if (
tr.isUserEvent("select") && (tr.isUserEvent("select") || userEventTypeUndefined) &&
tr.newSelection.ranges[0].from !== tr.newSelection.ranges[0].to tr.newSelection.ranges[0].from !== tr.newSelection.ranges[0].to
) { ) {
let text = ""; let text = "";

View file

@ -33,7 +33,7 @@ export default class BetterWordCount extends Plugin {
// Handle Statistics // Handle Statistics
if (this.settings.collectStats) { if (this.settings.collectStats) {
this.statsManager = new StatsManager(this.app.vault, this.app.workspace); this.statsManager = new StatsManager(this.app.vault, this.app.workspace, this);
} }
// Handle Status Bar // Handle Status Bar

View file

@ -4,6 +4,7 @@ export enum MetricCounter {
sentences, sentences,
footnotes, footnotes,
citations, citations,
pages,
files, files,
} }
@ -40,6 +41,7 @@ export interface BetterWordCountSettings {
altBar: StatusBarItem[]; altBar: StatusBarItem[];
countComments: boolean; countComments: boolean;
collectStats: boolean; collectStats: boolean;
pageWords: number;
} }
export const DEFAULT_SETTINGS: BetterWordCountSettings = { export const DEFAULT_SETTINGS: BetterWordCountSettings = {
@ -73,4 +75,5 @@ export const DEFAULT_SETTINGS: BetterWordCountSettings = {
], ],
countComments: false, countComments: false,
collectStats: false, collectStats: false,
pageWords: 300,
}; };

View file

@ -1,4 +1,4 @@
import { App, PluginSettingTab, Setting, ToggleComponent } from "obsidian"; import { App, PluginSettingTab, Setting, ToggleComponent, TextComponent } from "obsidian";
import type BetterWordCount from "src/main"; import type BetterWordCount from "src/main";
import { addStatusBarSettings } from "./StatusBarSettings"; import { addStatusBarSettings } from "./StatusBarSettings";
@ -37,6 +37,18 @@ export default class BetterWordCountSettingsTab extends PluginSettingTab {
await this.plugin.saveSettings(); await this.plugin.saveSettings();
}); });
}); });
new Setting(containerEl)
.setName("Page Word Count")
.setDesc("Set how many words count as one \"page\"")
.addText((text: TextComponent) => {
text.inputEl.type = "number";
text.setPlaceholder("300");
text.setValue(this.plugin.settings.pageWords.toString());
text.onChange(async (value: string) => {
this.plugin.settings.pageWords = parseInt(value);
await this.plugin.saveSettings();
});
});
// Status Bar Settings // Status Bar Settings
addStatusBarSettings(this.plugin, containerEl); addStatusBarSettings(this.plugin, containerEl);

View file

@ -22,6 +22,8 @@
return "Footnotes in Note" return "Footnotes in Note"
case MetricCounter.citations: case MetricCounter.citations:
return "Citations in Note" return "Citations in Note"
case MetricCounter.pages:
return "Pages in Note"
case MetricCounter.files: case MetricCounter.files:
return "Total Notes" return "Total Notes"
} }
@ -37,6 +39,8 @@
return "Daily Footnotes" return "Daily Footnotes"
case MetricCounter.citations: case MetricCounter.citations:
return "Daily Citations" return "Daily Citations"
case MetricCounter.pages:
return "Daily Pages"
case MetricCounter.files: case MetricCounter.files:
return "Total Notes" return "Total Notes"
} }
@ -52,6 +56,8 @@
return "Total Footnotes" return "Total Footnotes"
case MetricCounter.citations: case MetricCounter.citations:
return "Total Citations" return "Total Citations"
case MetricCounter.pages:
return "Total Pages"
case MetricCounter.files: case MetricCounter.files:
return "Total Notes" return "Total Notes"
} }
@ -195,6 +201,7 @@
<option value={MetricCounter.sentences}>Sentences</option> <option value={MetricCounter.sentences}>Sentences</option>
<option value={MetricCounter.footnotes}>Footnotes</option> <option value={MetricCounter.footnotes}>Footnotes</option>
<option value={MetricCounter.citations}>Citations</option> <option value={MetricCounter.citations}>Citations</option>
<option value={MetricCounter.pages}>Pages</option>
<option value={MetricCounter.files}>Files</option> <option value={MetricCounter.files}>Files</option>
</select> </select>
</div> </div>
@ -364,6 +371,7 @@
<option value={MetricCounter.sentences}>Sentences</option> <option value={MetricCounter.sentences}>Sentences</option>
<option value={MetricCounter.footnotes}>Footnotes</option> <option value={MetricCounter.footnotes}>Footnotes</option>
<option value={MetricCounter.citations}>Citations</option> <option value={MetricCounter.citations}>Citations</option>
<option value={MetricCounter.pages}>Pages</option>
<option value={MetricCounter.files}>Files</option> <option value={MetricCounter.files}>Files</option>
</select> </select>
</div> </div>

View file

@ -9,6 +9,7 @@ export interface Day {
words: number; words: number;
characters: number; characters: number;
sentences: number; sentences: number;
pages: number;
files: number; files: number;
footnotes: number; footnotes: number;
citations: number; citations: number;
@ -17,6 +18,7 @@ export interface Day {
totalSentences: number; totalSentences: number;
totalFootnotes: number; totalFootnotes: number;
totalCitations: number; totalCitations: number;
totalPages: number;
} }
export type ModifiedFiles = Record<string, FileStat>; export type ModifiedFiles = Record<string, FileStat>;
@ -27,6 +29,7 @@ export interface FileStat {
words: CountDiff; words: CountDiff;
characters: CountDiff; characters: CountDiff;
sentences: CountDiff; sentences: CountDiff;
pages: CountDiff;
} }
export interface CountDiff { export interface CountDiff {

View file

@ -1,10 +1,12 @@
import { debounce, Debouncer, TFile, Vault, Workspace } from "obsidian"; import { debounce, Debouncer, TFile, Vault, Workspace } from "obsidian";
import type BetterWordCount from "../main";
import { STATS_FILE } from "../constants"; import { STATS_FILE } from "../constants";
import type { Day, VaultStatistics } from "./Stats"; import type { Day, VaultStatistics } from "./Stats";
import moment from "moment"; import moment from "moment";
import { import {
getCharacterCount, getCharacterCount,
getSentenceCount, getSentenceCount,
getPageCount,
getWordCount, getWordCount,
getCitationCount, getCitationCount,
getFootnoteCount, getFootnoteCount,
@ -13,13 +15,15 @@ import {
export default class StatsManager { export default class StatsManager {
private vault: Vault; private vault: Vault;
private workspace: Workspace; private workspace: Workspace;
private plugin: BetterWordCount;
private vaultStats: VaultStatistics; private vaultStats: VaultStatistics;
private today: string; private today: string;
public debounceChange; public debounceChange;
constructor(vault: Vault, workspace: Workspace) { constructor(vault: Vault, workspace: Workspace, plugin: BetterWordCount) {
this.vault = vault; this.vault = vault;
this.workspace = workspace; this.workspace = workspace;
this.plugin = plugin;
this.debounceChange = debounce( this.debounceChange = debounce(
(text: string) => this.change(text), (text: string) => this.change(text),
50, 50,
@ -80,11 +84,13 @@ export default class StatsManager {
const totalSentences = await this.calcTotalSentences(); const totalSentences = await this.calcTotalSentences();
const totalFootnotes = await this.calcTotalFootnotes(); const totalFootnotes = await this.calcTotalFootnotes();
const totalCitations = await this.calcTotalCitations(); const totalCitations = await this.calcTotalCitations();
const totalPages = await this.calcTotalPages();
const newDay: Day = { const newDay: Day = {
words: 0, words: 0,
characters: 0, characters: 0,
sentences: 0, sentences: 0,
pages: 0,
files: 0, files: 0,
footnotes: 0, footnotes: 0,
citations: 0, citations: 0,
@ -93,6 +99,7 @@ export default class StatsManager {
totalSentences: totalSentences, totalSentences: totalSentences,
totalFootnotes: totalFootnotes, totalFootnotes: totalFootnotes,
totalCitations: totalCitations, totalCitations: totalCitations,
totalPages: totalPages,
}; };
this.vaultStats.modifiedFiles = {}; this.vaultStats.modifiedFiles = {};
@ -107,6 +114,8 @@ export default class StatsManager {
const currentSentences = getSentenceCount(text); const currentSentences = getSentenceCount(text);
const currentCitations = getCitationCount(text); const currentCitations = getCitationCount(text);
const currentFootnotes = getFootnoteCount(text); const currentFootnotes = getFootnoteCount(text);
const currentPages = getPageCount(text, this.plugin.settings.pageWords);
if ( if (
this.vaultStats.history.hasOwnProperty(this.today) && this.vaultStats.history.hasOwnProperty(this.today) &&
this.today === moment().format("YYYY-MM-DD") this.today === moment().format("YYYY-MM-DD")
@ -124,11 +133,15 @@ export default class StatsManager {
currentSentences - modFiles[fileName].footnotes.current; currentSentences - modFiles[fileName].footnotes.current;
this.vaultStats.history[this.today].totalCitations += this.vaultStats.history[this.today].totalCitations +=
currentSentences - modFiles[fileName].citations.current; currentSentences - modFiles[fileName].citations.current;
this.vaultStats.history[this.today].totalPages +=
currentPages - modFiles[fileName].pages.current;
modFiles[fileName].words.current = currentWords; modFiles[fileName].words.current = currentWords;
modFiles[fileName].characters.current = currentCharacters; modFiles[fileName].characters.current = currentCharacters;
modFiles[fileName].sentences.current = currentSentences; modFiles[fileName].sentences.current = currentSentences;
modFiles[fileName].footnotes.current = currentSentences; modFiles[fileName].footnotes.current = currentFootnotes;
modFiles[fileName].citations.current = currentSentences; modFiles[fileName].citations.current = currentCitations;
modFiles[fileName].pages.current = currentPages;
} else { } else {
modFiles[fileName] = { modFiles[fileName] = {
words: { words: {
@ -150,6 +163,9 @@ export default class StatsManager {
citations: { citations: {
initial: currentCitations, initial: currentCitations,
current: currentCitations, current: currentCitations,
pages: {
initial: currentPages,
current: currentPages,
}, },
}; };
} }
@ -169,6 +185,7 @@ export default class StatsManager {
Math.max(0, counts.sentences.current - counts.sentences.initial) Math.max(0, counts.sentences.current - counts.sentences.initial)
) )
.reduce((a, b) => a + b, 0); .reduce((a, b) => a + b, 0);
const footnotes = Object.values(modFiles) const footnotes = Object.values(modFiles)
.map((counts) => .map((counts) =>
Math.max(0, counts.footnotes.current - counts.footnotes.initial) Math.max(0, counts.footnotes.current - counts.footnotes.initial)
@ -178,6 +195,10 @@ export default class StatsManager {
.map((counts) => .map((counts) =>
Math.max(0, counts.citations.current - counts.citations.initial) Math.max(0, counts.citations.current - counts.citations.initial)
) )
const pages = Object.values(modFiles)
.map((counts) =>
Math.max(0, counts.pages.current - counts.pages.initial)
)
.reduce((a, b) => a + b, 0); .reduce((a, b) => a + b, 0);
this.vaultStats.history[this.today].words = words; this.vaultStats.history[this.today].words = words;
@ -185,6 +206,7 @@ export default class StatsManager {
this.vaultStats.history[this.today].sentences = sentences; this.vaultStats.history[this.today].sentences = sentences;
this.vaultStats.history[this.today].footnotes = footnotes; this.vaultStats.history[this.today].footnotes = footnotes;
this.vaultStats.history[this.today].citations = citations; this.vaultStats.history[this.today].citations = citations;
this.vaultStats.history[this.today].pages = pages;
this.vaultStats.history[this.today].files = this.getTotalFiles(); this.vaultStats.history[this.today].files = this.getTotalFiles();
await this.update(); await this.update();
@ -205,6 +227,7 @@ export default class StatsManager {
todayHist.totalSentences = await this.calcTotalSentences(); todayHist.totalSentences = await this.calcTotalSentences();
todayHist.totalFootnotes = await this.calcTotalFootnotes(); todayHist.totalFootnotes = await this.calcTotalFootnotes();
todayHist.totalCitations = await this.calcTotalCitations(); todayHist.totalCitations = await this.calcTotalCitations();
todayHist.totalPages = await this.calcTotalPages();
this.update(); this.update();
} else { } else {
this.updateToday(); this.updateToday();
@ -248,6 +271,20 @@ export default class StatsManager {
} }
return sentence; return sentence;
} }
private async calcTotalPages(): Promise<number> {
let pages = 0;
const files = this.vault.getFiles();
for (const i in files) {
const file = files[i];
if (file.extension === "md") {
pages += getPageCount(await this.vault.cachedRead(file), this.plugin.settings.pageWords);
}
}
return pages;
}
private async calcTotalFootnotes(): Promise<number> { private async calcTotalFootnotes(): Promise<number> {
let footnotes = 0; let footnotes = 0;
@ -285,6 +322,7 @@ export default class StatsManager {
return this.vaultStats.history[this.today].sentences; return this.vaultStats.history[this.today].sentences;
} }
public getDailyFootnotes(): number { public getDailyFootnotes(): number {
return this.vaultStats.history[this.today].footnotes; return this.vaultStats.history[this.today].footnotes;
} }
@ -292,6 +330,9 @@ export default class StatsManager {
public getDailyCitations(): number { public getDailyCitations(): number {
return this.vaultStats.history[this.today].citations; return this.vaultStats.history[this.today].citations;
} }
public getDailyPages(): number {
return this.vaultStats.history[this.today].pages;
}
public getTotalFiles(): number { public getTotalFiles(): number {
return this.vault.getMarkdownFiles().length; return this.vault.getMarkdownFiles().length;
@ -311,7 +352,7 @@ export default class StatsManager {
if (!this.vaultStats) return await this.calcTotalSentences(); if (!this.vaultStats) return await this.calcTotalSentences();
return this.vaultStats.history[this.today].totalSentences; return this.vaultStats.history[this.today].totalSentences;
} }
public async getTotalFootnotes(): Promise<number> { public async getTotalFootnotes(): Promise<number> {
if (!this.vaultStats) return await this.calcTotalFootnotes(); if (!this.vaultStats) return await this.calcTotalFootnotes();
return this.vaultStats.history[this.today].totalFootnotes; return this.vaultStats.history[this.today].totalFootnotes;
@ -322,4 +363,8 @@ export default class StatsManager {
return this.vaultStats.history[this.today].totalCitations; return this.vaultStats.history[this.today].totalCitations;
} }
public async getTotalPages(): Promise<number> {
if (!this.vaultStats) return await this.calcTotalPages();
return this.vaultStats.history[this.today].totalPages;
}
} }

View file

@ -6,6 +6,7 @@ import {
getSentenceCount, getSentenceCount,
getCitationCount, getCitationCount,
getFootnoteCount, getFootnoteCount,
getPageCount,
} from "src/utils/StatUtils"; } from "src/utils/StatUtils";
import { debounce } from "obsidian"; import { debounce } from "obsidian";
@ -149,6 +150,26 @@ export default class StatusBar {
: 0)); : 0));
break; break;
} }
} else if (metric.counter === MetricCounter.pages) {
switch (metric.type) {
case MetricType.file:
display = display + getPageCount(text, this.plugin.settings.pageWords);
break;
case MetricType.daily:
display =
display +
(this.plugin.settings.collectStats
? this.plugin.statsManager.getDailyPages()
: 0);
break;
case MetricType.total:
display =
display +
(await (this.plugin.settings.collectStats
? this.plugin.statsManager.getTotalPages()
: 0));
break;
}
} else if (metric.counter === MetricCounter.files) { } else if (metric.counter === MetricCounter.files) {
switch (metric.type) { switch (metric.type) {
case MetricType.file: case MetricType.file:
@ -252,7 +273,7 @@ export default class StatusBar {
break; break;
} }
} else if (metric.counter === MetricCounter.footnotes) { } else if (metric.counter === MetricCounter.footnotes) {
switch (metric.type) { switch (metric.type) {
case MetricType.file: case MetricType.file:
display = display + 0; display = display + 0;
break; break;
@ -260,14 +281,14 @@ export default class StatusBar {
display = display =
display + display +
(this.plugin.settings.collectStats (this.plugin.settings.collectStats
? this.plugin.statsManager.getDailyFootnotes() ? this.plugin.statsManager.getDailyFootnotes()
: 0); : 0);
break; break;
case MetricType.total: case MetricType.total:
display = display =
display + display +
(await (this.plugin.settings.collectStats (await (this.plugin.settings.collectStats
? this.plugin.statsManager.getTotalFootnotes() ? this.plugin.statsManager.getTotalFootnotes()
: 0)); : 0));
break; break;
} }
@ -291,6 +312,26 @@ export default class StatusBar {
: 0)); : 0));
break; break;
} }
} else if (metric.counter === MetricCounter.pages) {
switch (metric.type) {
case MetricType.file:
display = display + 0;
break;
case MetricType.daily:
display =
display +
(this.plugin.settings.collectStats
? this.plugin.statsManager.getDailyPages()
: 0);
break;
case MetricType.total:
display =
display +
(await (this.plugin.settings.collectStats
? this.plugin.statsManager.getTotalPages()
: 0));
break;
}
} else if (metric.counter === MetricCounter.files) { } else if (metric.counter === MetricCounter.files) {
switch (metric.type) { switch (metric.type) {
case MetricType.file: case MetricType.file:

View file

@ -54,6 +54,10 @@ export function getSentenceCount(text: string): number {
return sentences; return sentences;
} }
export function getPageCount(text: string, pageWords: number): number {
return parseFloat((getWordCount(text) / pageWords).toFixed(1));
}
export function getTotalFileCount(vault: Vault): number { export function getTotalFileCount(vault: Vault): number {
return vault.getMarkdownFiles().length; return vault.getMarkdownFiles().length;
} }