Embed quotes (callouts) from all notes in one dataview list + add inline fields as columns in a dataviewjs table

What I’m trying to do

2 things that are related:

  • get all my quote callouts from the entire vault to appear in one note, ideally each in the callout format (for now I’ve managed only to get them in table form).
  • get all my (custom) vocab callouts from the entire vault to appear in one note in a table form (I’ve gotten that far), with additional columns to include info (metadata, inline fields?)

Things I have tried

I hope I’m using the correct vocabulary! Please try to explain things as simply as humanly possible; I’ve used Obsidian for a while but not anything super technical. I dabble and tinker with CSS, and I understand the very basics of Dataview, with some trial and error.
I’m now trying Dataviewjs, as this use case seems to require it, but I’ve never used JavaScript, so I’ve gleaned examples on this forum and on Reddit and tried to adapt them. Surprisingly, I’ve gotten to something that kind of works, but still not exactly as I wanted it to.

For the quotes:

I have 2 bits of code that each do part of what I want, but I can’t find a way to the exact thing I had in mind:

```dataviewjs
const pages = dv.pages()
const regex = />\s\[\!quote\]\s(.+?)((\n>\s.*?)*)\n/
const rows = [] 
for (const page of pages) { 
	const file = app.vault.getAbstractFileByPath(page.file.path) 
// Read the file contents 
	const contents = await app.vault.read(file) 
// Extract the summary via regex 
	for (const callout of contents.match(new RegExp(regex, 'sg')) || []) { 
		const match = callout.match(new RegExp(regex, 's')) 
		rows.push([match[1], match[2], page.file.link])
    }
}
const quote = []
quote.push(rows[Math.floor(Math.random()*rows.length)]);
let author = quote[0][0]
let quotetext = quote[0][1]
let note = quote[0][2]
let text = "> [!quote] " + author + " \| " + note + "\n> " + quotetext
dv.paragraph(text)
```

That first one gets me a callout format, but only for one (randomly selected) quote. It’s great for a “quote of the day” concept, but not what I wanted (seeing all of my quotes).

```dataviewjs

const pages = dv.pages('!"CalloutStyles"')

const regex = />\s\[\!quote\]\s(.+?)((\n>\s.*?)*)\n/

const rows = [] 
for (const page of pages) { 
	const file = app.vault.getAbstractFileByPath(page.file.path) 
// Read the file contents 
	const contents = await app.vault.read(file) 
// Extract the summary via regex 
	for (const callout of contents.match(new RegExp(regex, 'sg')) || []) { 
		const match = callout.match(new RegExp(regex, 's')) 
		rows.push([match[1], match[2], page.file.link])
    }
}

dv.table(['Author', 'Quote', 'Link'], rows)

```

That second one does give me all of my quotes, but in a table form, which I don’t find great especially for long quotes. I’d prefer the callout format, or at least some type of paragraph. Something like:

[!quote] Author
Quote that goes on and on…
[[Link]]

or
Author
Quote that goes on and on…
[[Link]]

Just to clarify: I always use the first line of the quote callouts to name the author, then below I include the quote itself. And at the beginning of the code here, I exclude a note where I list all my callout styles for reference.

Is there any way to get the best of both worlds?

For the vocab:

Now for the second thing, I’ve used a very similar bit of code to get all my vocab callouts into a table. These are customized callouts that I’ve created with CSS snippets, but I don’t think this really changes anything here.

The table works quite well, but I was wondering if I would include more columns for info like the language and the field for each word.

What I’m imagining would be adding this info in each callout in their respective notes, perhaps something like lg::EN (when the language is English); and the dataview table would include this info in a separate column.

Schematically:
Word | Definition | Language | Field | Link

I didn’t find examples online for this specifically (maybe I didn’t use the right search terms), and when I tried to add inline fields, they were just included in the Definition (main content) column (as you can see in the screenshot at the end of this post). Any of my naive attempts to edit the dv.table line just created errors.

Here’s the code I have at the moment (without that added info):

