Skip to content

Commit

Permalink
feat: global inserts, cursor placement and better docs
Browse files Browse the repository at this point in the history
  • Loading branch information
StrangeGirlMurph committed Jun 8, 2024
1 parent 407e608 commit a85600c
Show file tree
Hide file tree
Showing 8 changed files with 63 additions and 56 deletions.
4 changes: 4 additions & 0 deletions docs/.vitepress/config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ export default defineConfig({
lang: "en-US",
base: "/obsidian-wikipedia-search/",


themeConfig: {
search: {
provider: "local",
},
nav: [
{ text: "Getting Started", link: "/getting-started" },
{ text: "Settings", link: "/settings" },
Expand Down
4 changes: 2 additions & 2 deletions docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ The plugin comes with the following two commands. You can access these commands

## `Link Article`

The `Link Article` command can be used in the edit mode of any markdown file in your vault. It lets you link articles. At first you have to search for and select the Wikipedia article you want to link using the [search pop-up](#shared-search-modal) that appears. After you selected the article you were looking for you have to choose which template to use for the insert. For this another pop-up appears for you to select one of the ones you configured in the settings. If you don't have any [additional templates](settings.md#template-settings) this step is skipped and the default template is used. When you picked the template the magic is happening. The insert is created using the templates [template string](settings.md#template-string) and is inserted inline at the cursors position or into a newly created note based on your [settings](settings.md#creates-note--custom-note-path). Now the ["Cursor placement" setting](settings.md#cursor-placement) comes into play and everything is done!
The `Link Article` command can be used in the edit mode of any markdown file in your vault. It lets you link articles. At first you have to search for and select the Wikipedia article you want to link using the [search pop-up](#shared-search-modal) that appears. After you selected the article you were looking for you have to choose which template to use for the insert. For this another pop-up appears for you to select one of the ones you configured in the settings. If you don't have any [additional templates](settings.md#template-settings) this step is skipped and the default template is used. When you picked the template the magic is happening. Based on your (inline vs note) [settings](settings.md#creates-note--custom-note-path) for the chosen template there are two ways this command can play out. For inline templates the template string will be copied into the selection of the cursor and all the [tags](settings.md#template-string) in the current file will be replaced with their corresponding data. For note templates the template string with the resulting replacements will instead be placed into the newly created file and the selection of the cursor in the current note will be replaced by a link (in the form of `[[{notePath}|{title}]]`) to the newly created one.

## `Open Article`

The `Open Article` command can be used everywhere. It lets you open articles to read. At first you have to search for and select the Wikipedia article you want to open using the [search pop-up](#shared-search-modal) that appears. Now the articles website gets opened either in your default browser or obsidian directly which depends on a few factors. On mobile articles always get opened in the browser. On desktop it depends on your ["Open article in browser" setting](settings.md#open-article-in-browser) and whether or not you have the [Surfing plugin](https://github.com/PKM-er/Obsidian-Surfing) enabled. The Surfing plugin allows you to browse the web and open websites within Obsidian. You can install it [here](obsidian://show-plugin?id=surfing). The Wikipedia Search plugin integrates with the Surfing plugin. By default will Wikipedia Search create a new Surfing web tab and make it open the url of your article selection if you have the plugin enabled.

## `Create Article Note`

The `Create Article Note` command can be used everywhere but you have to have at least one [note template](settings.md#creates-note--custom-note-path) configured to use it. It lets you create notes in your vault for Wikipedia articles. At first you have to search for and select the Wikipedia article you want to open using the [search pop-up](#shared-search-modal) that appears. After you selected the article you were looking for you have to choose one of the [note template](settings.md#creates-note--custom-note-path) you configured in the settings to use for the insert. If there is only one template to choose from it gets selected automatically. This will create the articles note in your vault.
The `Create Article Note` command can be used everywhere but you have to have at least one [note template](settings.md#creates-note--custom-note-path) configured to use it. It lets you create notes in your vault for Wikipedia articles. At first you have to search for and select the Wikipedia article you want to open using the [search pop-up](#shared-search-modal) that appears. After you selected the article you were looking for you have to choose one of the [note templates](settings.md#creates-note--custom-note-path) you configured in the settings to use for the notes content. If there is only one template to choose from it gets selected automatically. This will create the articles note in your vault.

## Shared search modal

Expand Down
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ hero:
link: /commands
---

### Features
### Feature Overview

- Linking Wikipedia articles in all languages.
- Opening articles and links directly in Obsidian (using the [Surfing plugin](https://github.com/PKM-er/Obsidian-Surfing)).
Expand Down
9 changes: 2 additions & 7 deletions docs/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ Default: `false` as in "inline" for the toggle and `‎` (empty) for the custom

The last and most important part of any template is its template string. The template string is the blueprint for the insert. This last section consists of a toggle and an input field which is either a big text or a file search field. The toggle sets whether or not the template string is declared directly in the settings tab in the big text field or separately in a file which the file search field references instead. Template files are only supported for note templates. That's why the toggle disappears and the input automatically switches to the text field once you switch to an inline template.

The template string can be any kind of string containing line breaks and whatever you can think of. The plugin recognizes the following character sequences and replaces all occurrences with the corresponding data:
The template string can be any kind of string containing line breaks and whatever you can think of. The plugin recognizes the following character sequences (tags) and replaces all occurrences with the corresponding data:

- `{title}` The articles title or current selection (based on [this setting](#use-article-title-instead-of-selection)).
- `{description}` The articles description if available. If not, all occurrences will be removed with a notice.
Expand All @@ -71,6 +71,7 @@ The template string can be any kind of string containing line breaks and whateve
- `{intro}` The articles intro (the first big paragraph). _Note: It can be pretty long!_
- `{thumbnail}` An embed to the articles thumbnail if available. If not, all occurrences will be removed with a notice. This will look like `![<article-title> Thumbnail](<url-to-thumbnail>)` or `![<article-title> Thumbnail | <thumbnail-width>](<url-to-thumbnail>)` if the [thumbnail width](#thumbnail-width) is set.
- `{thumbnailUrl}` The url of the articles thumbnail if available. If not, all occurrences will be removed with a notice.
- `{cursor}` The position of the cursor after inserting. The first reference will be used an all the other deleted. By default (if no `{cursor}` is found) the cursor will be placed after the locally inserted content.

Default: `[{title}]({url})` for inline templates and `{thumbnail}\n[{title}]({url}): {intro}` for note templates

Expand All @@ -86,12 +87,6 @@ You can also use [Templater](https://github.com/SilentVoid13/Templater) Syntax i
![workflow optimization settings screenshot](/workflow-optimizations.png)
:::

### Cursor placement

Whether or not the cursor is placed infront of the insert instead of after it. For longer inserts it might make it easier to keep the cursor at the start of the insert.

Default: `false`

### Auto-search note title

Whether or not to automatically use the active notes title when searching for articles. The current selection will be prioritized.
Expand Down
4 changes: 2 additions & 2 deletions src/commands/createArticleNotes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ async function createArticleNote(
}
}

const insert = await generateInsert(settings, article, templateString, "");
const filePath = await createNoteInFolder(app, article.title, insert, folderPath, settings.overrideFiles);
const result = await generateInsert(settings, article, templateString, "");
const filePath = await createNoteInFolder(app, article.title, result.insert, folderPath, settings.overrideFiles);
if (!filePath) return;
if (settings.openCreatedNotes) {
app.workspace
Expand Down
57 changes: 36 additions & 21 deletions src/commands/linkArticles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,37 +11,39 @@ export class LinkArticleModal extends SearchModal {
if (this.settings.templates.length > 1) {
new LinkArticleTemplateModal(app, this.settings, this.editor!, article).open();
} else {
insertLink(app, this.editor!, this.settings, article, this.settings.templates[0]);
linkArticle(this.app, this.editor!, this.settings, article, this.settings.templates[0]);
}
}
}

class LinkArticleTemplateModal extends TemplateModal {
async onChooseSuggestion(template: Template) {
insertLink(app, this.editor, this.settings, this.article, template);
linkArticle(this.app, this.editor, this.settings, this.article, template);
}
}

async function insertLink(
async function linkArticle(
app: App,
editor: Editor,
settings: WikipediaSearchSettings,
article: Article,
template: Template
) {
let templateString = template.templateString;
if (template.useTemplateFile && template.createNote) {
const templateFile = app.vault.getAbstractFileByPath(template.templateFilePath);
if (!templateFile || !(templateFile instanceof TFile)) {
new Notice(`Aborting! Template file '${template.templateFilePath}' not found!`);
return;
let templateString = template.templateString
const selection = editor.getSelection()

if (template.createNote) {
if (template.useTemplateFile) {
const templateFile = app.vault.getAbstractFileByPath(template.templateFilePath);
if (!templateFile || !(templateFile instanceof TFile)) {
new Notice(`Aborting! Template file '${template.templateFilePath}' not found!`);
return;
}
templateString = await app.vault.read(templateFile);
}
templateString = await app.vault.read(templateFile);
}

let insert = await generateInsert(settings, article, templateString, editor.getSelection());
const content = await generateInsert(settings, article, templateString, selection)

if (template.createNote) {
let folderPath: string | null =
template.customPath === "" ? settings.defaultNotePath : template.customPath;
if (folderPath === createNoteInActiveNotesFolderMarker) {
Expand All @@ -54,15 +56,28 @@ async function insertLink(
}
}

const notePath = await createNoteInFolder(app, article.title, insert, folderPath, settings.overrideFiles);
const notePath = await createNoteInFolder(app, article.title, content.insert, folderPath, settings.overrideFiles);
if (notePath == null) return;

insert = `[[${notePath}|${
settings.prioritizeArticleTitle || editor.getSelection() === "" ? article.title : editor.getSelection()
}]]`;
}
editor.replaceSelection(`[[${notePath}|${
settings.prioritizeArticleTitle || selection === "" ? article.title : selection
}]]`);
} else {
const internalCursorMarker = "{cursorMarker}"

let content = editor.getValue();
content = content.substring(0, editor.posToOffset(editor.getCursor("from"))) + templateString + internalCursorMarker + content.substring(editor.posToOffset(editor.getCursor("to")))

const cursorPosition = editor.getCursor();
editor.replaceSelection(insert);
if (settings.placeCursorInfrontOfInsert) editor.setCursor(cursorPosition);
const result = await generateInsert(settings, article, content, selection);
let newContent = result.insert
let cursorPosition = result.cursorPosition
if (cursorPosition == null)
cursorPosition = newContent.search(internalCursorMarker);
newContent = newContent.replace(internalCursorMarker, "")

editor.setValue(newContent)
const cursorPos = editor.offsetToPos(cursorPosition!)
editor.setCursor(cursorPos)
editor.scrollIntoView({from: cursorPos, to: cursorPos}, true);
}
}
20 changes: 4 additions & 16 deletions src/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ export interface WikipediaSearchSettings {
thumbnailWidth: number;
defaultNotePath: string;
templates: Template[];
placeCursorInfrontOfInsert: boolean;
autoInsertSingleResponseQueries: boolean;
autoSearchNoteTitle: boolean;
prioritizeArticleTitle: boolean;
Expand All @@ -49,7 +48,6 @@ export const DEFAULT_SETTINGS: WikipediaSearchSettings = {
thumbnailWidth: NaN,
defaultNotePath: "/",
templates: [DEFAULT_TEMPLATE],
placeCursorInfrontOfInsert: false,
autoInsertSingleResponseQueries: false,
autoSearchNoteTitle: false,
prioritizeArticleTitle: false,
Expand Down Expand Up @@ -160,16 +158,6 @@ export class WikipediaSearchSettingTab extends PluginSettingTab {

new Setting(containerEl).setName("Workflow optimizations").setHeading();

new Setting(containerEl)
.setName("Cursor placement")
.setDesc("Whether or not the cursor is placed infront of the insert instead of after it.")
.addToggle((toggle) =>
toggle.setValue(this.settings.placeCursorInfrontOfInsert).onChange(async (value) => {
this.settings.placeCursorInfrontOfInsert = value;
await this.plugin.saveSettings();
})
);

new Setting(containerEl)
.setName("Auto-search note title")
.setDesc("Whether or not to automatically use the active notes title when searching for articles.")
Expand Down Expand Up @@ -315,7 +303,7 @@ export class WikipediaSearchSettingTab extends PluginSettingTab {

if (template.createNote) {
setting.addSearch((search: SearchComponent) => {
new FolderSuggest(app, search.inputEl);
new FolderSuggest(this.app, search.inputEl);
search
.setPlaceholder("custom note path")
.setValue(template.customPath)
Expand Down Expand Up @@ -349,7 +337,7 @@ export class WikipediaSearchSettingTab extends PluginSettingTab {

if (template.useTemplateFile && template.createNote) {
setting.addSearch((search: SearchComponent) => {
new FileSuggest(app, search.inputEl);
new FileSuggest(this.app, search.inputEl);
search
.setPlaceholder("template file path")
.setValue(template.templateFilePath)
Expand All @@ -368,7 +356,7 @@ export class WikipediaSearchSettingTab extends PluginSettingTab {
"style",
"white-space:pre;overflow-wrap:normal;overflow:hidden;resize:none;flex-grow:1;width:220px;"
);
text.inputEl.setAttr("rows", "2");
text.inputEl.setAttr("rows", template.createNote ? "3" : "2");

return text
.setPlaceholder("template string")
Expand Down Expand Up @@ -406,7 +394,7 @@ export class WikipediaSearchSettingTab extends PluginSettingTab {
.onClick(async () => {
if (this.settings.templates.length == 21)
return new Notice(
"Easy buddy... I need to stop you right there. You can only have up to 20 templates. It's for your own good! (I think) If you really need more come and talk to me on GitHub. If you convince me I'll let you have more.",
"Easy buddy... I need to stop you right there. You can only have up to 20 templates. It's for your own good! (I think) If you really need more write me. If you convince me I'll let you have more.",
15000
);

Expand Down
19 changes: 12 additions & 7 deletions src/utils/generateInsert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,25 @@ import { getArticleIntros, getArticleThumbnails } from "./wikipediaAPI";
export async function generateInsert(
settings: WikipediaSearchSettings,
article: Article,
templateString: string,
content: string,
selection: string
): Promise<string> {
): Promise<{insert: string, cursorPosition: number | null}> {
const title = settings.prioritizeArticleTitle || selection === "" ? article.title : selection;
let insert = templateString
let insert = content
.replaceAll("{title}", title)
.replaceAll("{url}", article.url)
.replaceAll("{description}", article.description ?? "")
.replaceAll("{language}", languages[article.languageCode])
.replaceAll("{languageCode}", article.languageCode);

if (templateString.includes("{intro}")) {
if (content.includes("{intro}")) {
const intro: string | null =
(await getArticleIntros([article.title], settings.language, settings.cleanupIntros))?.[0] ?? null;
insert = insert.replaceAll("{intro}", intro ?? "");
if (!intro) new Notice("Could not fetch the articles introduction.");
}

if (templateString.includes("{thumbnail}") || templateString.includes("{thumbnailUrl}")) {
if (content.includes("{thumbnail}") || content.includes("{thumbnailUrl}")) {
const thumbnailUrl: string | null =
(await getArticleThumbnails([article.title], settings.language))?.[0] ?? null;
insert = insert
Expand All @@ -41,8 +41,13 @@ export async function generateInsert(
if (!thumbnailUrl) new Notice("Could not fetch the articles thumbnail.");
}

if (templateString.includes("{description}") && !article.description)
if (content.includes("{description}") && !article.description)
new Notice("The article has no description.");

return insert;
let cursorPosition: number | null = insert.search("{cursor}")
cursorPosition = cursorPosition != -1 ? cursorPosition : null

insert = insert.replaceAll("{cursor}", "")

return {insert, cursorPosition };
}

0 comments on commit a85600c

Please sign in to comment.