Compare commits

...

2 commits

Author SHA1 Message Date
riccardoferretti
30f145c132 Docs sync @ 4e0f6a5 Fixed typos in docs 2025-07-23 14:01:19 +00:00
Riccardo
31586bb758
Docs sync @ c669e54 Pass arguments when running test scripts (#65) 2025-07-10 11:55:40 +02:00
2 changed files with 213 additions and 68 deletions

View file

@ -2,45 +2,56 @@
Foam supports note templates which let you customize the starting content of your notes instead of always starting from an empty note.
Note templates are `.md` files located in the special `.foam/templates` directory of your workspace.
Foam supports two types of templates:
- **Markdown templates** (`.md` files) - Simple templates with predefined content and variables
- **JavaScript templates** (`.js` files) - Smart templates that can adapt based on context and make intelligent decisions
Both types of templates are located in the special `.foam/templates` directory of your workspace.
## Quickstart
Create a template:
### Creating templates
**For simple templates:**
- Run the `Foam: Create New Template` command from the command palette
- OR manually create a regular `.md` file in the `.foam/templates` directory
**For smart templates:**
- Create a `.js` file in the `.foam/templates` directory (see [JavaScript Templates](#javascript-templates) section below)
![Create new template GIF](../../assets/images/create-new-template.gif)
_Theme: Ayu Light_
### Using templates
To create a note from a template:
- Run the `Foam: Create New Note From Template` command and follow the instructions. Don't worry if you've not created a template yet! You'll be prompted to create a new template if none exist.
- OR run the `Foam: Create New Note` command, which uses the special default template (`.foam/templates/new-note.md`, if it exists)
- Run the `Foam: Create New Note From Template` command and follow the instructions. Don't worry if you've not created a template yet! You'll be prompted to create a new simple template if none exist.
- OR run the `Foam: Create New Note` command, which uses the special default template (`.foam/templates/new-note.md` or `.foam/templates/new-note.js`, if it exists)
![Create new note from template GIF](../../assets/images/create-new-note-from-template.gif)
_Theme: Ayu Light_
## Special templates
### Default template
The `.foam/templates/new-note.md` template is special in that it is the template that will be used by the `Foam: Create New Note` command.
Customize this template to contain content that you want included every time you create a note. To begin it is _recommended_ to define the YAML Front-Matter of the template similar to the following:
The default template is used by the `Foam: Create New Note` command. Foam will look for these templates in order:
```markdown
---
type: basic-note
---
```
1. `.foam/templates/new-note.js` (JavaScript template)
2. `.foam/templates/new-note.md` (Markdown template)
Customize this template to contain content that you want included every time you create a note.
### Default daily note template
The `.foam/templates/daily-note.md` template is special in that it is the template that will be used when creating daily notes (e.g. by using `Foam: Open Daily Note`).
Customize this template to contain content that you want included every time you create a daily note. To begin it is _recommended_ to define the YAML Front-Matter of the template similar to the following:
The daily note template is used when creating daily notes (e.g. by using `Foam: Open Daily Note`). Foam will look for these templates in order:
1. `.foam/templates/daily-note.js` (JavaScript template)
2. `.foam/templates/daily-note.md` (Markdown template)
For a simple markdown template, it is _recommended_ to define the YAML Front-Matter similar to the following:
```markdown
---
@ -48,9 +59,184 @@ type: daily-note
---
```
## Variables
## JavaScript Templates
Templates can use all the variables available in [VS Code Snippets](https://code.visualstudio.com/docs/editor/userdefinedsnippets#_variables).
JavaScript templates are a powerful way to create smart, context-aware note templates that can adapt based on the situation. Unlike static Markdown templates, JavaScript templates can make intelligent decisions about what content to include.
**Use JavaScript templates when you want to:**
- Create different note structures based on the day of the week, time, or date
- Adapt templates based on where the note is being created from
- Automatically find and link related notes in your workspace
- Generate content based on existing notes or workspace structure
- Implement complex logic that static templates cannot handle
### Basic JavaScript template structure
A JavaScript template is a `.js` file that exports a function returning note content, and optionally location:
```javascript
// .foam/templates/daily-note.js
async function createNote({ trigger, foam, resolver, foamDate }) {
const today = dayjs();
// or you could use foamDate for day specific notes, see FOAM_DATE_* variables
// const day = dayjs(foamDate)
const formattedDay = today.format('YYYY-MM-DD');
// if you need a variable you can use the resolver
// const title = await resolver.resolveFromName('FOAM_TITLE');
console.log(
'Creating note for today: ' + formattedDay,
JSON.stringify(trigger)
);
let content = `# Daily Note - ${formattedDay}
## Today's focus
-
## Notes
-
`;
switch (today.day()) {
case 1: // Monday
content = `# Week Planning - ${formattedDay}
## This week's goals
- [ ] Goal 1
- [ ] Goal 2
## Focus areas
-
`;
break;
case 5: // Friday
content = `# Week Review - ${formattedDay}
## What went well
-
## What could be improved
-
## Next week's priorities
-
`;
break;
}
return {
content,
filepath: `/weekly-planning/${formattedDay}.md`,
};
}
```
### Examples
**Smart meeting notes:**
```javascript
async function createNote({ trigger, foam, resolver }) {
const title = (await resolver.resolveFromName('FOAM_TITLE')) || 'Meeting';
const today = dayjs();
// Detect meeting type from title
const isStandup = title.toLowerCase().includes('standup');
const isReview = title.toLowerCase().includes('review');
let template = `# ${title} - ${today.format('YYYY-MM-DD')}
`;
if (isStandup) {
template += `## What I did yesterday
-
## What I'm doing today
-
## Blockers
-
`;
} else if (isReview) {
template += `## What went well
-
## What could be improved
-
## Action items
- [ ]
`;
} else {
template += `## Agenda
-
## Notes
-
## Action items
- [ ]
`;
}
return {
content: template,
filepath: `/meetings/${title}.md`,
};
}
```
### Template result format
JavaScript templates must return an object with:
- `content` (required): The note content as a string
- `filepath` (required): Custom file path for the note
- NOTE: the path must be within the workspace.
- A relative path will be resolved based on the `onRelativePath` command configuration.
- An absolute path will be taken as is, if it falls within the workspace. Otherwise it will be considered to be from the workspace root
```javascript
return {
content: '# My Note\n\nContent here...',
filepath: 'custom-folder/my-note.md',
};
```
### Security and limitations
JavaScript templates run in a best-effort secured environment:
- ✅ Can only run from trusted VS Code workspaces
- ✅ Can access Foam workspace and utilities
- ✅ Can use standard JavaScript features
- ✅ Have a 30-second execution timeout
- ❌ Cannot access the file system directly
- ❌ Cannot make network requests
- ❌ Cannot access Node.js modules
This increases the chances that templates stay safe while still being powerful enough for complex logic.
STILL - PLEASE BE AWARE YOU ARE EXECUTING CODE ON YOUR MACHINE. THIS SANDBOX IS NOT MEANT TO BE THE ULTIMATE SECURITY SOLUTION.
**YOU MUST TRUST THE REPO CONTRIBUTORS**
## Markdown templates
Markdown templates are a simple way to create notes
**Use Markdown templates when you want to:**
- Create simple, consistent note structures
- Use basic variables and placeholders
- Keep templates easy to read and modify
### Variables
Markdown templates can use all the variables available in [VS Code Snippets](https://code.visualstudio.com/docs/editor/userdefinedsnippets#_variables).
In addition, you can also use variables provided by Foam:
@ -93,9 +279,9 @@ If instead you were to use the VS Code versions of these variables, they would b
When creating notes in any other scenario, the `FOAM_DATE_` values are computed using the same datetime as the VS Code ones, so the `FOAM_DATE_` versions can be used in all scenarios by default.
## Metadata
### Metadata
Templates can also contain metadata about the templates themselves. The metadata is defined in YAML "Frontmatter" blocks within the templates.
**Markdown templates** can also contain metadata about the templates themselves. The metadata is defined in YAML "Frontmatter" blocks within the templates.
| Name | Description |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------- |
@ -105,40 +291,7 @@ Templates can also contain metadata about the templates themselves. The metadata
Foam-specific variables (e.g. `$FOAM_TITLE`) can be used within template metadata. However, VS Code snippet variables are ([currently](https://github.com/foambubble/foam/pull/655)) not supported.
### `filepath` attribute
The `filepath` metadata attribute allows you to define a relative or absolute filepath to use when creating a note using the template. If the filepath is a relative filepath, it is relative to the current workspace.
#### Example of **relative** `filepath`
For example, `filepath` can be used to customize `.foam/templates/new-note.md`, overriding the default `Foam: Create New Note` behaviour of opening the file in the same directory as the active file:
```yaml
---
# This will create the note in the "journal" subdirectory of the current workspace,
# regardless of which file is the active file.
foam_template:
filepath: 'journal/$FOAM_TITLE.md'
---
```
#### Example of **absolute** `filepath`
`filepath` can be an absolute filepath, so that the notes get created in the same location, regardless of which file or workspace the editor currently has open.
The format of an absolute filepath may vary depending on the filesystem used.
```yaml
---
foam_template:
# Unix / MacOS filesystems
filepath: '/Users/john.smith/foam/journal/$FOAM_TITLE.md'
# Windows filesystems
filepath: 'C:\Users\john.smith\Documents\foam\journal\$FOAM_TITLE.md'
---
```
#### Example of **date-based** `filepath`
#### `filepath` attribute
It is possible to vary the `filepath` value based on the current date using the `FOAM_DATE_*` variables. This is especially useful for the [[daily-notes]] template if you wish to organize by years, months, etc. Below is an example of a daily-note template metadata section that will create new daily notes under the `journal/YEAR/MONTH-MONTH_NAME/` filepath. For example, when a note is created on November 15, 2022, a new file will be created at `C:\Users\foam_user\foam_notes\journal\2022\11-Nov\2022-11-15-daily-note.md`. This method also respects the creation of daily notes relative to the current date (i.e. `/+1d`).
@ -146,27 +299,23 @@ It is possible to vary the `filepath` value based on the current date using the
---
type: daily-note
foam_template:
description: Daily Note for $FOAM_TITLE
filepath: "C:\\Users\\foam_user\\foam_notes\\journal\\$FOAM_DATE_YEAR\\$FOAM_DATE_MONTH-$FOAM_DATE_MONTH_NAME_SHORT\\$FOAM_DATE_YEAR-$FOAM_DATE_MONTH-$FOAM_DATE_DATE-daily-note.md"
description: Daily Note
filepath: '/journal/$FOAM_DATE_YEAR/$FOAM_DATE_MONTH-$FOAM_DATE_MONTH_NAME_SHORT/$FOAM_DATE_YEAR-$FOAM_DATE_MONTH-$FOAM_DATE_DATE-daily-note.md'
---
# $FOAM_DATE_YEAR-$FOAM_DATE_MONTH-$FOAM_DATE_DATE Daily Notes
```
> Note: this method **requires** the use of absolute file paths, and in this example is using Windows path conventions. This method will also override any filename formatting defined in `.vscode/settings.json`
### `name` and `description` attributes
#### `name` and `description` attributes
These attributes provide a human readable name and description to be shown in the template picker (e.g. When a user uses the `Foam: Create New Note From Template` command):
![Template Picker annotated with attributes](../../assets/images/template-picker-annotated.png)
### Adding template metadata to an existing YAML Frontmatter block
#### Adding template metadata to an existing YAML Frontmatter block
If your template already has a YAML Frontmatter block, you can add the Foam template metadata to it.
#### Limitations
Foam only supports adding the template metadata to _YAML_ Frontmatter blocks. If the existing Frontmatter block uses some other format (e.g. JSON), you will have to add the template metadata to its own YAML Frontmatter block.
Further, the template metadata must be provided as a [YAML block mapping](https://yaml.org/spec/1.2/spec.html#id2798057), with the attributes placed on the lines immediately following the `foam_template` line:
@ -182,11 +331,7 @@ foam_template: # this is a YAML "Block" mapping ("Flow" mappings aren't supporte
This is the rest of the template
```
Due to the technical limitations of parsing the complex YAML format, unless the metadata is provided this specific form, Foam is unable to correctly remove the template metadata before creating the resulting note.
If this limitation proves inconvenient to you, please let us know. We may be able to extend our parsing capabilities to cover your use case. In the meantime, you can add the template metadata without this limitation by providing it in its own YAML Frontmatter block.
### Adding template metadata to its own YAML Frontmatter block
#### Adding template metadata to its own YAML Frontmatter block
You can add the template metadata to its own YAML Frontmatter block at the start of the template:

View file

@ -10,7 +10,7 @@ To install search note-macros in vscode or head to [note-macros - Visual Studio
## Instructions
### Run macro From command pallette
### Run macro From command palette
Simply use `Ctrl+P` or `Alt+P` depend on your os, and type `Note Macros: Run A Macro` then chose the macro you want to execute.