InsideDarkWeb.com

How to pretty-format code (auto-insert newlines, indent, etc)?

I’m using spacemacs but presumably it’s emacs knowledge that’s required here.

I have a JSON file with a single long line, let’s say this JSON from json.org/example:

{"menu": {"id": "file", "value": "File", "popup": {"menuitem": [{"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}]}}}

I would like emacs to reindent this, which means to me not change the leftmost character of line to the proper indentation level, but break the line in several lines.

If I use spacemacs/indent-region-or-buffer (SPC j =) then the text is not changed at all.

How could I ask from emacs to actually break this long line and reindent to get something like this:

{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}

I’m not interested in a JSON-specific answer, for instance I believe that intelliJ does that for any language it supports (java, json…). I would think it’s achievable for any language emacs has a major mode for, or let’s say the most popular ones.

EDIT I discovered M-x json-reformat-region that spacemacs ships with and works, but yes, I would like that for any language and with always the same shortcut, based on the major mode…

EDIT2 Ok so my conclusion is that it’s implemented for various languages, JSON & lisp at least, presumably others, and it would be easy for yet more (XML/XHTML, go which has go-fmt and also using clang). However there’s no generic function name that would do it for all the languages. There is space here to implement it in spacemacs layers for the various languages… I didn’t find a X/HTML implementation though, which surprises me a bit.

Emacs Asked by Emmanuel Touzery on November 18, 2021

7 Answers

7 Answers

I use json-mode-beautify

GNU Emacs 24.3.1

;;; json-mode.el --- Major mode for editing JSON files.

;; Copyright (C) 2011-2014 Josh Johnston

;; Author: Josh Johnston
;; URL: https://github.com/joshwnj/json-mode
;; Version: 1.6.0

Answered by yang xun on November 18, 2021

With emacs 26.3 you can just use the stock json-pretty-print function.

json-pretty-print is an interactive and compiled function defined in json.el.gz.

-- Emacs 26.3 documentation

select the region and M-x json-pretty-print.

I've just executed this procedure taking your example as input. Here is the result:

{
  "menu": {
    "id": "file",
    "value": "File",
    "popup": {
      "menuitem": [
        {
          "value": "New",
          "onclick": "CreateNewDoc()"
        },
        {
          "value": "Open",
          "onclick": "OpenDoc()"
        },
        {
          "value": "Close",
          "onclick": "CloseDoc()"
        }
      ]
    }
  }
}

Answered by ninrod on November 18, 2021

BTW, for major modes using SMIE as their indentation engine, there is some part of what you need for that in the form of an auto-fill-mode support. I think fill-paragraph or fill-region won't do a good job, but if you put your code onto a single line, then go to the end of that line and do M-: (smie-auto-fill) it should give sane results (probably not perfect by a long stretch, tho).

Answered by Stefan on November 18, 2021

For this specific scenario json-pretty-print will prettify the highlighted lump of json.

Answered by Fergie on November 18, 2021

json.el package provides json-pretty-print-buffer. This is what it produces for your example:

{
  "menu": {
    "popup": {
      "menuitem": [
        {
          "onclick": "CreateNewDoc()",
          "value": "New"
        },
        {
          "onclick": "OpenDoc()",
          "value": "Open"
        },
        {
          "onclick": "CloseDoc()",
          "value": "Close"
        }
      ]
    },
    "value": "File",
    "id": "file"
  }
}

Seems pretty decent to me.

Answered by wvxvw on November 18, 2021

According to the tip here, you can use external command to format a region in your Json file:

(defun json-format ()
  (interactive)
  (save-excursion
    (shell-command-on-region (region-beginning)
                             (region-end)
                             "python -m json.tool"
                             (buffer-name)
                             t)))

You can easily extend it to format the whole buffer:

(defun json-format ()
  (interactive)
  (save-excursion
    (shell-command-on-region (point-min)
                             (point-max)
                             "python -m json.tool"
                             (buffer-name) t))) 

Emacs does not have formatting tool for programming languages (except for Lisp), only indentation commands.

Answered by Tu Do on November 18, 2021

It looks like you need the fill-region function more than the indentation.

  • Select that line and do M-x fill-region.
  • Select the same, now split across multiple lines, and do M-x indent-region.

That will, though, not insert new lines at the exact points as shown in your example. It will simply make the line fit in the fill columns.

Answered by Kaushal Modi on November 18, 2021

Add your own answers!

Related Questions

Tramp can’t connect – cannot find ssh

0  Asked on September 2, 2021 by n1k31t4

     

Emacs insane CPU load caused by org-superstar-mode

2  Asked on September 2, 2021 by mor3dr3ad

   

What ASCII character is C-q C-E?

1  Asked on September 2, 2021

   

M-x man: Can’t find the %s manpage caused by loading helm

0  Asked on September 2, 2021 by wdkrnls

   

Can the ring data structure really be rotated?

1  Asked on September 2, 2021

 

How do I compose an email using Emacs’ keybindings?

0  Asked on September 2, 2021 by user81065

 

Can I take vector (SVG) screenshots of Emacs?

2  Asked on September 2, 2021 by clment

     

tramp and sudo: how to edit files under another account

3  Asked on September 2, 2021 by daniel-wu

 

Tramp session fails to recover from inactivity

2  Asked on September 2, 2021 by bignose

 

How company-mode suggestions are delivered?

1  Asked on September 2, 2021 by seonghyun-park

 

How to set utf-8 encoding for *markdown-output* buffer?

1  Asked on September 2, 2021 by volodymyr

 

Bind keybord shortcuts to a MIDI keyboard?

1  Asked on September 2, 2021 by gabriele-nicolardi

 

Ask a Question

Get help from others!

© 2021 InsideDarkWeb.com. All rights reserved.