```dataviewjs

const pages = dv.pages('!"CalloutStyles"')

const regex = />\s\[\!vocab\]\s(.+?)((\n>\s.*?)*)\n/

const rows = [] 
for (const page of pages) { 
	const file = app.vault.getAbstractFileByPath(page.file.path) 
// Read the file contents 
	const contents = await app.vault.read(file) 
// Extract the summary via regex 
	for (const callout of contents.match(new RegExp(regex, 'sg')) || []) { 
		const match = callout.match(new RegExp(regex, 's')) 
		rows.push([match[1], match[2], page.file.link])
    }
}

dv.table(['Word', 'Definition', 'Link'], rows)

```

Is it possible to add those columns I’m envisioning, and how?

And one last tangentially related question: my dataviewjs table puts an empty line before the content itself, for the second column (the one that comes from the content of the callout below the title). Is that normal/avoidable? See below, the highlighted blank space.

Hi there, so I’ve actually solved my second question (and third, tangential question) to my satisfaction. If anyone’s interested:

```dataviewjs

// From all notes in the vault except for the one called CalloutStyles
const pages = dv.pages('!"CalloutStyles"')

// Define a regex that matches my !vocab callout
const regex = />\s\[\!vocab\]\s(.+?)((\n>\s.*?)*)\n/

const rows = [] 
for (const page of pages) { 
	const file = app.vault.getAbstractFileByPath(page.file.path) 

// Read the file contents 
	const contents = await app.vault.read(file) 

// Extract the summary via regex 
	for (const callout of contents.match(new RegExp(regex, 'sg')) || []) { 
		const match = callout.match(new RegExp(regex, 's'))

// Define parts of the contents you want (match[2] is the content below the title of your callout, here we're dividing it into smaller parts)

		// The first part goes from 3rd character (actual beginning of the text) to the first "<=" characters 

		const def = match[2].substring(
			3, 
			match[2].indexOf("<=")
		);

		// The second part goes from just after "<=" (+3 means you start after the space following <=) to the first # character

		const etym = match[2].substring(
		    match[2].indexOf("<=") + 3, 
		    match[2].indexOf("#")
		);

		// The third part goes from # (including it because I want to see it as a tag, otherwise add +1) to the last # character

		const lg = match[2].substring(
		    match[2].indexOf("#"), 
		    match[2].lastIndexOf("#")
		);

		// The last part goes from the last # (this excludes it, which doesn't bother me) to the end

		const usg = match[2].split('#').pop();

// Call the parts you've just defined to become rows (match[1] is the title of your callout; page.file.link is the link to the note the callout is in; the others are the names defined earlier in the code)

		rows.push([match[1], def, etym, lg, usg, page.file.link])
    }
}
// Create the table and name each column

dv.table(['Word', 'Definition', 'Etymology', 'Lg', 'Usage', 'Link'], rows)

```

… which gives me this table:

I do have to format the callouts quite carefully, it looks like this:

[!vocab] protean
changeable (protéiforme)
<= Proteus, Greek shape-shifting sea god
#EN #soutenu

(but different formatting could work, as long as you edit the code accordingly)

And the line below const def is the one that solved my blank line issue: it starts 3 characters after the theoretical beginning of the content, removing the characters before the text (added by the callout style, I think, as there is no added line break on my part).

I’m still at a loss on my first question with the quotes, though!

I have something similar for my medication tracker, it takes a set of values and renders them as bulletpoints with quotes. I use it for various overivews/summaries in my Templater files, for example:

In my case, CustomJS plugin is also needed because my workflow requires reusability, so the formatter lives in /_config/scripts/render.js as a custom “Render” class, and I then import what’s needed from it to use in templater or dv. If you’d rather not rely on more plugins, you can also hardcode it directly into your dv block.

(A)I made some examples below, one set with my data and another with what you’ve described, also included extra comments to explain the whys of the whats.


Using a custom JS class

My data is coming from a csv file, so skipping explanations of that part, but basilcally, to produce what’s shown on the screenshot above, you’d have something like this inside of the summary.md file:

//```dataviewjs
const { Logs, Dates, Render } = await cJS(); // calls the custom classes

const page = dv.current();
const logs = await Logs.retrieveLogs(dv);
if (!logs) return;

// ...processing goes here...


// renders the formatting from a class using processed values
dv.paragraph(Render.renderTree({
  Total: `${logs.records.total} records`,
  Today: max == null ? `${taken} logged` : `${taken} of ${max} doses (${left} remaining)`,
  Last:  last ? `${last.value}${unit} · ${Dates.formatDuration(last.date, Dates.now()).asLabel}` : "no records",
  Next:  nextLine,
}, { quote: true }));

