diff --git a/dwertheimer.TaskAutomations/src/NPTaskScanAndProcess.js b/dwertheimer.TaskAutomations/src/NPTaskScanAndProcess.js index 7105d4c59..5c4649875 100644 --- a/dwertheimer.TaskAutomations/src/NPTaskScanAndProcess.js +++ b/dwertheimer.TaskAutomations/src/NPTaskScanAndProcess.js @@ -156,7 +156,6 @@ export function getSingleTaskOptions(origPara: TParagraph, todayLines: any, cont { label: `! Set priority to p1`, value: '__p1__' }, { label: `!! Set priority to p2`, value: '__p2__' }, { label: `!!! Set priority to p3`, value: '__p3__' }, - { label: `!!!! Set priority to p4`, value: '__p4__' }, { label: `x! Remove priority from task (p0)`, value: '__p0__' }, ] if (NotePlan.environment.platform === 'macOS') { @@ -287,7 +286,7 @@ export function handlePriorityAction(origPara: TParagraph, userChoice: string): __p1__: '!', __p2__: '!!', __p3__: '!!!', - __p4__: '!!!!', + __p4__: '>>', // '!!!!' isn't a NotePlan priority; NotePlan's level 4 is '>>'. Kept as an alias for any saved choice. '__>>__': '>>', } const prioritySymbol = priorityMap[userChoice] || '' diff --git a/helpers/HTMLView.js b/helpers/HTMLView.js index c72eb3ff0..edd194ec1 100644 --- a/helpers/HTMLView.js +++ b/helpers/HTMLView.js @@ -13,6 +13,7 @@ import { getStoredWindowRect, getWindowFromCustomId, isHTMLWindowOpen, storeWind import { generateCSSFromTheme, RGBColourConvert } from '@helpers/NPThemeToCSS' import { isTermInEventLinkHiddenPart, isTermInNotelinkOrURI, isTermInMarkdownPath } from '@helpers/paragraph' import { RE_EVENT_LINK, RE_SYNC_MARKER } from '@helpers/regex' +import { getPriorityLevel } from '@helpers/taskPriority' import { getTimeBlockString, isTimeBlockLine } from '@helpers/timeblocks' import { usersVersionHas } from '@helpers/NPVersions' @@ -192,17 +193,14 @@ function taskStateFromBox(box: string, marker: string): string { } /** - * Leading `!` / `!!` / `!!!` / `>>` on the task text. These are the only supported priority markers. + * Leading `!` / `!!` / `!!!` / `>>` on the task text, followed by a space. These are the only supported priority markers + * (see helpers/taskPriority.js). * @param {string} text * @returns {string} `priority1`..`priority4`, or '' */ function priorityClassFromTaskText(text: string): string { - const match = text.match(/^(!!!|!!|!|>>)(?=\s|$)/) - if (!match) return '' - if (match[1] === '>>') return 'priority4' - if (match[1] === '!!!') return 'priority3' - if (match[1] === '!!') return 'priority2' - return 'priority1' + const level = getPriorityLevel(text) + return level > 0 ? `priority${String(level)}` : '' } /** diff --git a/helpers/__tests__/paragraph.test.js b/helpers/__tests__/paragraph.test.js index 639c072e0..918de40aa 100644 --- a/helpers/__tests__/paragraph.test.js +++ b/helpers/__tests__/paragraph.test.js @@ -947,3 +947,41 @@ describe('paragraph.js', () => { }) }) }) + +describe('priority markers (NotePlan: leading !, !!, !!! or >> followed by a space)', () => { + const para = (content: string): any => ({ content, note: null }) + describe('getTaskPriority()', () => { + test('reads only a leading marker followed by a space', () => { + expect(p.getTaskPriority('!! x')).toBe(2) + expect(p.getTaskPriority('>> x')).toBe(4) + expect(p.getTaskPriority('x !!')).toBe(0) + expect(p.getTaskPriority('Pay rent !>2026-12-05')).toBe(0) + expect(p.getTaskPriority('!>2026-12-05 Pay rent')).toBe(0) + }) + }) + describe('changePriority()', () => { + test('keeps due dates, images and other ! in the text', () => { + expect(p.changePriority(para('Pay rent !>2026-12-05'), '!!')).toBe('!! Pay rent !>2026-12-05') + expect(p.changePriority(para('Wow! Great ![img](a.png)'), '!')).toBe('! Wow! Great ![img](a.png)') + }) + test('replaces or removes an existing marker', () => { + expect(p.changePriority(para('! x'), '>>')).toBe('>> x') + expect(p.changePriority(para('>> x'), '')).toBe('x') + }) + test("treats a marker that isn't NotePlan's (e.g. '!!!!') as no priority", () => { + expect(p.changePriority(para('! x'), '!!!!')).toBe('x') + }) + }) + describe('cyclePriorityStateUp() / cyclePriorityStateDown()', () => { + test('up keeps a due date', () => { + expect(p.cyclePriorityStateUp(para('Pay rent !>2026-12-05'))).toBe('! Pay rent !>2026-12-05') + }) + test('down from none goes to >>', () => { + expect(p.cyclePriorityStateDown(para('x'))).toBe('>> x') + }) + test('round trip', () => { + expect(p.cyclePriorityStateUp(para('>> x'))).toBe('x') + expect(p.cyclePriorityStateDown(para('! x'))).toBe('x') + }) + }) +}) diff --git a/helpers/__tests__/sorting.test.js b/helpers/__tests__/sorting.test.js index 7306d2b42..be800e735 100644 --- a/helpers/__tests__/sorting.test.js +++ b/helpers/__tests__/sorting.test.js @@ -630,6 +630,19 @@ describe('sorting.js', () => { expect(result).toEqual(defaultPriority) }) + test.each([ + ['!>2026-12-05 due date at the start', 0], + ['!2026-12-05 due date at the start', 0], + ['!x no space after the marker', 0], + ['!!!! four is not a NotePlan marker', 0], + ['>>x no space after the marker', 0], + ['!! x', 2], + ['! Pay rent !>2026-12-05', 1], + ])('NotePlan priority rules: %j -> %i', (content, expected) => { + const paragraph = new Paragraph({ type: 'open', content, filename: 'testFile.md' }) + expect(s.getNumericPriority(s.getSortableTask(paragraph))).toEqual(expected) + }) + test('should return -1 for unknown priority', () => { const paragraph = new Paragraph({ type: 'open', content: 'test content ??', filename: 'testFile.md' }) const result = s.getNumericPriority(s.getSortableTask(paragraph)) diff --git a/helpers/__tests__/taskPriority.test.js b/helpers/__tests__/taskPriority.test.js new file mode 100644 index 000000000..c82124e44 --- /dev/null +++ b/helpers/__tests__/taskPriority.test.js @@ -0,0 +1,77 @@ +/* globals describe, expect, test */ +import { getPriorityLevel, getPriorityMarker, nextPriorityLevel, removePriorityMarker, setPriorityLevel } from '../taskPriority' + +describe('taskPriority', () => { + describe('getPriorityLevel()', () => { + test.each([ + ['! task', 1], + ['!! task', 2], + ['!!! task', 3], + ['>> task', 4], + [' !! indented task', 2], + ['!task (no space)', 0], + ['>>task (no space)', 0], + ['!!!! four is not a NotePlan marker', 0], + ['task !! (not at the start)', 0], + ['task >> (not at the start)', 0], + ['!2026-12-05 due date first', 0], + ['!>2026-12-05 due date first', 0], + ['!>2026-W49 due week first', 0], + ['Pay rent !>2026-12-05', 0], + ['! Pay rent !>2026-12-05', 1], + ['![image](a.png) first', 0], + ['Wow! Great', 0], + ['', 0], + ['!', 0], + ])('%j -> %i', (content, expected) => { + expect(getPriorityLevel(content)).toBe(expected) + }) + }) + + test('getPriorityMarker() returns the marker itself', () => { + expect(getPriorityMarker('!!! x')).toBe('!!!') + expect(getPriorityMarker('>> x')).toBe('>>') + expect(getPriorityMarker('x')).toBe('') + }) + + describe('removePriorityMarker()', () => { + test('removes only the leading marker and its space', () => { + expect(removePriorityMarker('!! Pay rent !>2026-12-05')).toBe('Pay rent !>2026-12-05') + expect(removePriorityMarker('>> Wow! Great ![img](a.png)')).toBe('Wow! Great ![img](a.png)') + }) + test('leaves text without a NotePlan marker unchanged', () => { + expect(removePriorityMarker('!>2026-12-05 Pay rent')).toBe('!>2026-12-05 Pay rent') + expect(removePriorityMarker('!!!! four')).toBe('!!!! four') + expect(removePriorityMarker('Call Bob !!')).toBe('Call Bob !!') + }) + test('keeps leading whitespace', () => { + expect(removePriorityMarker(' ! x')).toBe(' x') + }) + }) + + describe('setPriorityLevel()', () => { + test('adds, replaces and removes the leading marker', () => { + expect(setPriorityLevel('Pay rent', 2)).toBe('!! Pay rent') + expect(setPriorityLevel('! Pay rent', 4)).toBe('>> Pay rent') + expect(setPriorityLevel('>> Pay rent', 0)).toBe('Pay rent') + }) + test('leaves due dates, images and other ! alone', () => { + expect(setPriorityLevel('Pay rent !>2026-12-05', 1)).toBe('! Pay rent !>2026-12-05') + expect(setPriorityLevel('!>2026-12-05 Pay rent', 3)).toBe('!!! !>2026-12-05 Pay rent') + expect(setPriorityLevel('Wow! Great ![img](a.png)', 1)).toBe('! Wow! Great ![img](a.png)') + }) + test('out-of-range levels mean no priority', () => { + expect(setPriorityLevel('!! x', 7)).toBe('x') + expect(setPriorityLevel('!! x', -1)).toBe('x') + }) + }) + + describe('nextPriorityLevel()', () => { + test('up: none -> ! -> !! -> !!! -> >> -> none', () => { + expect([0, 1, 2, 3, 4].map((l) => nextPriorityLevel(l, 'up'))).toEqual([1, 2, 3, 4, 0]) + }) + test('down: none -> >> -> !!! -> !! -> ! -> none', () => { + expect([0, 1, 2, 3, 4].map((l) => nextPriorityLevel(l, 'down'))).toEqual([4, 0, 1, 2, 3]) + }) + }) +}) diff --git a/helpers/paragraph.js b/helpers/paragraph.js index 74e6bff3a..171e47a30 100644 --- a/helpers/paragraph.js +++ b/helpers/paragraph.js @@ -18,6 +18,7 @@ import { } from '@helpers/regex' import { getLineMainContentPos } from '@helpers/search' import { getElementsFromTask } from '@helpers/sorting' +import { getPriorityLevel, nextPriorityLevel, PRIORITY_MARKERS, removePriorityMarker, setPriorityLevel } from '@helpers/taskPriority' import { stripBlockIDsFromString, stripDateRefsFromString, stripAllTagssFromString, stripLinksFromString } from '@helpers/stringTransforms' import { parseTeamspaceFilename } from '@helpers/teamspace' @@ -899,44 +900,31 @@ export function removeDuplicateSyncedLines(paras: $ReadOnlyArray): $ } /** - * Get number of consecutive '!' in 'content' that aren't at the start/end of a word, or preceding a '[' - * From 3.9.4 there are also `>>` working-on markers at the start of 'content', which are treated as priority 4. + * The task's priority level, as NotePlan reads it: a leading '!', '!!', '!!!' or '>>' followed by a space. + * (Before 2026-12 this counted any run of '!' anywhere in the line, including the '!' of a due date like '!>2026-12-05'.) * @param {string} content - * @returns {string} number of !, or 4 if line is flagged as 'working-on', or -1 + * @returns {number} 1-3 for '!' to '!!!', 4 for '>>' (working on), or 0 for none */ export function getTaskPriority(content: string): number { - if (content.match(/\B\!+\B(?!\[)/)) { - // not in middle of word, or starting an image tag - // Note: this second (unanchored) match is guaranteed to succeed if the test above did, but it can find an earlier - // run of '!'s than the one the test matched, so keep it as a separate match rather than re-using the test's result. - const exclamationMatch = content.match(/\B\!+\B/) - if (exclamationMatch) { - return exclamationMatch[0].length - } - } - if (content.match(/^>>/)) { - return 4 - } - return 0 + return getPriorityLevel(content) } /** - * Remove task Priority Indicators (!, !!, !!!, >>) from start of content (was: any where in line except starting an image tag, or at start/end of a word). + * Remove the task's priority marker ('!', '!!', '!!!' or '>>' plus a space, at the start of the content). * @param {string} content - * @returns {string} content minus any priority indicators + * @returns {string} content minus its priority marker */ export function removeTaskPriorityIndicators(content: string): string { - // let output = content.replace(/\B\!+\B(?!\[)/g, '') // not in middle of word, or starting an image tag - let output = content.replace(/^!{1,3}\s/, '') // start of line only - output = output.replace(/^>>\s?/, '') // start of line only - return output + return removePriorityMarker(content) } /** - * Change the priority in a task to '!', '!!', '!!!', '>>' (or remove priority) + * Change the priority in a task to '!', '!!', '!!!', '>>' (or remove priority). + * Only the leading marker is replaced: any other '!' in the text (e.g. a due date '!>2026-12-05', an image '![..](..)', + * or 'Wow!') is left alone. (Before 2026-12 every '!' in the line was removed.) * @author @dwertheimer updated by @jgclark * @param {TParagraph} input - the task/pagraph to be processed - * @param {string} priorityString - the new priority (!,!!,!!! or '' for none) + * @param {string} priorityString - the new priority ('!', '!!', '!!!', '>>', or '' for none) * @param {boolean} - commit the change after the change is made (default false) * @returns {string} the resulting updated paragraph's content * Note: If the third param is missing or false, THE CHANGE HAS NOT BEEN COMMITTED YET. You should use note.updateParagraph(s) to commit the change you receive back. @@ -944,14 +932,15 @@ export function removeTaskPriorityIndicators(content: string): string { */ export function changePriority(inputPara: TParagraph, prioStr: string, commitChange?: boolean = false): string { const outputPara = inputPara - outputPara.content = outputPara.content.replace(/!\s*/g, '').replace(/\s+!/g, '').replace(/^>>\s/, '') - outputPara.content = `${prioStr ? `${prioStr} ` : ''}${outputPara.content}`.trim() + const level = PRIORITY_MARKERS.indexOf(prioStr ?? '') + if (level === -1) { + logWarn('changePriority', `'${prioStr}' isn't a NotePlan priority marker; removing the priority instead`) + } + outputPara.content = setPriorityLevel(outputPara.content, Math.max(level, 0)) commitChange && outputPara.note ? outputPara.note.updateParagraph(outputPara) : null return outputPara.content } -const PRIORITY_LEVELS = ['', '!', '!!', '!!!', '>>'] - /** * Cycle the priority level of a task up: none -> ! -> !! -> !!! -> >> -> none * Written originally to suit a single UI window in the Dashboard. @@ -960,22 +949,21 @@ const PRIORITY_LEVELS = ['', '!', '!!', '!!!', '>>'] * @returns {string} the resulting updated paragraph's content */ export function cyclePriorityStateUp(input: TParagraph): string { - const currentPriorityLevel = getTaskPriority(input.content) - const newPriorityLevel = (currentPriorityLevel + 1) % 5 - return changePriority(input, PRIORITY_LEVELS[newPriorityLevel], true) + const newPriorityLevel = nextPriorityLevel(getPriorityLevel(input.content), 'up') + return changePriority(input, PRIORITY_MARKERS[newPriorityLevel], true) } /** * Cycle the priority level of a task down: none -> >> -> !!! -> !! -> ! -> none + * (Before 2026-12, down from none stayed at none.) * Written for the Dashboard. * @author @jgclark * @param {TParagraph} input - the task/pagraph to be processed * @returns {string} the resulting updated paragraph's content */ export function cyclePriorityStateDown(input: TParagraph): string { - const currentPriorityLevel = getTaskPriority(input.content) - const newPriorityLevel = (currentPriorityLevel - 1) % 5 - return changePriority(input, PRIORITY_LEVELS[newPriorityLevel], true) + const newPriorityLevel = nextPriorityLevel(getPriorityLevel(input.content), 'down') + return changePriority(input, PRIORITY_MARKERS[newPriorityLevel], true) } export type TagsList = { hashtags: Array, mentions: Array } //include the @ and # characters diff --git a/helpers/sorting.js b/helpers/sorting.js index 8d080a8cb..8d63fe9c0 100644 --- a/helpers/sorting.js +++ b/helpers/sorting.js @@ -3,6 +3,7 @@ import get from 'lodash/get' import { isScheduled } from './dateTime' import { clo, logDebug, logError } from './dev' +import { getPriorityMarker } from './taskPriority' // Note: an object type, not an `interface`, so it can be spread (`{ ...t, duration: 0 }`). // Kept INEXACT (trailing `...`) because .flowconfig sets exact_by_default=true and callers @@ -74,7 +75,9 @@ const RE_HASHTAGS: RegExp = /\B(?:#|#)((?![\p{N}\-_\/]+(?:$|[^\p{L}\p{M}\p{N}\ // Mentions follow the same rule. NotePlan reports "@estimate(2)" as the mention "@estimate", so the // trailing "(...)" is left out here too -- which also keeps @estimate(2) and @estimate(5) in one sort group. const RE_MENTIONS: RegExp = /\B@((?![\p{N}\-_\/]+(?:$|[^\p{L}\p{M}\p{N}\p{S}\-_\/]))[\p{L}\p{M}\p{N}\p{S}\-_\/]{0,59}[\p{L}\p{M}\p{N}\p{S}\-_])/gu -const RE_LEADING_EXCLAMATIONS: RegExp = /^\s*(!+)/g // at start of content, though allowing for leading whitespace (as NP does) +// A NotePlan priority marker: '!', '!!' or '!!!' at the start of the content (leading whitespace allowed, as NP does), followed +// by a space. So '!!!! x', '!x' and due dates like '!>2026-12-05' at the start are not priorities. See helpers/taskPriority.js. +const RE_LEADING_EXCLAMATIONS: RegExp = /^\s*(!{1,3})\s/g const RE_LEADING_PARENS_PRIORITY: RegExp = /^\s*\(([a-zA-z])\)\B/g // must be at start of content export const TASK_TYPES: Array = ['open', 'scheduled', 'done', 'cancelled', 'checklist', 'checklistDone', 'checklistCancelled', 'checklistScheduled'] export const isTask = (para: TParagraph): boolean => TASK_TYPES.indexOf(para.type) >= 0 @@ -191,6 +194,7 @@ export function getElementsFromTask(content: string, reSearch: RegExp): Array>, 0 for not priority markers, or -1 (for error or empty item) + * Note: only NotePlan's markers count: '!', '!!', '!!!' or '>>' at the start of the content, followed by a space. * Note: -1 is a special value in Dashboard: * - Sentinel value: indicates "no priority set" or "no items found" * - Initialization: default for max priority calculations @@ -207,7 +211,8 @@ export function getNumericPriority(item: SortableParagraphSubset): number { } else if (item.parensPriority[0]) { prio = item.parensPriority[0].charCodeAt(0) - 'A'.charCodeAt(0) + 1 if (prio === 23) prio = 4 - } else if (item.content.startsWith('>>')) { + } else if (getPriorityMarker(item.content) === '>>') { + // '>>' (working on) only counts at the start and followed by a space, like the '!' markers prio = 4 } return prio diff --git a/helpers/taskPriority.js b/helpers/taskPriority.js new file mode 100644 index 000000000..5f41a4443 --- /dev/null +++ b/helpers/taskPriority.js @@ -0,0 +1,80 @@ +// @flow +//-------------------------------------------------------------------------- +// NotePlan task priority markers: the one place that says what counts as one. +// +// NotePlan only recognises a priority marker at the START of a task's text, and only when a space follows it: +// '! ' -> 1 +// '!! ' -> 2 +// '!!! ' -> 3 +// '>> ' -> 4 ('working on') +// So these are NOT priorities: '!Pay rent' (no space), 'Pay rent !!' (not at the start), '!!!! four' (not a NotePlan +// marker), and due dates such as '!2026-12-05' or '!>2026-12-05' (the '!' is followed by a date, not a space). +// +// No imports, so that helpers/paragraph.js, helpers/sorting.js, helpers/HTMLView.js and React code can all use it. +// Last updated 2026-12-03 by @dwertheimer & @Claude +//-------------------------------------------------------------------------- + +/** The marker for each priority level, indexed by level (0 = none) */ +export const PRIORITY_MARKERS: $ReadOnlyArray = ['', '!', '!!', '!!!', '>>'] + +/** Highest priority level ('>>') */ +export const MAX_PRIORITY_LEVEL = 4 + +// Leading whitespace is allowed, as NotePlan allows it. Longest '!' run first, so '!!! x' is 3, not 1. +const RE_LEADING_PRIORITY_MARKER = /^(\s*)(!!!|!!|!|>>)\s+/ + +/** + * The priority marker at the start of a task's text, if NotePlan would treat it as one. + * @param {string} content - the task's text (without the task marker '* ' / '- ' / '+ ') + * @returns {string} '!', '!!', '!!!', '>>', or '' if none + */ +export function getPriorityMarker(content: string): string { + const match = (content ?? '').match(RE_LEADING_PRIORITY_MARKER) + return match ? match[2] : '' +} + +/** + * The priority level of a task's text, as NotePlan reads it. + * @param {string} content - the task's text + * @returns {number} 0 (none), 1 ('!'), 2 ('!!'), 3 ('!!!') or 4 ('>>') + */ +export function getPriorityLevel(content: string): number { + const marker = getPriorityMarker(content) + return marker ? PRIORITY_MARKERS.indexOf(marker) : 0 +} + +/** + * Remove the leading priority marker (and the space after it), leaving everything else in the text untouched. + * @param {string} content - the task's text + * @returns {string} + */ +export function removePriorityMarker(content: string): string { + return (content ?? '').replace(RE_LEADING_PRIORITY_MARKER, '$1') +} + +/** + * Set a task's priority level, replacing any existing leading marker. Nothing else in the text changes. + * @param {string} content - the task's text + * @param {number} level - 0 (none) to 4 ('>>'); out-of-range values mean none + * @returns {string} + */ +export function setPriorityLevel(content: string, level: number): string { + const rest = removePriorityMarker(content) + const marker = Number.isInteger(level) && level > 0 && level <= MAX_PRIORITY_LEVEL ? PRIORITY_MARKERS[level] : '' + if (!marker) return rest + // Keep any leading whitespace before the new marker + const leading = rest.match(/^\s*/)?.[0] ?? '' + return `${leading}${marker} ${rest.slice(leading.length)}` +} + +/** + * The next level when cycling priority: up goes none -> ! -> !! -> !!! -> >> -> none; down goes the other way. + * @param {number} level - current level, 0-4 + * @param {'up' | 'down'} direction + * @returns {number} + */ +export function nextPriorityLevel(level: number, direction: 'up' | 'down'): number { + const count = MAX_PRIORITY_LEVEL + 1 + const current = Number.isInteger(level) && level >= 0 && level <= MAX_PRIORITY_LEVEL ? level : 0 + return direction === 'up' ? (current + 1) % count : (current + count - 1) % count +}