-
Notifications
You must be signed in to change notification settings - Fork 663
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
generate copy without wikilinks #1365
Merged
riccardoferretti
merged 24 commits into
foambubble:master
from
hereistheusername:master
Jul 10, 2024
Merged
Changes from 3 commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
60b4adf
inseart new test file
hereistheusername bab6cd7
add generate standalone note command
hereistheusername bcfde0e
vscode cmd configure
hereistheusername 76ed1ad
fix embeded wikilinks
hereistheusername 07702c2
refactor convertLinksFormat function & add 4 user command interfaces
hereistheusername 62f458e
cleanup
hereistheusername 0aefd72
add comments
hereistheusername 2e350d7
change user interface
hereistheusername 08451f1
del outdated comments
hereistheusername 18dbbb5
fix typo
hereistheusername b384491
modify createUpdateLinkEdit to accomplish convert
hereistheusername 7adf32f
only images can be embedded
hereistheusername 4483132
move useAngles to if-branch uses it
hereistheusername 8dd26c9
keey filename when using in page anchor
hereistheusername 7732e4b
remove redundant procedure
hereistheusername 8194b5c
give a default value to alias in link format combination branch
hereistheusername 6765d52
add tests to createUpdateLinkEdit about changint links' type and isEmbed
hereistheusername 1daf3be
follow prettier format
hereistheusername aaa8321
change to one line expression
hereistheusername bdfa676
get target from getIdentifier
hereistheusername 7af316b
add tests for inserting angles
hereistheusername e8e3c2a
Merge pull request #1 from hereistheusername/test/modify-createUpdate…
hereistheusername b9775a3
fix typo
hereistheusername 866a091
change require to import statement
hereistheusername File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
55 changes: 55 additions & 0 deletions
55
packages/foam-vscode/src/core/janitor/generate-mdlinks.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
import { generateMarkdownLinks } from './generate-mdlinks'; | ||
import { TEST_DATA_DIR } from '../../test/test-utils'; | ||
import { MarkdownResourceProvider } from '../services/markdown-provider'; | ||
import { Resource } from '../model/note'; | ||
import { FoamWorkspace } from '../model/workspace'; | ||
import { Logger } from '../utils/log'; | ||
import fs from 'fs'; | ||
import { URI } from '../model/uri'; | ||
import { createMarkdownParser } from '../services/markdown-parser'; | ||
import { FileDataStore } from '../../test/test-datastore'; | ||
|
||
Logger.setLevel('error'); | ||
|
||
describe('generateStdMdLink', () => { | ||
let _workspace: FoamWorkspace; | ||
// TODO slug must be reserved for actual slugs, not file names | ||
const findBySlug = (slug: string): Resource => { | ||
return _workspace | ||
.list() | ||
.find(res => res.uri.getName() === slug) as Resource; | ||
}; | ||
|
||
beforeAll(async () => { | ||
/** Use fs for reading files in units where vscode.workspace is unavailable */ | ||
const readFile = async (uri: URI) => | ||
(await fs.promises.readFile(uri.toFsPath())).toString(); | ||
const dataStore = new FileDataStore( | ||
readFile, | ||
TEST_DATA_DIR.joinPath('__scaffold__').toFsPath() | ||
); | ||
const parser = createMarkdownParser(); | ||
const mdProvider = new MarkdownResourceProvider(dataStore, parser); | ||
_workspace = await FoamWorkspace.fromProviders([mdProvider], dataStore); | ||
}); | ||
|
||
it('initialised test graph correctly', () => { | ||
expect(_workspace.list().length).toEqual(11); | ||
}); | ||
|
||
it('can generate markdown links correctly', async () => { | ||
const note = findBySlug('file-with-different-link-formats'); | ||
const actual = await generateMarkdownLinks(note, _workspace); | ||
const expected: string[] = [ | ||
'[first-document](first-document.md "First Document")', | ||
'[second-document](second-document.md "Second Document")', | ||
'[#one section](<#one section> "File with different link formats")', | ||
'[another name](<#one section> "File with different link formats")', | ||
'[an alias](first-document.md "First Document")', | ||
]; | ||
expect(actual.length).toEqual(expected.length); | ||
const _ = actual.map((textReplace, index) => { | ||
expect(textReplace.to).toEqual(expected[index]); | ||
}); | ||
}); | ||
}); |
107 changes: 107 additions & 0 deletions
107
packages/foam-vscode/src/core/janitor/generate-mdlinks.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,107 @@ | ||
import { NoteLinkDefinition, Resource } from '../model/note'; | ||
import { FoamWorkspace } from '../model/workspace'; | ||
import { createMarkdownReferences } from '../services/markdown-provider'; | ||
|
||
export interface TextReplace { | ||
from: string; | ||
to: string; | ||
} | ||
|
||
/** | ||
* parse wikilink's rawText | ||
* possible inpout: | ||
* 1. [[\<filename\>#\<section\>|\<label\>]] | ||
* 2. [[#\<section\>|\<label\>]] | ||
* 3. [[\<filename\>#\<section\>]] | ||
* 4. [[\<filename\>|\<label\>]] | ||
*/ | ||
class WikilinkRawText { | ||
private lable_m: string = ''; | ||
private filename_m: string = ''; | ||
private section_m: string = ''; | ||
|
||
public readFromText(definition: NoteLinkDefinition): WikilinkRawText { | ||
const struct_rawText_regex = | ||
/(?:(?<filename>[^\]|#]+)?(?:#(?<section>[^\]|]+))?)?(?:\|(?<label>[^\]]+))?/; | ||
const match_result = definition.label.match(struct_rawText_regex); | ||
if (match_result) { | ||
this.filename_m = match_result[1]; | ||
this.section_m = match_result[2]; | ||
this.lable_m = match_result[3]; | ||
} | ||
return this; | ||
} | ||
|
||
public getLable(): string { | ||
if (this.lable_m) { | ||
return this.lable_m; | ||
} | ||
// return `${this.getFilename()}${this.section_m ? '#' : ''}${this.getSection()}`; | ||
return ''; | ||
} | ||
public getFilename(): string { | ||
if (this.filename_m) { | ||
return this.filename_m; | ||
} | ||
return ''; | ||
} | ||
public getSection(): string { | ||
if (this.section_m) { | ||
return this.section_m; | ||
} | ||
return ''; | ||
} | ||
public toMarkdownLink( | ||
definition: NoteLinkDefinition, | ||
toNote: Resource | ||
): string { | ||
const struct_rawText_regex = | ||
/(?:(?<filename>[^\]|#]+)?(?:#(?<section>[^\]|]+))?)?(?:\|(?<label>[^\]]+))?/; | ||
const match_result = definition.label.match(struct_rawText_regex); | ||
this.filename_m = match_result[1]; | ||
this.section_m = match_result[2]; | ||
this.lable_m = match_result[3]; | ||
|
||
let url = `${ | ||
definition.url !== toNote.uri.getBasename() ? definition.url : '' | ||
}${this.section_m ? `#${this.getSection()}` : ''}`; | ||
if (url.indexOf(' ') > 0) { | ||
url = `<${url}>`; | ||
} | ||
url = `(${url}${definition.title ? ` "${definition.title}"` : ''})`; | ||
|
||
let label = this.lable_m; | ||
let filename = | ||
this.getFilename() !== toNote.uri.getName() ? this.getFilename() : ''; | ||
let section = this.getSection(); | ||
if (!label) { | ||
label = `${filename}${this.section_m ? `#${section}` : ''}`; | ||
} | ||
|
||
return `[${label}]${url}`; | ||
} | ||
} | ||
|
||
export const generateMarkdownLinks = async ( | ||
note: Resource, | ||
workspace: FoamWorkspace | ||
): Promise<TextReplace[]> => { | ||
if (!note) { | ||
return [] as TextReplace[]; | ||
} | ||
|
||
const newWikilinkDefinitions = createMarkdownReferences( | ||
workspace, | ||
note, | ||
true | ||
); | ||
const wikilinkRawTextParser = new WikilinkRawText(); | ||
const toReplaceArray = newWikilinkDefinitions.map(definition => { | ||
return { | ||
from: `[[${definition.label}]]`, | ||
to: wikilinkRawTextParser.toMarkdownLink(definition, note), | ||
}; | ||
}); | ||
|
||
return toReplaceArray; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,3 @@ | ||
export { generateLinkReferences } from './generate-link-references'; | ||
export { generateHeading } from './generate-headings'; | ||
export { generateMarkdownLinks } from './generate-mdlinks'; |
73 changes: 73 additions & 0 deletions
73
packages/foam-vscode/src/features/commands/generate-standalone-note.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
import { commands, ExtensionContext, window } from 'vscode'; | ||
import { isMdEditor } from '../../utils'; | ||
import { Foam } from '../../core/model/foam'; | ||
import { FoamWorkspace } from '../../core/model/workspace'; | ||
import { fromVsCodeUri } from '../../utils/vsc-utils'; | ||
import { getEditorEOL } from '../../services/editor'; | ||
import { ResourceParser } from '../../core/model/note'; | ||
import { IMatcher } from '../../core/services/datastore'; | ||
import { generateMarkdownLinks } from '../../core/janitor'; | ||
const vscode = require('vscode'); /* cannot import workspace from above statement and not sure what happened */ | ||
|
||
export default async function activate( | ||
context: ExtensionContext, | ||
foamPromise: Promise<Foam> | ||
) { | ||
const foam = await foamPromise; | ||
|
||
context.subscriptions.push( | ||
commands.registerCommand('foam-vscode.generate-standalone-note', () => { | ||
return generateStandaloneNote( | ||
foam.workspace, | ||
foam.services.parser, | ||
foam.services.matcher | ||
); | ||
}) | ||
); | ||
} | ||
|
||
/** | ||
* based on generate-link-references, | ||
* copy the current note, | ||
* replace wikilinks in it, | ||
* save it at the same directory, | ||
* call update-wikilinks to remove link references if neccessary | ||
*/ | ||
async function generateStandaloneNote( | ||
fWorkspace: FoamWorkspace, | ||
fParser: ResourceParser, | ||
fMatcher: IMatcher | ||
) { | ||
const editor = window.activeTextEditor; | ||
const doc = editor.document; | ||
|
||
if (!isMdEditor(editor) || !fMatcher.isMatch(fromVsCodeUri(doc.uri))) { | ||
return; | ||
} | ||
|
||
// const setting = getWikilinkDefinitionSetting(); | ||
const eol = getEditorEOL(); | ||
let text = doc.getText(); | ||
|
||
const resource = fParser.parse(fromVsCodeUri(doc.uri), text); | ||
const textReplaceArr = await generateMarkdownLinks(resource, fWorkspace); | ||
function escapeRegExp(string) { | ||
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); | ||
} | ||
|
||
textReplaceArr.forEach(({ from, to }) => { | ||
text = text.replace(new RegExp(escapeRegExp(from), 'g'), to); | ||
}); | ||
|
||
const basePath = doc.uri.path.split('/').slice(0, -1).join('/'); | ||
|
||
const fileUri = vscode.Uri.file( | ||
`${ | ||
basePath ? basePath + '/' : '' | ||
}${resource.uri.getName()}.standalone${resource.uri.getExtension()}` | ||
); | ||
const encoder = new TextEncoder(); | ||
await vscode.workspace.fs.writeFile(fileUri, encoder.encode(text)); | ||
await window.showTextDocument(fileUri); | ||
await commands.executeCommand('foam-vscode.update-wikilink-definitions'); | ||
riccardoferretti marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
21 changes: 21 additions & 0 deletions
21
packages/foam-vscode/test-data/__scaffold__/file-with-different-link-formats.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
# File with different link formats | ||
|
||
markdown link [home page](https://foambubble.github.io/) | ||
|
||
wikilink to file [[first-document]]. | ||
|
||
markdown format link to local [file](first-document.md) | ||
|
||
embeded wikilink to file ![[second-document]]. | ||
|
||
wikilink to placeholder [[non-exist-file]] | ||
|
||
in-note anchor [[file-with-different-link-formats#one section]] | ||
|
||
alias to anchor [[file-with-different-link-formats#one section|another name]] | ||
|
||
alias [[first-document|an alias]] | ||
|
||
dupilcated wikilink to file [[first-document]] | ||
|
||
# one section |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You probably can reuse the mechanisms available in
MarkdownLink
to achieve the same in a more integrated way