With this code driving it underneath (lives in the scripts folder, reusable):

class Render {

  renderTree(obj, opts = {}) {
  // Render a nested object as a markdown bullet tree.
  // Returns one string with leading "\n" so it can be used by dv.paragraph.
  //
  // Every key becomes `- **key:** value`, and `value` accepts:
  //   leaf (string/number/bool)  printed inline after the label
  //   array                      label alone, then one bullet per item
  //   object                     label alone, then its keys one level deeper
  //   { label, value }           `label` replaces the object key as the display
  //                              name; `value` is again any of the above
  //
  // Nesting is drawn with blockquotes, not list indentation: 
  // depth 0 is a plain list, and every deeper line is prefixed `> ` 
  // plus two spaces per level.
    const quoteAll = opts.quote ?? false;
    // Check if the data is already labeled:
    // `{ label, value }` wrapper is not the same as a plain nested object 
    // both are objects, but the wrapper is a relabelled leaf, not a subtree
    const isLabelPair = x =>
      x !== null && typeof x === "object" && !Array.isArray(x)
      && "label" in x && "value" in x;

    // Line prefixes:
    // `bullet` skips the quote marker at depth 0 (top level is a plain list); 
    // `quote` always emits it, since quoted leaves only appear
    // under a label that has already opened the block.
    const bullet = d => (d === 0 ? "" : `> ${"  ".repeat(d)}`);
    const quote  = d => `> ${"  ".repeat(d)}`;

    // Process the data and build a new string:
    const walk = (node, depth) => {
      const lines = [];
      for (const [k, v] of Object.entries(node)) {
        const pair = isLabelPair(v);
        const name = pair ? v.label : k;
        const val  = pair ? v.value : v;
        const q    = pair && "quote" in v ? v.quote : quoteAll;

        if (Array.isArray(val)) {
          lines.push(`${bullet(depth)}- **${name}:**`);
          for (const item of val) lines.push(`${bullet(depth + 1)}- ${item}`);
        } else if (val !== null && typeof val === "object") {
          lines.push(`${bullet(depth)}- **${name}:**`);
          lines.push(walk(val, depth + 1));
        } else if (q) {
          lines.push(`${bullet(depth)}- **${name}:**`);
          lines.push(String(val).split("\n").map(l => `${quote(depth)}${l}`).join("\n"));
        } else {
          lines.push(`${bullet(depth)}- **${name}:** ${val}`);
        }
      }
      return lines.join("\n");
    };
    return `\n${walk(obj, 0)}`;
  }
}

Example of custom helpers class with your data structure

(made with AI and not tested as I don’t have your data)


class Quotes {  
  // --- callouts -----------------------------------------------------------
  //
  // Gather every `[!quote]` (or any other type) in the vault into one note.
  //
  // Scanned line by line rather than by regex, because a callout is a run of
  // lines starting with `>` at one indent -- a state, not a pattern. Regex
  // versions half-work and then lose callouts containing a blank line (that
  // line is a bare `>`, so `\n>\s` stops matching), callouts ending at EOF, and
  // the structure of anything nested.

