d2-mode icon indicating copy to clipboard operation
d2-mode copied to clipboard

autoformat on save

Open alixander opened this issue 2 years ago • 7 comments

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

alixander avatar Dec 08 '22 06:12 alixander

yes! good callout. thanks @alixander

andorsk avatar Dec 08 '22 10:12 andorsk

@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.

andorsk avatar Dec 08 '22 11:12 andorsk

Example:

avelino avatar Jan 04 '23 08:01 avelino

@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?

andorsk avatar Jan 04 '23 09:01 andorsk

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

alixander avatar Jan 04 '23 18:01 alixander

@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 avatar Jan 05 '23 09:01 andorsk

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

andorsk avatar Jan 07 '23 08:01 andorsk