andorsk / d2-mode

emacs major mode for d2 graphs
GNU General Public License v3.0
63 stars 7 forks source link

autoformat on save #30

Open alixander opened 1 year ago

alixander commented 1 year ago

Latest D2 version exposes a command for autoformatting D2 scripts. Intended to be used like Go's, i.e. format on save

https://github.com/terrastruct/d2/pull/292

andorsk commented 1 year ago

yes! good callout. thanks @alixander

andorsk commented 1 year ago

@alixander this is actually tricker than it looks.

For .d2 files, it's pretty clear what to do, but there are also d2 regions in emacs mode, which it's less clear. I think we would want to autoformat all the d2 regions as well on save.

I think a few functions are probably required to support this :

  1. format-buffer
  2. format-region
  3. format-file
  4. format-all-d2-regions ;; goes through all d2 codeblocks and formats them.
avelino commented 1 year ago

Example:

andorsk commented 1 year ago

@avelino yep. I'm aware of hooks you can configure on save with a hook. I think again, the tricky part here is region support. If that's not important for most people, I'm happy to implement a quick format command on the d2-mode. Personally, I tend to use d2 mostly in regions, which is why I've held back on implementing the simple solution.

Proposal here:

  1. Implement format support with caveat that region's won't be supported for now.
  2. Region formatting will be a roadmap item. I'm guessing it will be must more involved, as we'll have to write something to scan the file and format appropriately. Not sure what the right solution is there.

Are @avelino and @alixander ok with excluding region support?

alixander commented 1 year ago

Is regions like a markdown block? I do mostly edit just the d2 files standalone.

andorsk commented 1 year ago

@alixander exactly. Regions are blocks.

As an example:

This is a graph

```d2 A --> B ``` Commentary here.

Another graph:

```d2 A --> B ```

Commentary here.

I mostly do graphs in regions, so for me ( personally ) unless there's region support it becomes a lot less useful. I didn't know people use standalone files frequently. Might make sense to support this for standalone files.

I'll see about getting a PR started this weekend.

andorsk commented 1 year ago

Started work on a PR here: https://github.com/andorsk/d2-mode/pull/37