  // Every callout of `type` in one file's text. Pure, so it is testable.
  parseCallouts(text, type) {
    const want = String(type).toLowerCase();
    const lines = String(text).split("\n");
    const out = [];

    for (let i = 0; i < lines.length; i++) {
      // `> [!type] Title`, optionally indented, optionally foldable (`+`/`-`)
      const head = lines[i].match(/^([ \t]*)>[ \t]?\[!([^\]]+)\][+-]?[ \t]*(.*)$/);
      if (!head) continue;
      const [, indent, kind, title] = head;

      // The block runs on while lines keep quoting at this indent -- a bare `>`
      // included, which is the line regex versions stop at.
      let end = i + 1;
      while (end < lines.length) {
        const m = lines[end].match(/^([ \t]*)>/);
        if (!m || m[1].length < indent.length) break;
        end++;
      }

      if (kind.trim().toLowerCase() === want) {
        const block = lines.slice(i, end).map(l => l.slice(indent.length));

        // Inline fields (`key:: value` on their own line) are metadata, not
        // prose, so they move to `fields` and leave the body. Keys lowercase
        // with dashes, as Dataview sanitises them: `Part of speech` -> part-of-speech.
        const fields = {}, prose = [];
        for (const l of block.slice(1).map(l => l.replace(/^>[ \t]?/, ""))) {
          const f = l.match(/^([A-Za-z][\w -]*?)[ \t]*::[ \t]*(.*)$/);
          if (f) fields[f[1].toLowerCase().replace(/ /g, "-")] = f[2].trim();
          else prose.push(l);
        }

        out.push({
          title: title.trim(),
          fields,
          body: prose.join("\n").trim(),
          // Verbatim source (shared indent removed, trailing blank quote lines
          // trimmed). Re-emitting these lines as-is is what keeps nested
          // callouts, lists and images intact; rebuilding from the parts
          // flattens all of it.
          raw: block.join("\n").replace(/(\n>[ \t]*)+$/, ""),
        });
      }
      i = end - 1;   // resume past the block
    }
    return out;
  }

  // Every matching callout in the vault, note order. `skip` is a path prefix or
  // a list of them -- typically the note where the callout styles are kept.
  async collectCallouts(type, skip = []) {
    const skips = [].concat(skip);
    const files = app.vault.getMarkdownFiles().sort((a, b) => (a.path < b.path ? -1 : 1));
    const out = [];
    for (const file of files) {
      if (skips.some(s => file.path.startsWith(s))) continue;
      // cachedRead, not read: this touches every note and only displays it.
      const text = await app.vault.cachedRead(file);
      if (!text.includes("[!")) continue;   // cheap skip for most notes
      for (const c of this.parseCallouts(text, type)) out.push({ ...c, file });
    }
    return out;
  }

  // Print each one with a link back to its note. Returns the list, so a note
  // can render the callouts and then table the same pass.
  //
  // One dv.paragraph per callout rather than one joined string, so a malformed
  // callout spoils only its own block.
  async renderCallouts(dv, type, skip) {
    const items = await this.collectCallouts(type, skip);
    if (!items.length) dv.paragraph(`No \`[!${type}]\` callouts found.`);
    for (const c of items) {
      dv.paragraph(`${c.raw}\n> [[${c.file.path.replace(/\.md$/, "")}|${c.file.basename}]]`);
    }
    return items;
  }
}

Once this is ready, you can then call it within dv blocks:

//```dataviewjs
await customJS.Quotes.renderCallouts(dv, "quote", "CalloutStyles");


Standalone example

Can be used in a dataviewjs block directly, without the custom JS plugin and setup:

//```dataviewjs
const TYPE = "quote";               // callout type to collect
const SKIP = ["CalloutStyles"];     // path prefixes to leave out

for (const file of app.vault.getMarkdownFiles().sort((a, b) => a.path < b.path ? -1 : 1)) {
  if (SKIP.some(s => file.path.startsWith(s))) continue;
  const lines = (await app.vault.cachedRead(file)).split("\n");

  for (let i = 0; i < lines.length; i++) {
    const head = lines[i].match(/^([ \t]*)>[ \t]?\[!([^\]]+)\][+-]?[ \t]*(.*)$/);
    if (!head) continue;
    const [, indent, kind] = head;

    // the block runs on while lines keep quoting at this indent, bare `>` included
    let end = i + 1;
    while (end < lines.length) {
      const m = lines[end].match(/^([ \t]*)>/);
      if (!m || m[1].length < indent.length) break;
      end++;
    }

    if (kind.trim().toLowerCase() === TYPE) {
      // verbatim lines, so nesting and formatting survive; link on the last one
      const raw = lines.slice(i, end).map(l => l.slice(indent.length)).join("\n");
      dv.paragraph(`${raw}\n> [[${file.path.replace(/\.md$/, "")}|${file.basename}]]`);
    }
    i = end - 1;
  }
}

Or like this if you want a table:

//```dataviewjs
const items = await customJS.Quotes.collectCallouts("vocab");
dv.table(["Term", "Language", "Definition", "Source"],
  items.map(c => [c.title, c.fields.lang, c.body, dv.fileLink(c.file.path)]));