Skip to content
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

How to write metadata with indentation? #115

Open
Guts opened this issue Feb 21, 2024 · 1 comment
Open

How to write metadata with indentation? #115

Guts opened this issue Feb 21, 2024 · 1 comment

Comments

@Guts
Copy link

Guts commented Feb 21, 2024

Thanks for this useful package!

I'm using it to homogenize YAML frontmatter through thousands of Markdown files but I can't figure out how to keep the source file indentation (to 4):

Input Markdown:

---
date: 2023-05-12
title: Sample
tags:
    - test
    - sample
---

# Title 1

Script:

[...]
# write new version
with md_filepath.open(mode="w", encoding="UTF-8") as out_file:
    # frontmatter.dump(content, out_file) # not working, using workaround
    out_file.write(
        frontmatter.dumps(content, sort_keys=False, **{"indent": 4})
    )

Output Markdown:

See tags values

---
processed: true
date: 2023-05-12
title: Sample
tags:
- test
- sample
---

# Title 1
@PLRrex
Copy link

PLRrex commented Jul 7, 2024

Perhaps I'm too late to answer, but I tested the following code I adapted from this answer at stackoverflow with your input markdown and it seems to work.

import frontmatter
import yaml

class MyDumper(yaml.Dumper):
    def increase_indent(self, flow=False, indentless=False):
        return super(MyDumper, self).increase_indent(flow, False)

# code to read input here goes here

# write new version
with open(mode="w", encoding="UTF-8") as out_file:
    out_file.write(
        frontmatter.dumps(content, sort_keys=False, width=5000, Dumper=MyDumper, default_flow_style=False, indent=4)
    )

(The width=5000 is a nice trick you may find useful if some of your yaml values are longer than the default line width, resulting in them being undesirably wrapped to multiple lines, but that's another story.)

Also, I don't know why, but out of curiosity I tried changing indent=4 to something extreme like indent=20 and it goes back to the default(?) value of indenting 2 spaces, so perhaps the above code has some bugs hidden somewhere.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants