zyedidia / micro

A modern and intuitive terminal-based text editor
https://micro-editor.github.io
MIT License
24.9k stars 1.17k forks source link

[QUESTION] Formatting/beautifying php, js, html,... #1899

Open ctuxboy opened 3 years ago

ctuxboy commented 3 years ago

Last weeks using this awesome Micro editor. Trying customizing some settings and keybindings. I'm a webdeveloper, but missing a formatting tool in Micro. Are there plans adding a formatting-tool/plugin for Micro? Found the fmt-plugin, but doesn't work in the latest Micro version (2.0.8).

jb2328 commented 3 years ago

Have the same question, formatting is very important and fmt stopped supporting anything that is over v2.0

zyedidia commented 3 years ago

You can make a custom formatter with a small amount of lua code. Here is the example from the Go plugin that uses gofmt (this code would go in ~/.config/micro/init.lua or a custom plugin in ~/.config/micro/plug/... if you choose):

local micro = import("micro")
local shell = import("micro/shell")

function gofmt(bp)
    bp:Save()
    local _, err = shell.RunCommand("gofmt -w " .. bp.Buf.Path)
    if err ~= nil then
        micro.InfoBar():Error(err)
        return
    end

    bp.Buf:ReOpen()
end

-- to run the formatter on every save:
function onSave(bp)
    if bp.Buf:FileType() == "go" then
        gofmt(bp)
    end
    return true
end

Of course, you would want to change gofmt to whatever tool you are using for formatting (it should do the formatting in-place on the file), and replace the filetype check with the filetype you are formatting.

Heart1010 commented 3 years ago

Anyone got this working for formatting php, html, c++ code?

entozoon commented 2 years ago

Yes @Heart1010 ! I actually got HTML, JS, TS, SCSS, etc formatting with Prettier on save, thanks to @zyedidia 's example.

npm i -g prettier
nano  ~/.config/micro/init.lua

Then pop this in:

local micro = import("micro")
local shell = import("micro/shell")

function gofmt(bp)
    bp:Save()
    local _, err = shell.RunCommand("prettier --write " .. bp.Buf.Path)
    if err ~= nil then
        micro.InfoBar():Error(_)
        return
    end

    bp.Buf:ReOpen()
end

-- to run the formatter on every save:
function onSave(bp)
    if bp.Buf:FileType() == "javascript" 
    or bp.Buf:FileType() == "jsx"
    or bp.Buf:FileType() == "angular"
    or bp.Buf:FileType() == "vue"
    or bp.Buf:FileType() == "flow"
    or bp.Buf:FileType() == "typescript"
    or bp.Buf:FileType() == "css"
    or bp.Buf:FileType() == "less"
    or bp.Buf:FileType() == "scss"
    or bp.Buf:FileType() == "html"
    or bp.Buf:FileType() == "json"
    or bp.Buf:FileType() == "graphql"
    or bp.Buf:FileType() == "markdown"
    or bp.Buf:FileType() == "yaml" then
        gofmt(bp)
    end
    return true
end