Skip to content

Commit

Permalink
Review /new note and move /new note from * from Filer to NoteHelpers
Browse files Browse the repository at this point in the history
  • Loading branch information
jgclark committed Dec 26, 2024
1 parent 8deee51 commit f7b6124
Show file tree
Hide file tree
Showing 13 changed files with 164 additions and 112 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
.DS_Store
node_modules/
node_modules*
dist/
.cache/
*/ts-template/*.*
Expand Down
59 changes: 47 additions & 12 deletions helpers/NPFrontMatter.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import fm from 'front-matter'
import { clo, JSP, logDebug, logError, logWarn, timer } from '@helpers/dev'
import { displayTitle } from '@helpers/general'
import { RE_MARKDOWN_LINKS_CAPTURE_G } from '@helpers/regex'

const pluginJson = 'helpers/NPFrontMatter.js'

// Note: update these for each new trigger that gets added
Expand Down Expand Up @@ -195,7 +194,7 @@ export function removeFrontMatterField(note: CoreNoteFields, fieldToRemove: stri
* @param {string} indent - level for recursive indent
* @returns
*/
function _objectToYaml(obj: any, indent: string = ' ') {
function _objectToYaml(obj: any, indent: string = ' '): string {
let output = ''
for (const prop in obj) {
output += `\n${indent}${prop}:`
Expand Down Expand Up @@ -337,7 +336,7 @@ export function setFrontMatterVars(note: CoreNoteFields, varObj: { [string]: str
export function ensureFrontmatter(note: CoreNoteFields, alsoEnsureTitle: boolean = true, title?: string | null): boolean {
try {
let retVal = false
let front = ''
let fm = ''
if (note == null) {
// no note - return false
throw new Error(`No note found. Stopping conversion.`)
Expand All @@ -357,11 +356,7 @@ export function ensureFrontmatter(note: CoreNoteFields, alsoEnsureTitle: boolean
// need to add frontmatter
let newTitle
if (note.type === 'Notes' && alsoEnsureTitle) {
// if (!note.title) {
// logError('ensureFrontmatter', `'${note.filename}' had no frontmatter or title line, but request requires a title. Stopping conversion.`)
logDebug('ensureFrontmatter', `'${note.filename}' had no frontmatter or title line, so will now make one:`)
// return false
// }

const firstLine = note.paragraphs.length ? note.paragraphs[0] : {}
const titleFromFirstLine = firstLine.type === 'title' && firstLine.headingLevel === 1 ? firstLine.content : ''
Expand All @@ -374,28 +369,68 @@ export function ensureFrontmatter(note: CoreNoteFields, alsoEnsureTitle: boolean
}

if (titleFromFirstLine) note.removeParagraph(note.paragraphs[0]) // remove the heading line now that we set it to fm title
front = `---\ntitle: ${quoteText(newTitle)}\n---`
fm = `---\ntitle: ${quoteText(newTitle)}\n---\n`
} else {
logDebug('ensureFrontmatter', `- just adding empty frontmatter to this calendar note`)
front = `---\n---`
fm = `---\n---\n`
}
// const newContent = `${front}${note?.content || ''}`
// logDebug('ensureFrontmatter', `newContent = ${newContent}`)
// note.content = '' // in reality, we can just set this to newContent, but for the mocks to work, we need to do it the long way
logDebug('ensureFrontmatter', `front to add: ${front}`)
logDebug('ensureFrontmatter', `front to add: ${fm}`)
// FIXME: this doesn't do anything for @jgclark
note.insertParagraph(front, 0, 'text')
note.insertParagraph(fm, 0, 'text')
retVal = true
logDebug('ensureFrontmatter', `-> Note '${displayTitle(note)}' converted to use frontmatter.`)
}
// logDebug('ensureFrontmatter', `Returning ${String(retVal)}`)
return retVal
} catch (error) {
logError('NPFrontMatter/ensureFrontmattter()', JSP(error))
return false
}
}

/**
* Works out which is the last line of the frontmatter, returning the line index number of the closing separator, or 0 if no frontmatter found.
* @author @jgclark
* @param {TNote} note - the note to assess
* @returns {number | false} - the line index number of the closing separator, or false if no frontmatter found
*/
export function endOfFrontmatterLineIndex(note: CoreNoteFields): number | false {
try {
const paras = note.paragraphs
const lineCount = paras.length
logDebug(`paragraph/endOfFrontmatterLineIndex`, `total paragraphs in note (lineCount) = ${lineCount}`)
// Can't have frontmatter as less than 2 separators
if (paras.filter((p) => p.type === 'separator').length < 2) {
return false
}
// No frontmatter if first line isn't ---
if (note.paragraphs[0].type !== 'separator') {
return false
}
// No frontmatter if less than 3 lines
if (note.paragraphs.length < 3) {
return false
}
// Look for second --- line
let lineIndex = 1
while (lineIndex < lineCount) {
const p = paras[lineIndex]
if (p.type === 'separator') {
logDebug(`paragraph/endOfFrontmatterLineIndex`, `-> line ${lineIndex} of ${lineCount}`)
return lineIndex
}
lineIndex++
}
// Shouldn't get here ...
return false
} catch (err) {
logError('paragraph/findEndOfActivePartOfNote', err.message)
return NaN // for completeness
}
}

// Triggers in frontmatter: https://help.noteplan.co/article/173-plugin-note-triggers
// triggers: onEditorWillSave => np.test.onEditorWillSave
// triggers: onEditorWillSave => plugin.id.commandName, onEditorWillSave => plugin.id2.commandName2
Expand Down
27 changes: 16 additions & 11 deletions helpers/NPnote.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { getBlockUnderHeading } from './NPParagraph'
import {
calcOffsetDateStrUsingCalendarType,
getTodaysDateHyphenated,
// isScheduled,
isValidCalendarNoteFilenameWithoutExtension,
RE_ISO_DATE,
RE_OFFSET_DATE,
Expand All @@ -19,7 +18,7 @@ import {
import { clo, JSP, logDebug, logError, logInfo, logTimer, logWarn, timer } from '@helpers/dev'
import { getFolderFromFilename } from '@helpers/folders'
import { displayTitle } from '@helpers/general'
import { ensureFrontmatter } from '@helpers/NPFrontMatter'
import { endOfFrontmatterLineIndex, ensureFrontmatter } from '@helpers/NPFrontMatter'
import { findStartOfActivePartOfNote, findEndOfActivePartOfNote } from '@helpers/paragraph'
import { noteType } from '@helpers/note'
import { caseInsensitiveIncludes, getCorrectedHashtagsFromNote } from '@helpers/search'
Expand Down Expand Up @@ -206,7 +205,7 @@ export function getNoteFilenameFromTitle(inputStr: string): string | null {
}

/**
* Convert the note to using frontmatter Syntax
* Convert the note to use frontmatter syntax.
* If optional default text is given, this is added to the frontmatter.
* @author @jgclark
* @param {TNote} note to convert
Expand All @@ -216,20 +215,26 @@ export function getNoteFilenameFromTitle(inputStr: string): string | null {
export function convertNoteToFrontmatter(note: TNote, defaultFMText: string = ''): void {
try {
if (!note) {
throw new Error("note/convertNoteToFrontmatter: No note supplied, and can't find Editor either.")
throw new Error("NPnote/convertNoteToFrontmatter: No valid note supplied.")
}
const success = ensureFrontmatter(note)
if (success) {
logDebug('note/convertNoteToFrontmatter', `ensureFrontmatter() worked for note ${note.filename}`)

const result = ensureFrontmatter(note)
if (result) {
logDebug('NPnote/convertNoteToFrontmatter', `ensureFrontmatter() worked for note ${note.filename}`)

if (defaultFMText !== '') {
const endOfFMLineIndex = findStartOfActivePartOfNote(note) - 1 // closing separator line
note.insertParagraph(defaultFMText, endOfFMLineIndex, 'text') // inserts before closing separator line
const endOfFMLineIndex: number | false = endOfFrontmatterLineIndex(note) // closing separator line
if (endOfFMLineIndex !== false) {
note.insertParagraph(defaultFMText, endOfFMLineIndex, 'text') // inserts before closing separator line
} else {
logWarn('NPnote/convertNoteToFrontmatter', `endOfFrontmatterLineIndex() failed for note ${note.filename}`)
}
}
} else {
logWarn('note/convertNoteToFrontmatter', `ensureFrontmatter() failed for note ${note.filename}`)
logWarn('NPnote/convertNoteToFrontmatter', `ensureFrontmatter() failed for note ${note.filename}`)
}
} catch (error) {
logError(pluginJson, JSP(error))
logError(pluginJson, `convertNoteToFrontmatter: ${error.message}`)
}
}

Expand Down
44 changes: 1 addition & 43 deletions helpers/paragraph.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import { getDateStringFromCalendarFilename } from './dateTime'
import { clo, logDebug, logError, logInfo, logWarn } from './dev'
import { getElementsFromTask } from './sorting'
import { endOfFrontmatterLineIndex } from '@helpers/NPFrontMatter'
import { RE_MARKDOWN_LINK_PATH_CAPTURE, RE_NOTELINK_G, RE_SIMPLE_URI_MATCH } from '@helpers/regex'
import { getLineMainContentPos } from '@helpers/search'
import { stripLinksFromString } from '@helpers/stringTransforms'
Expand Down Expand Up @@ -399,49 +400,6 @@ export function findEndOfActivePartOfNote(note: CoreNoteFields): number {
}
}

/**
* Works out which is the last line of the frontmatter, returning the line index number of the closing separator, or 0 if no frontmatter found.
* Now
* TODO: Move to NPFrontMatter.js ?
* @author @jgclark
* @param {TNote} note - the note to assess
* @returns {number} - the line index number of the closing separator, or 0 if no frontmatter found
*/
export function endOfFrontmatterLineIndex(note: CoreNoteFields): number {
try {
const paras = note.paragraphs
const lineCount = paras.length
// logDebug(`paragraph/endOfFrontmatterLineIndex`, `total paragraphs in note (lineCount) = ${lineCount}`)
// Can't have frontmatter as less than 2 separators
if (paras.filter((p) => p.type === 'separator').length < 2) {
return 0
}
// No frontmatter if first line isn't ---
if (note.paragraphs[0].type !== 'separator') {
return 0
}
// No frontmatter if less than 3 lines
if (note.paragraphs.length <= 3) {
return 0
}
// Look for second --- line
let lineIndex = 1
while (lineIndex < lineCount) {
const p = paras[lineIndex]
if (p.type === 'separator') {
// logDebug(`paragraph/endOfFrontmatterLineIndex`, `-> line ${lineIndex} of ${lineCount}`)
return lineIndex
}
lineIndex++
}
// Shouldn't get here ...
return 0
} catch (err) {
logError('paragraph/findEndOfActivePartOfNote', err.message)
return NaN // for completeness
}
}

/**
* Get the paragraph from the passed content (using exact match)
* @author @jgclark
Expand Down
3 changes: 3 additions & 0 deletions jgclark.Filer/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# What's changed in 📦 Filer plugin?
Please see the [Readme for this plugin](https://github.com/NotePlan/plugins/tree/main/jgclark.Filer) for more details, including the available settings.

## [1.1.6] - 2024-12-26???
- the **new note from clipboard** and **new note from selection** commands have moved to the NoteHelpers plugin.

## [1.1.5] - 2023-10-20
### Changed
- hopefully a fix for "/move paras" sometimes not removing the lines from the original note
Expand Down
6 changes: 0 additions & 6 deletions jgclark.Filer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,12 +87,6 @@ You can also run from an x-callback call. At simplest this is:
noteplan://x-callback-url/runPlugin?pluginID=jgclark.Filer&command=move%20note%20links%20%28recently%20changed%29&arg0=
```

## /new note from clipboard
This command (alias **/nnc**) takes the current text in the clipboard to form the basis of a new note. The command asks for the note title and folder location.

## /new note from selection
This command (alias **/nns**) takes the current selected text to form the basis of a new note. The command asks for the note title and folder location.

## /filer:update plugin settings
This command allows settings to be changed on iOS/iPadOS.

Expand Down
22 changes: 2 additions & 20 deletions jgclark.Filer/plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
"plugin.author": "jgclark",
"plugin.url": "https://github.com/NotePlan/plugins/tree/main/jgclark.Filer",
"plugin.changelog": "https://github.com/NotePlan/plugins/blob/main/jgclark.Filer/CHANGELOG.md",
"plugin.version": "1.1.5",
"plugin.lastUpdateInfo": "1.1.5: try to fix /move paras occasionally not deleting from original\n1.1.4: try to fix a race condition in /add sync'd copy to note. Fix to /move note link.\n1.1.3: bug fix.\n1.1.2: updating to newer libraries.\n1.1.1: new create folder option.\n1.1.0: new /archive command. 1.1.0: new '/... note links...' commands.",
"plugin.version": "1.2.0",
"plugin.lastUpdateInfo": "1.2.0: move /new note commands to NoteHelpers plugin. Updated folder chooser.\n1.1.5: try to fix /move paras occasionally not deleting from original\n1.1.4: try to fix a race condition in /add sync'd copy to note. Fix to /move note link.\n1.1.3: bug fix.\n1.1.2: updating to newer libraries.\n1.1.1: new create folder option.\n1.1.0: new /archive command. 1.1.0: new '/... note links...' commands.",
"plugin.dependencies": [],
"plugin.script": "script.js",
"plugin.isRemote": "false",
Expand Down Expand Up @@ -139,24 +139,6 @@
"description": "quick move a block of paragraphs to Next Week's note",
"jsFunction": "moveParasToNextWeekly"
},
{
"name": "new note from clipboard",
"alias": [
"nnc",
"new"
],
"description": "New note from clipboard",
"jsFunction": "newNoteFromClipboard"
},
{
"name": "new note from selection",
"alias": [
"nns",
"new"
],
"description": "New note from selection (and leave link to it in its place)",
"jsFunction": "newNoteFromSelection"
},
{
"name": "Filer: update plugin settings",
"description": "Settings interface (even for iOS)",
Expand Down
8 changes: 6 additions & 2 deletions jgclark.NoteHelpers/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
# What's changed in 📙 Note Helpers plugin?
For more details see the [plugin's README](https://github.com/NotePlan/plugins/tree/main/jgclark.NoteHelpers/).

## [1.0.0] - 2024-12-26???
## [1.0.0] - 2024-12-???
### New
- the **new note** command has been revived (alias **nn**). It creates a new (regular, not calendar) note with a title you give, and in a folder you can select. If the "Default Text to add to frontmatter" setting isn't blank, then the note will be created using that frontmatter.

### Important Changes
- when "/move note" shows the list of folders, the special Templates and Archive folders are moved to the end of the list. (Plus any other special ones that start with '@').
- when **move note** shows the list of folders, the special Templates and Archive folders are moved to the end of the list. (Plus any other special ones that start with '@').
- the **new note from clipboard** and **new note from selection** commands have moved from Filer plugin to NoteHelpers.

## [0.20.3] - 2024-12-25 (unpublished)
- new **logEditorNoteDetailed** command (which can easily triggered from a callback) that also logs line type and rawContents
Expand Down
5 changes: 4 additions & 1 deletion jgclark.NoteHelpers/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ This plugin provides commands to do things with notes that aren't yet provided i
- **list inconsistent note filenames**: lists the names of notes whose filenames are inconsistent with their titles
- **log note details** command that logs the main details about the currently open note to the plugin console
- **logEditorNoteDetailed** command that does the same as **log note details** but also logs line type and rawContents
- **move note** (alias **mn**): which moves a note to a different folder the user selects
- - **move note** (alias **mn**): which moves a note to a different folder the user selects
- **new note** (alias **nn**): creates a new (regular, not calendar) note with a title you give, and in a folder you can select. If the "Default Text to add to frontmatter" setting isn't blank, then the note will be created using that frontmatter.
- **new note from clipboard** (alias **/nnc**): takes the current text in the clipboard to form the basis of a new note. The command asks for the note title and folder location.
- **new note from selection** (alias **/nns**): takes the current selected text to form the basis of a new note. The command asks for the note title and folder location.
- **open current note new split** (alias **ocns**): open the current note again in a new split of the main window (and places the cursor at what it judges to be the start of the main content)
- **open note new window** (alias **onw**): open a user-selected note in a new window (and places the cursor at what it judges to be the start of the main content)
- **open note new split** (alias **ons**): open a user-selected note in a new split of the main window (and places the cursor at what it judges to be the start of the main content)
Expand Down
46 changes: 36 additions & 10 deletions jgclark.NoteHelpers/plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
"plugin.author": "Jonathan Clark & Eduard Metzger",
"plugin.url": "https://github.com/NotePlan/plugins/tree/main/jgclark.NoteHelpers/",
"plugin.changelog": "https://github.com/NotePlan/plugins/blob/main/jgclark.NoteHelpers/CHANGELOG.md",
"plugin.version": "0.20.3",
"plugin.lastUpdateInfo": "0.20.3: New 'printEditorDetailed' command to log all paragraph details as well.\n0.20.2: 'printNote' extended to cover backlinks.\n0.20.1: new command 'printNote' for debugging purposes.\n0.20.0: new commands \"unlinked note finder\" and \"delete note\". Bug fix to \"rename note filename\" command.\n0.19.2: fix edge cases with \"add trigger to note\".\n0.19.1: \"add trigger to note\" command can now be run from template. Added migration message about 'open note' commands.\n0.19.0: fix to '/rename inconsistent filename' command. Moved 'open note' functions to WindowTools plugin. Updated the display of the 'index folders' command. Removed 'Show month/quarter/year' commands as they are now in the main NP menus.\n0.18.2: fix edge case with /add trigger command.\n0.18.1: Add 3 file naming commands (by @leo)\n.0.18.0: Add '/Show This Month/Quarter/Year' and '/update all indexes' commands\n0.17.3: fix bugs in '/index folders'. New setting 'Title to use for Index notes'. 0.17.0: new command '/open url from a note'.",
"plugin.version": "1.0.0",
"plugin.lastUpdateInfo": "1.0.0: move '/new note from ...' commands here from Filer plugin, and revived '/new note' command.\n0.20.3: New 'printEditorDetailed' command to log all paragraph details as well.\n0.20.2: 'printNote' extended to cover backlinks.\n0.20.1: new command 'printNote' for debugging purposes.\n0.20.0: new commands \"unlinked note finder\" and \"delete note\". Bug fix to \"rename note filename\" command.\n0.19.2: fix edge cases with \"add trigger to note\".\n0.19.1: \"add trigger to note\" command can now be run from template. Added migration message about 'open note' commands.\n0.19.0: fix to '/rename inconsistent filename' command. Moved 'open note' functions to WindowTools plugin. Updated the display of the 'index folders' command. Removed 'Show month/quarter/year' commands as they are now in the main NP menus.",
"plugin.dependencies": [],
"plugin.script": "script.js",
"plugin.commands": [
Expand Down Expand Up @@ -77,6 +77,18 @@
"description": "Find and create links to all unlinked notes",
"jsFunction": "findUnlinkedNotesInAllNotes"
},
{
"name": "index folders",
"alias": [
"index"
],
"description": "Make/Update indexes for all notes in a folder (and sub-folders if wanted)",
"jsFunction": "indexFolders",
"parameters": [
"folder",
"string: displayOrder=(key);dateDisplayType=(key);includeSubfolders=(key)"
]
},
{
"name": "jump to heading",
"alias": [
Expand Down Expand Up @@ -121,16 +133,30 @@
"jsFunction": "moveNote"
},
{
"name": "index folders",
"name": "new note",
"alias": [
"index"
"nn"
],
"description": "Make/Update indexes for all notes in a folder (and sub-folders if wanted)",
"jsFunction": "indexFolders",
"parameters": [
"folder",
"string: displayOrder=(key);dateDisplayType=(key);includeSubfolders=(key)"
]
"description": "Make New note with choice of folder",
"jsFunction": "newNote"
},
{
"name": "new note from clipboard",
"alias": [
"nnc",
"new"
],
"description": "New note from clipboard",
"jsFunction": "newNoteFromClipboard"
},
{
"name": "new note from selection",
"alias": [
"nns",
"new"
],
"description": "New note from selection (and leave link to it in its place)",
"jsFunction": "newNoteFromSelection"
},
{
"name": "open URL from a note",
Expand Down
Loading

0 comments on commit f7b6124

Please sign in to comment.