Code Monkey home page Code Monkey logo

juliaformatter.vim's Introduction

JuliaFormatter.vim

Plugin for formatting Julia code in (n)vim using JuliaFormatter.jl.

Note: LanguageServer.jl now supports JuliaFormatter.jl, so you may not want to use this if you already are using lsp with vim/neovim.

Install

Use any plugin manager:

vim-plug

Plug 'kdheepak/JuliaFormatter.vim'

dein.vim

call dein#add('kdheepak/JuliaFormatter.vim')

Vundle.vim

Plugin 'kdheepak/JuliaFormatter.vim'

Usage

Open any Julia file, type : to open the command prompt and type the following:

" format full file
:JuliaFormatterFormat
" format last/current selection
:'<,'>JuliaFormatterFormat
" format from line 5 to line 15 inclusive
:5,15JuliaFormatterFormat

You can remap this to a keyboard shortcut as well.

" normal mode mapping
nnoremap <localleader>jf :JuliaFormatterFormat<CR>
" visual mode mapping
vnoremap <localleader>jf :JuliaFormatterFormat<CR>

The (n)vim documentation recommends using <localleader> for a filetype plugin, but feel free to use <leader> or <localleader> for this remap. In (n)vim, both <leader> and <localleader> are set to the \ key by default.

Feel free to open an issue for debugging a problem, questions or feature requests.

For debugging, the following is useful to check.

:JuliaFormatterEchoCmd

You can access the JuliaFormatter server log file by running the following:

:JuliaFormatterLog

Finally, you can run JuliaFormatterUpdate to run julia --project=/path/to/vim_plugin/ -e "using Pkg; Pkg.update()"

:JuliaFormatterUpdate

Note that this repository has loose compat bounds for JuliaFormatter.jl or PackageCompiler.jl. This will most likely result in the latest version of JuliaFormatter.jl and PackageCompiler.jl being installed. If this plugin doesn't work with the latest versions of these packages, please open an issue. Older versions are supported on a best effort basis.

Options

Setting Format Options

Click to expand!

To modify the formatting options can be modified by setting g:JuliaFormatter_options in your vimrc. An example of this is:

let g:JuliaFormatter_options = {
        \ 'indent'                    : 4,
        \ 'margin'                    : 92,
        \ 'always_for_in'             : v:false,
        \ 'whitespace_typedefs'       : v:false,
        \ 'whitespace_ops_in_indices' : v:true,
        \ }

This translates to a call to:

JuliaFormatter.format_text(vim_text_selection_or_buffer, indent = 4, margin = 92; always_for_in = true, whitespace_typedef = false, whitespace_ops_in_indices = true)

See full list of options over on the JuliaFormatter API documentation.

Compatibility with BlueStyle and YASStyle

Click to expand!

JuliaFormatter.vim enables compatibility with BlueStyle and YAS.

Here is how to configure (n)vim for BlueStyle or YAS:

  1. Install JuliaFormatter.vim

  2. Add the following to your vimrc to follow the BlueStyle standard:

    let g:JuliaFormatter_options = {
            \ 'style' : 'blue',
            \ }

    This translates to a call to:

    style = BlueStyle()
    JuliaFormatter.format_text(vim_text_selection_or_buffer, style = style)

    OR

    Add the following to your vimrc to follow the YAS standard:

    let g:JuliaFormatter_options = {
            \ 'style' : 'yas',
            \ }

    This translates to a call to:

    style = YASStyle()
    JuliaFormatter.format_text(vim_text_selection_or_buffer, style = style)
  3. (Optional) Create a file in the path ~/.vim/after/ftplugin/julia.vim and add to the julia.vim file the following:

    " ~/.vim/after/ftplugin/julia.vim
    setlocal expandtab       " Replace tabs with spaces.
    setlocal textwidth=92    " Limit lines according to Julia's CONTRIBUTING guidelines.
    setlocal colorcolumn+=1  " Highlight first column beyond the line limit.

Support .JuliaFormatter.toml configuration

Click to expand!

When :JuliaFormatterFormat is called, it will look for .JuliaFormatter.toml in the location of the file being formatted, and searching up the file tree until a config file is (or isn't) found. When found, the configurations in the file will overwrite the options provided by g:JuliaFormatter_options.

See https://domluna.github.io/JuliaFormatter.jl/stable/config/ for more information.

Precompiling JuliaFormatter using PackageCompiler

Click to expand!

Using a custom system image can speedup the initialization time of the plugin. This can be done using PackageCompiler.jl.

PackageCompiler.jl can be used with JuliaFormatter.vim by running the following:

$ cd /path/to/JuliaFormatter.vim/
$ julia --project scripts/packagecompiler.jl

This will create a Julia sysimage that is stored in /path/to/JuliaFormatter.vim/scripts folder. You can type :echo g:JuliaFormatter_root in (n)vim to find where /path/to/JuliaFormatter.vim/ is. For more information check (n)vim documentation or consult your plugin manager documentation.

Then in your vimrc set:

let g:JuliaFormatter_use_sysimage=1

If you would like to use a sysimage that is located elsewhere, you can do so too. Add the following to your vimrc:

let g:JuliaFormatter_use_sysimage=1
let g:JuliaFormatter_sysimage_path="/path/to/julia_sysimage.so"

Launching the JuliaFormatter server when opening a Julia file

Click to expand!

By default, the JuliaFormatter server is only started the first time you call :JuliaFormatterFormat. This means your first format will be slower than the remaining times for an open session of (n)vim. PackageCompiler.jl compiles JuliaFormatter.jl, JSON.jl and other methods used for formatting Julia code and this significantly speeds up the first call to :JuliaFormatterFormat. Once the server is started, it is waiting for input on stdin and remaining calls will be fast.

Additionally, if you would like, you can start the server when you open a Julia file for the first time instead of when you call :JuliaFormatterFormat for the first time. Just add the following in your vimrc:

let g:JuliaFormatter_always_launch_server=1

Format on save using neovim built in LSP formatting

You'll need https://github.com/mattn/efm-langserver. Add the following to your .vimrc:

require"lspconfig".efm.setup {
    init_options = {documentFormatting = true},
    filetypes = {"julia"},
    settings = {
        rootMarkers = {".git/"},
        languages = {
            julia = {require("juliaformatter").efmConfig}
        }
    }
}

Then you can this to ftplugin/julia.vim:

autocmd BufWritePre *.jl lua vim.lsp.buf.formatting_sync()

This works best if you have and use PackageCompiler to compile JuliaFormatter into a sysimage.

You can run the following to see what process is executed on the command line to format your code:

:lua print(require("juliaformatter").efmConfig)

Troubleshooting

Click to expand!

See MINRC before opening an issue.

juliaformatter.vim's People

Contributors

00sapo avatar blegat avatar emig avatar kdheepak avatar lassepe avatar moelf avatar ndgnuh avatar nickrobinson251 avatar storopoli avatar thecedarprince avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

juliaformatter.vim's Issues

Undefined variable `s:job` when calling JuliaFormatter#Kill from the plugin file

I think the error occurs because when JuliaFormatter#Kill is being called (from the plugin/ file) it doesn't know anything about script-local variables defined in the autoload file. You might need to refactor a bit to define job ID in the plugin/ file.

Related to #27.

My neovim version:

❯ nvim --version
NVIM v0.4.4
Build type: Release
LuaJIT 2.0.5
Compilation: /usr/bin/cc -D_FORTIFY_SOURCE=2 -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1 -O2 -DNDEBUG -DMIN_LOG_LEVEL=3 -Wall -Wextra -pedantic -Wno-unused-parameter -Wstrict-prototypes -std=gnu99 -Wshadow -Wconversion -Wmissing-prototypes -Wimplicit-fallthrough -Wvla -fstack-protector-strong -fno-common -fdiagnostics-color=always -DINCLUDE_GENERATED_DECLARATIONS -D_GNU_SOURCE -DNVIM_MSGPACK_HAS_FLOAT32 -DNVIM_UNIBI_HAS_VAR_FROM -I/build/neovim/src/build/config -I/build/neovim/src/neovim-0.4.4/src -I/usr/include -I/build/neovim/src/build/src/nvim/auto -I/build/neovim/src/build/include
Compiled by builduser

Minimal vimrc (remember to change the vim-plug path):

set nocompatible              " be iMproved, required
filetype off                  " required

call plug#begin('~/.local/share/nvim/plugged')
    Plug 'kdheepak/JuliaFormatter.vim'
call plug#end()

Relevant snippet from vim log:

Executing VimLeavePre Autocommands for "*"
autocommand call JuliaFormatter#Kill()

Searching for "autoload/JuliaFormatter.vim" in "/home/admin/.config/nvim,/home/admin/.local/share/nvim/plugged/JuliaFormatter.vim,/etc/xdg/nvim,/home/admin/.local/share/nvim/site,/usr/local/share/nvim/site,/usr/share/nvim/site,/usr/share/nvim/runtime,/usr/share/nvim/runtime/pack/dist/opt/matchit,/usr/share/nvim/site/after,/usr/local/share/nvim/site/after,/home/admin/.local/share/nvim/site/after,/etc/xdg/nvim/after,/home/admin/.config/nvim/after"
Searching for "/home/admin/.config/nvim/autoload/JuliaFormatter.vim"
Searching for "/home/admin/.local/share/nvim/plugged/JuliaFormatter.vim/autoload/JuliaFormatter.vim"
chdir(/home/admin/issuedrafts/juliaformatter-lsp-ale)
chdir(/home/admin/.local/share/nvim/plugged/JuliaFormatter.vim/autoload)
chdir(/home/admin/issuedrafts/juliaformatter-lsp-ale)
line 0: sourcing "/home/admin/.local/share/nvim/plugged/JuliaFormatter.vim/autoload/JuliaFormatter.vim"
finished sourcing /home/admin/.local/share/nvim/plugged/JuliaFormatter.vim/autoload/JuliaFormatter.vim
continuing in VimLeavePre Autocommands for "*"
                                              Error detected while processing function JuliaFormatter#Kill:
line    2:
E121: Undefined variable: s:job
E15: Invalid expression: s:job > 0

Is there some way to not show the log message every time I open a file?

Troubleshooting

  • vim 8.2
(juliaformatter) pkg> st
      Status `/vim_location/juliaformatter/Project.toml`
  [682c06a0] JSON v0.21.1
  [98e50ef6] JuliaFormatter v0.15.0
  [9b87118b] PackageCompiler v1.2.6
Julia Version 1.6.1
Commit 6aaedecc44 (2021-04-23 05:59 UTC)
Platform Info:
  OS: macOS (x86_64-apple-darwin18.7.0)
  CPU: Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-11.0.1 (ORCJIT, skylake)

Is there some way to skip the log message that shows up every time I open a file when I have let g:JuliaFormatter_always_launch_server=1? It's getting quite annoying to have to hit enter a second time every time I open a file.

Every file I open I get the following:

"ssh.jl" 36L, 1282B
[JuliaFormatter] started JuliaFormatter server (see :JuliaFormatterEchoCmd)julia --startup-file=no --color=no --project=/vim_location/juliaformatter /vim_location/juliaformatter/scripts/server.jl
Press ENTER or type command to continue

My vim settings for this plugin are as follows:

let g:JuliaFormatter_use_sysimg=1
let g:JuliaFormatter_always_launch_server=1

let g:JuliaFormatter_options = {
    \ 'style' : 'blue',
    \ }

Julia process pins CPU at 100% after vim is closed

Troubleshooting

akako@ThinkX ~/D/g/Julia (fix_search_last)> vim --version
NVIM v0.5.0-dev+1386-gfd7e77b22
Build type: RelWithDebInfo
LuaJIT 2.1.0-beta3
Compilation: /usr/bin/cc -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1 -O2 -g -Og -g -Wall -Wextra -pedantic -Wno-unused-parameter -Wstrict-prototypes -std=gnu99 -Wshadow -Wconversion -Wmissing-prototypes -Wimplicit-fallthrough -Wvla -fstack-protector-strong -fno-common -fdiagnostics-color=always -DINCLUDE_GENERATED_DECLARATIONS -D_GNU_SOURCE -DNVIM_MSGPACK_HAS_FLOAT32 -DNVIM_UNIBI_HAS_VAR_FROM -DMIN_LOG_LEVEL=3 -I/home/runner/work/neovim/neovim/build/config -I/home/runner/work/neovim/neovim/src -I/home/runner/work/neovim/neovim/.deps/usr/include -I/usr/include -I/home/runner/work/neovim/neovim/build/src/nvim/auto -I/home/runner/work/neovim/neovim/build/include
Compiled by runner@fv-az68-784

Features: +acl +iconv +tui
See ":help feature-compile"

julia --project=~/.vim/plugged/JuliaFormatter.vim/ -e "using Pkg; Pkg.status()"
      Status `~/.vim/plugged/JuliaFormatter.vim/Project.toml`
  [682c06a0] JSON v0.21.1
  [98e50ef6] JuliaFormatter v0.14.4
  [9b87118b] PackageCompiler v1.2.5

julia --project=~/.vim/plugged/JuliaFormatter.vim/ -e "using InteractiveUtils; versioninfo()"
Julia Version 1.6.1
Commit 6aaedecc44 (2021-04-23 05:59 UTC)
Platform Info:
  OS: Linux (x86_64-pc-linux-gnu)
  CPU: Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-11.0.1 (ORCJIT, skylake)
Environment:
  JULIA_NUM_THREADS = 4

Error when quit vim

  • vim version: 8.2-2891
  • JuliaFormatter.vim: d30ba16

Hello, today after I update the plugin, these errors occur whenever I quit vim from arbitray file.

image

Translation:
Error when processing autocmd "*" ..function JuliaFormatter#kill:
Line 6:
E475: Invalid argument: 0
Line 7:
E475: Invalid argument: 0

Not idempotent (extra newline every time)

Each time call JuliaFormatter#Format(0) is called an extra newline is added to the end of the file.

Troubleshooting

vim info:

VIM - Vi IMproved 8.1 (2018 May 18, compiled Dec 29 2019 00:36:15)

julia info:

julia> versioninfo()
Julia Version 1.3.1
Commit 2d5741174c (2019-12-30 21:36 UTC)
Platform Info:
  OS: macOS (x86_64-apple-darwin18.6.0)
  CPU: Intel(R) Core(TM) i7-4980HQ CPU @ 2.80GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-6.0.1 (ORCJIT, haswell)
Environment:
  JULIA_EDITOR = vim
  JULIA_PKG_DEVDIR = /Users/jekozdon/codes/julia_dev

Long startup time

64   │ 1174.081  1105.161  1105.161: sourcing /home/akako/.local/share/nvim/site/pack/packer/start/JuliaFormatter.vim/plugin/JuliaFormatter.vim

Annoying auto-formatter

Although auto formatting with autocmd is supported, auto formatting is super annoying for two reason:

  1. When the file is saved, the formatter runs and rewrite the file, make it unsaved again, results in a file that will never be saved
  2. When I'm editting at the middle of the file and hit save, the formatter make the cursor jump to the end of the file.

I like not having to worry about the format of my code, but having to jump back every time I save is actually worse.

Troubleshooting

vim --version
NVIM v0.4.4
Build type: Release
LuaJIT 2.1.0-beta3
Compilation: /usr/lib/ccache/bin/cc -fstack-clash-protection -D_FORTIFY_SOURCE=2 -mtune=generic -O2  -g -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1 -O2 -DNDEBUG -DMIN_LOG_LEVEL=3 -Wall -Wextra -pedantic -Wno-unused-parameter -Wstrict-prototypes -std=gnu99 -Wshadow -Wconversion -Wmissing-prototypes -Wimplicit-fallthrough -Wvla -fstack-protector-strong -fno-common -fdiagnostics-color=auto -DINCLUDE_GENERATED_DECLARATIONS -D_GNU_SOURCE -DNVIM_MSGPACK_HAS_FLOAT32 -DNVIM_UNIBI_HAS_VAR_FROM -I/builddir/neovim-0.4.4/build/config -I/builddir/neovim-0.4.4/src -I/usr/include -I/builddir/neovim-0.4.4/build/src/nvim/auto -I/builddir/neovim-0.4.4/build/include
Compiled by void-buildslave@a-hel-fi

Features: +acl +iconv +tui
See ":help feature-compile"

   system vimrc file: "$VIM/sysinit.vim"
  fall-back for $VIM: "/usr/share/nvim"

Run :checkhealth for more info
julia --project=/path/to/JuliaFormatter.vim/ -e "using Pkg; Pkg.status()"
Status `~/.config/nvim/plug/JuliaFormatter.vim/Project.toml`
  [682c06a0] JSON v0.21.1
  [98e50ef6] JuliaFormatter v0.13.4
  [9b87118b] PackageCompiler v1.2.5
julia --project=/path/to/JuliaFormatter.vim/ -e "using JuliaFormatter; versioninfo()"
Julia Version 1.6.0-beta1
Commit b84990e1ac (2021-01-08 12:42 UTC)
Platform Info:
  OS: Linux (x86_64-pc-linux-gnu)
  CPU: Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-11.0.0 (ORCJIT, skylake)
Environment:
  JULIA_DEPOT_PATH = /home/hung/.cache/julia
  JULIA_NUM_THREADS = 4
Can you reproduce the output using [`MINRC`](../blob/master/tests/MINRC)?

I have to change some path in minrc to make it works, but yes, the problem persists.

Post relevant section from log file below ``` [2021-03-14T13:51:58.453] calling main ... [2021-03-14T13:52:00.466] Connected. [2021-03-14T13:52:00.507] Setting up defaults ... [2021-03-14T13:52:00.512] Searching for .JuliaFormatter.toml ... [2021-03-14T13:52:00.512] No .JuliaFormatter.toml [2021-03-14T13:52:00.583] Using options: Dict{Symbol, Any}(:indent => 4, :margin => 92, :always_for_in => false, :whitespace_typedefs => false, :whitespace_ops_in_indices => true, :style => DefaultStyle(nothing)) with style: DefaultStyle(nothing) [2021-03-14T13:52:00.591] Formatting: [2021-03-14T13:52:00.601] module SaleDSS

using Base.Threads
using Dash
using DashCoreComponents
using DashHtmlComponents
using DashBootstrapComponents

app = dash()

app.layout = html_div() do
html_span("Input 1:"),
dcc_input(; id="input-1", value="", type="text"),
html_div(""),
html_span("Input 2:"),
dcc_input(; id="input-2", value="", type="text"),
html_p("Output..."; id="my-div"),
html_div("..."; id="output")
end

callback!(
app, Output("output", "children"), Input("input-1", "value"), State("input-2", "value")
) do ip1, ip2
"""
input-1: $(ip1)...
input-2: $(ip2)
"""
end

function main()
host = get(ENV, "HOST", "0.0.0.0")
port = get(ENV, "PORT", "8080")
return run_server(app, "0.0.0.0", 8080; debug=true)
end

function julia_main()::Cint
try
# @show ARGS
# @show Base.PROGRAM_FILE
# @show DEPOT_PATH
# @show LOAD_PATH
# @show pwd()
# @show Base.active_project()
# @show Threads.nthreads()
# @show Sys.BINDIR
# display(Base.loaded_modules)
main(app)
println()
catch
Base.invokelatest(Base.display_error, Base.catch_stack())
end
return 0
end

end # module
[2021-03-14T13:52:08.898] Success
[2021-03-14T13:52:08.898]

[2021-03-14T13:52:08.898] Formatted:
[2021-03-14T13:52:08.898]
module SaleDSS

using Base.Threads
using Dash
using DashCoreComponents
using DashHtmlComponents
using DashBootstrapComponents

app = dash()

app.layout = html_div() do
html_span("Input 1:"),
dcc_input(; id = "input-1", value = "", type = "text"),
html_div(""),
html_span("Input 2:"),
dcc_input(; id = "input-2", value = "", type = "text"),
html_p("Output..."; id = "my-div"),
html_div("..."; id = "output")
end

callback!(
app,
Output("output", "children"),
Input("input-1", "value"),
State("input-2", "value"),
) do ip1, ip2
"""
input-1: $(ip1)...
input-2: $(ip2)
"""
end

function main()
host = get(ENV, "HOST", "0.0.0.0")
port = get(ENV, "PORT", "8080")
return run_server(app, "0.0.0.0", 8080; debug = true)
end

function julia_main()::Cint
try
# @show ARGS
# @show Base.PROGRAM_FILE
# @show DEPOT_PATH
# @show LOAD_PATH
# @show pwd()
# @show Base.active_project()
# @show Threads.nthreads()
# @show Sys.BINDIR
# display(Base.loaded_modules)
main(app)
println()
catch
Base.invokelatest(Base.display_error, Base.catch_stack())
end
return 0
end

end # module
[2021-03-14T13:52:09.175] Done.
[2021-03-14T13:52:19.525] Connected.
[2021-03-14T13:52:19.525] Setting up defaults ...
[2021-03-14T13:52:19.525] Searching for .JuliaFormatter.toml ...
[2021-03-14T13:52:19.525] No .JuliaFormatter.toml
[2021-03-14T13:52:19.526] Using options: Dict{Symbol, Any}(:indent => 4, :margin => 92, :always_for_in => false, :whitespace_typedefs => false, :whitespace_ops_in_indices => true, :style => DefaultStyle(nothing)) with style: DefaultStyle(nothing)
[2021-03-14T13:52:19.526] Formatting:
[2021-03-14T13:52:19.526]
module SaleDSS

using Base.Threads
using Dash
using DashCoreComponents
using DashHtmlComponents
using DashBootstrapComponents

app = dash()

app.layout = html_div() do
html_span("Input 1:"),
dcc_input(; id = "input-1", value = "", type = "text"),
html_div(""),
html_span("Input 2:"),
dcc_input(; id = "input-2", value = "", type = "text"),
html_p("Output..."; id = "my-div"),
html_div("..."; id = "output")
end

callback!(
app,
Output("output", "children"),
Input("input-1", "value"),
State("input-2", "value"),
) do ip1, ip2
"""
input-1: $(ip1)...
input-2: $(ip2)
"""
end

function main()
host = get(ENV, "HOST", "0.0.0.0")
port = get(ENV, "PORT", "8080")
return run_server(app, "0.0.0.0", 8080; debug = true)
end

function julia_main()::Cint
try
# @show ARGS
# @show Base.PROGRAM_FILE
# @show DEPOT_PATH
# @show LOAD_PATH
# @show pwd()
# @show Base.active_project()
# @show Threads.nthreads()
# @show Sys.BINDIR
# display(Base.loaded_modules)
main(app)
println()
catch
Base.invokelatest(Base.display_error, Base.catch_stack())
end
return 0
end

end # module
[2021-03-14T13:52:19.527] Success
[2021-03-14T13:52:19.527]

[2021-03-14T13:52:19.527] Formatted:
[2021-03-14T13:52:19.527]
module SaleDSS

using Base.Threads
using Dash
using DashCoreComponents
using DashHtmlComponents
using DashBootstrapComponents

app = dash()

app.layout = html_div() do
html_span("Input 1:"),
dcc_input(; id = "input-1", value = "", type = "text"),
html_div(""),
html_span("Input 2:"),
dcc_input(; id = "input-2", value = "", type = "text"),
html_p("Output..."; id = "my-div"),
html_div("..."; id = "output")
end

callback!(
app,
Output("output", "children"),
Input("input-1", "value"),
State("input-2", "value"),
) do ip1, ip2
"""
input-1: $(ip1)...
input-2: $(ip2)
"""
end

function main()
host = get(ENV, "HOST", "0.0.0.0")
port = get(ENV, "PORT", "8080")
return run_server(app, "0.0.0.0", 8080; debug = true)
end

function julia_main()::Cint
try
# @show ARGS
# @show Base.PROGRAM_FILE
# @show DEPOT_PATH
# @show LOAD_PATH
# @show pwd()
# @show Base.active_project()
# @show Threads.nthreads()
# @show Sys.BINDIR
# display(Base.loaded_modules)
main(app)
println()
catch
Base.invokelatest(Base.display_error, Base.catch_stack())
end
return 0
end

end # module
[2021-03-14T13:52:19.527] Done.
[2021-03-14T13:52:38.670] Connected.
[2021-03-14T13:52:38.670] Setting up defaults ...
[2021-03-14T13:52:38.670] Searching for .JuliaFormatter.toml ...
[2021-03-14T13:52:38.670] No .JuliaFormatter.toml
[2021-03-14T13:52:38.671] Using options: Dict{Symbol, Any}(:indent => 4, :margin => 92, :always_for_in => false, :whitespace_typedefs => false, :whitespace_ops_in_indices => true, :style => DefaultStyle(nothing)) with style: DefaultStyle(nothing)
[2021-03-14T13:52:38.671] Formatting:
[2021-03-14T13:52:38.671]
module SaleDSS

using Base.Threads
using Dash
using DashCoreComponents
using DashHtmlComponents
using DashBootstrapComponents

app = dash()

app.layout = html_div() do
html_span("Input 1:"),
dcc_input(; id = "input-1", value = "", type = "text"),
html_div(""),
html_span("Input 2:"),
dcc_input(; id = "input-2", value = "", type = "text"),
html_p("Output..."; id = "my-div"),
html_div("..."; id = "output")
end

callback!(
app,
Output("output", "children"),
Input("input-1", "value"),
State("input-2", "value"),
) do ip1, ip2
"""
input-1: $(ip1)...
input-2: $(ip2)
"""
end

function main()
host = get(ENV, "HOST", "0.0.0.0")
port = get(ENV, "PORT", "8080")
return run_server(app, "0.0.0.0", 8080; debug = true)
end

function julia_main()::Cint
try
# @show ARGS
# @show Base.PROGRAM_FILE
# @show DEPOT_PATH
# @show LOAD_PATH
# @show pwd()
# @show Base.active_project()
# @show Threads.nthreads()
# @show Sys.BINDIR
# display(Base.loaded_modules)
main(app)
println()
catch
Base.invokelatest(Base.display_error, Base.catch_stack())
end
return 0
end

end # module
[2021-03-14T13:52:38.672] Success
[2021-03-14T13:52:38.672]

[2021-03-14T13:52:38.672] Formatted:
[2021-03-14T13:52:38.672]
module SaleDSS

using Base.Threads
using Dash
using DashCoreComponents
using DashHtmlComponents
using DashBootstrapComponents

app = dash()

app.layout = html_div() do
html_span("Input 1:"),
dcc_input(; id = "input-1", value = "", type = "text"),
html_div(""),
html_span("Input 2:"),
dcc_input(; id = "input-2", value = "", type = "text"),
html_p("Output..."; id = "my-div"),
html_div("..."; id = "output")
end

callback!(
app,
Output("output", "children"),
Input("input-1", "value"),
State("input-2", "value"),
) do ip1, ip2
"""
input-1: $(ip1)...
input-2: $(ip2)
"""
end

function main()
host = get(ENV, "HOST", "0.0.0.0")
port = get(ENV, "PORT", "8080")
return run_server(app, "0.0.0.0", 8080; debug = true)
end

function julia_main()::Cint
try
# @show ARGS
# @show Base.PROGRAM_FILE
# @show DEPOT_PATH
# @show LOAD_PATH
# @show pwd()
# @show Base.active_project()
# @show Threads.nthreads()
# @show Sys.BINDIR
# display(Base.loaded_modules)
main(app)
println()
catch
Base.invokelatest(Base.display_error, Base.catch_stack())
end
return 0
end

end # module
[2021-03-14T13:52:38.672] Done.
[2021-03-14T13:52:41.375] Connected.
[2021-03-14T13:52:41.375] Setting up defaults ...
[2021-03-14T13:52:41.375] Searching for .JuliaFormatter.toml ...
[2021-03-14T13:52:41.375] No .JuliaFormatter.toml
[2021-03-14T13:52:41.376] Using options: Dict{Symbol, Any}(:indent => 4, :margin => 92, :always_for_in => false, :whitespace_typedefs => false, :whitespace_ops_in_indices => true, :style => DefaultStyle(nothing)) with style: DefaultStyle(nothing)
[2021-03-14T13:52:41.376] Formatting:
[2021-03-14T13:52:41.376]
module SaleDSS

using Base.Threads
using Dash
using DashCoreComponents
using DashHtmlComponents
using DashBootstrapComponents

app = dash()

app.layout = html_div() do
html_span("Input 1:"),
dcc_input(; id = "input-1", value = "", type = "text"),
html_div(""),
html_span("Input 2:"),
dcc_input(; id = "input-2", value = "", type = "text"),
html_p("Output..."; id = "my-div"),
html_div("..."; id = "output")
end

callback!(
app,
Output("output", "children"),
Input("input-1", "value"),
State("input-2", "value"),
) do ip1, ip2
"""
input-1: $(ip1)...
input-2: $(ip2)
"""
end

function main()
host = get(ENV, "HOST", "0.0.0.0")
port = get(ENV, "PORT", "8080")
return run_server(app, "0.0.0.0", 8080; debug = true)
end

function julia_main()::Cint
try
# @show ARGS
# @show Base.PROGRAM_FILE
# @show DEPOT_PATH
# @show LOAD_PATH
# @show pwd()
# @show Base.active_project()
# @show Threads.nthreads()
# @show Sys.BINDIR
# display(Base.loaded_modules)
main(app)
println()
catch
Base.invokelatest(Base.display_error, Base.catch_stack())
end
return 0
end

end # module
[2021-03-14T13:52:41.377] Success
[2021-03-14T13:52:41.377]

[2021-03-14T13:52:41.377] Formatted:
[2021-03-14T13:52:41.377]
module SaleDSS

using Base.Threads
using Dash
using DashCoreComponents
using DashHtmlComponents
using DashBootstrapComponents

app = dash()

app.layout = html_div() do
html_span("Input 1:"),
dcc_input(; id = "input-1", value = "", type = "text"),
html_div(""),
html_span("Input 2:"),
dcc_input(; id = "input-2", value = "", type = "text"),
html_p("Output..."; id = "my-div"),
html_div("..."; id = "output")
end

callback!(
app,
Output("output", "children"),
Input("input-1", "value"),
State("input-2", "value"),
) do ip1, ip2
"""
input-1: $(ip1)...
input-2: $(ip2)
"""
end

function main()
host = get(ENV, "HOST", "0.0.0.0")
port = get(ENV, "PORT", "8080")
return run_server(app, "0.0.0.0", 8080; debug = true)
end

function julia_main()::Cint
try
# @show ARGS
# @show Base.PROGRAM_FILE
# @show DEPOT_PATH
# @show LOAD_PATH
# @show pwd()
# @show Base.active_project()
# @show Threads.nthreads()
# @show Sys.BINDIR
# display(Base.loaded_modules)
main(app)
println()
catch
Base.invokelatest(Base.display_error, Base.catch_stack())
end
return 0
end

end # module
[2021-03-14T13:52:41.377] Done.
[2021-03-14T13:53:11.392] Connected.
[2021-03-14T13:53:11.392] Setting up defaults ...
[2021-03-14T13:53:11.392] Searching for .JuliaFormatter.toml ...
[2021-03-14T13:53:11.392] No .JuliaFormatter.toml
[2021-03-14T13:53:11.393] Using options: Dict{Symbol, Any}(:indent => 4, :margin => 92, :always_for_in => false, :whitespace_typedefs => false, :whitespace_ops_in_indices => true, :style => DefaultStyle(nothing)) with style: DefaultStyle(nothing)
[2021-03-14T13:53:11.393] Formatting:
[2021-03-14T13:53:11.393]
module SaleDSS

using Base.Threads
using Dash
using DashCoreComponents
using DashHtmlComponents
using DashBootstrapComponents

app = dash()

app.layout = html_div() do
html_span("Input 1:"),
dcc_input(; id = "input-1", value = "", type = "text"),
html_div(""),
html_span("Input 2:"),
dcc_input(; id = "input-2", value = "", type = "text"),
html_p("Output..."; id = "my-div"),
html_div("..."; id = "output")
end

callback!(
app,
Output("output", "children"),
Input("input-1", "value"),
State("input-2", "value"),
) do ip1, ip2
"""
input-1: $(ip1)...
input-2: $(ip2)
"""
end

function main()
host = get(ENV, "HOST", "0.0.0.0")
port = get(ENV, "PORT", "8080")
return run_server(app, "0.0.0.0", 8080; debug = true)
end

function julia_main()::Cint
try
# @show ARGS
# @show Base.PROGRAM_FILE
# @show DEPOT_PATH
# @show LOAD_PATH
# @show pwd()
# @show Base.active_project()
# @show Threads.nthreads()
# @show Sys.BINDIR
# display(Base.loaded_modules)
main(app)
println()
catch
Base.invokelatest(Base.display_error, Base.catch_stack())
end
return 0
end

end # module
[2021-03-14T13:53:11.393] Success
[2021-03-14T13:53:11.393]

[2021-03-14T13:53:11.394] Formatted:
[2021-03-14T13:53:11.394]
module SaleDSS

using Base.Threads
using Dash
using DashCoreComponents
using DashHtmlComponents
using DashBootstrapComponents

app = dash()

app.layout = html_div() do
html_span("Input 1:"),
dcc_input(; id = "input-1", value = "", type = "text"),
html_div(""),
html_span("Input 2:"),
dcc_input(; id = "input-2", value = "", type = "text"),
html_p("Output..."; id = "my-div"),
html_div("..."; id = "output")
end

callback!(
app,
Output("output", "children"),
Input("input-1", "value"),
State("input-2", "value"),
) do ip1, ip2
"""
input-1: $(ip1)...
input-2: $(ip2)
"""
end

function main()
host = get(ENV, "HOST", "0.0.0.0")
port = get(ENV, "PORT", "8080")
return run_server(app, "0.0.0.0", 8080; debug = true)
end

function julia_main()::Cint
try
# @show ARGS
# @show Base.PROGRAM_FILE
# @show DEPOT_PATH
# @show LOAD_PATH
# @show pwd()
# @show Base.active_project()
# @show Threads.nthreads()
# @show Sys.BINDIR
# display(Base.loaded_modules)
main(app)
println()
catch
Base.invokelatest(Base.display_error, Base.catch_stack())
end
return 0
end

end # module
[2021-03-14T13:53:11.394] Done.

</details>

Play nicely with changing Julia versions in the $PATH

I find myself switching between Julia versions a lot for different project. Since I am using a system-image for Julia formatter, this causes the formatter to crash if the image was compiled for another version. It would be nice to either

  • Be able to tell JuliaFormatter.vim which exact julia binary to use
  • Or allow to create multiple system images, name them by julia version, and load the correct one based on the current julia version.

Dangerous behaviour when editing multiple files.

Hello, I would like to report a dangerous non-isolation of buffers when using JuliaFormatter. To reproduce, create the following two files on disk:
julia_file.jl

f=  function(some,poorly,
 formatted,  code) return 5; end

unrelated_file.txt

unrelated content

Then

  1. Open code with vim julia_file.jl.
  2. Consider the code is not nice, run :JuliaFormatterFormat.
  3. It's taking a while the first time, take this opportunity to :edit unrelated_file.txt.
  4. Wait a minute for the magic to happen.

JuliaFormatter formats the wrong buffer, and immediately saves the result on disk. At the end of the game:

julia_file.jl (unchanged)

f=  function(some,poorly,
 formatted,  code) return 5; end

unrelated_file.txt (corrupted)

f = function (some, poorly, formatted, code)
    return 5
end

The sad story is that I've just lost my entire .vimrc to this cr..corruption problem. It would've been.. preferable if this did not happen X(

Considering the formatting delay, can JuliaFormatter be careful not to naively edit the current buffer, but the one from which the formatting command was originally issued?


  • vim --version
NVIM v0.6.0
Build type: Release
LuaJIT 2.0.5
Compiled by builduser

Features: +acl +iconv +tui
See ":help feature-compile"

   system vimrc file: "$VIM/sysinit.vim"
  fall-back for $VIM: "/usr/share/nvim"

Run :checkhealth for more info
  • julia --project=/path/to/JuliaFormatter.vim/ -e "using Pkg; Pkg.status()"
      Status `/opt/vim.plugged/JuliaFormatter.vim/Project.toml`
  [682c06a0] JSON v0.21.2
  [98e50ef6] JuliaFormatter v0.15.11
  [9b87118b] PackageCompiler v1.4.0
  • julia --project=/path/to/JuliaFormatter.vim/ -e "using InteractiveUtils; versioninfo()"
Julia Version 1.7.0
Commit 3bf9d17731* (2021-11-30 12:12 UTC)
Platform Info:
  OS: Linux (x86_64-pc-linux-gnu)
  CPU: Intel(R) Core(TM) i7-6700HQ CPU @ 2.60GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-13.0.0 (ORCJIT, skylake)

:JuliaFormatterLog

[2021-12-17T10:11:35.544] calling main ...
[2021-12-17T10:11:40.448] Connected.
[2021-12-17T10:11:40.460] Setting up defaults ...
[2021-12-17T10:11:40.469] Searching for .JuliaFormatter.toml ...
[2021-12-17T10:11:40.469] No .JuliaFormatter.toml
[2021-12-17T10:11:40.535] Using options: Dict{Symbol, Any}(:indent => 4, :margin => 92, :always_for_in => false, :whitespace_typedefs => false, :whitespace_ops_in_indices => true, :style => DefaultStyle(nothing)) with style: DefaultStyle(nothing)
[2021-12-17T10:11:40.541] Formatting: 
[2021-12-17T10:11:40.553]

f=  function(some,poorly,
 formatted,  code) return 5; end

[2021-12-17T10:11:42.804] Success
[2021-12-17T10:11:42.804] 
---------------------------------------------------------------------

[2021-12-17T10:11:42.804] Formatted: 
[2021-12-17T10:11:42.804]

f = function (some, poorly, formatted, code)
    return 5
end

[2021-12-17T10:11:43.070] Done.

:JuliaFormatterEchoCmd

[JuliaFormatter] julia --startup-file=no --color=no --project=/opt/vim.plugged/JuliaFormatter.v
im /opt/vim.plugged/JuliaFormatter.vim/scripts/server.jl

E910: Using a Job as a Number

Vim Version:

$ vim --version
VIM - Vi IMproved 8.2 (2019 Dec 12, compiled May  8 2021 05:44:12)
macOS version
Included patches: 1-2029
Compiled by [email protected]

Formatter Status:

$ julia --project=/path/to/juliaformatter -e "using Pkg; Pkg.status()"
      Status `/path/to/juliaformatter/Project.toml`
  [682c06a0] JSON v0.21.1
  [98e50ef6] JuliaFormatter v0.15.0
  [9b87118b] PackageCompiler v1.2.6

Versioninfo:

Julia Version 1.6.1
Commit 6aaedecc44 (2021-04-23 05:59 UTC)
Platform Info:
  OS: macOS (x86_64-apple-darwin18.7.0)
  CPU: Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-11.0.1 (ORCJIT, skylake)

When I exit vim, sometimes I see a very fast error before it closes. So I ran vim with vim -V9myVim.log file.jl. When I exit, I checked the log and I see this error right at the end:

Executing VimLeavePre Autocommands for "*"
autocommand call JuliaFormatter#Kill()

Error detected while processing VimLeavePre Autocommands for "*"..function JuliaFormatter#Kill:
line    7:
E910: Using a Job as a Number
Writing viminfo file "/Users/fchorney/.viminfo"
Executing VimLeave Autocommands for "*"
autocommand for s:jobbuf in keys(s:edit_jobs) |   call writefile([], s:edit_jobs[s:jobbuf][0].temp . '.exit') |   redraw! |   call call('s:RunWait', remove(s:edit_jobs, s:jobbuf)) | endfor

I found another git issue which may be relevant? mhinz/vim-signify#222

Buffer doesn't get updated

When calling :call JuliaFormatter#Format(0) I don't see any change in vim. However, cat juliaformatter.log looks fine.

[2020-03-13T21:45:00.877] calling main ...
[2020-03-13T21:45:01.964] Formatting: 
[2020-03-13T21:45:01.975]
using   Pkg

# Load in `deps.jl`, complaining if it does not exist
const depsjl_path = joinpath( @__DIR__, "..","deps","deps.jl")

if !isfile(depsjl_path)
error(
      "Package not installed properly, run Pkg.build(\"Package\"), restart Julia and try again",
     )
end
include(depsjl_path)

# Module initialization function
function __init__()
# Always check your dependencies from `deps.jl`
check_deps(   )
end


include(joinpath("..", "deps", "build.jl"))

const MaybeFloat64 = Union{Float64, Nothing }

    function foo(
        x ::Union{Nothing,Vector{UInt}} = nothing,
        y:: Union{Nothing,UInt64} = nothing;
        z :: Bool = true,
        a::AbstractString="John Doe",
        b::Integer= 12345,
        c::AbstractString ="XYZ\n\nABC",
    )

        for i in 1:b

            println( x[i] )
        end

    end
[2020-03-13T21:45:05.625] 
---------------------------------------------------------------------

[2020-03-13T21:45:05.625]
using Pkg

# Load in `deps.jl`, complaining if it does not exist
const depsjl_path = joinpath(@__DIR__, "..", "deps", "deps.jl")

if !isfile(depsjl_path)
    error("Package not installed properly, run Pkg.build(\"Package\"), restart Julia and try again",)
end
include(depsjl_path)

# Module initialization function
function __init__()
    # Always check your dependencies from `deps.jl`
    check_deps()
end


include(joinpath("..", "deps", "build.jl"))

const MaybeFloat64 = Union{Float64,Nothing}

function foo(
    x::Union{Nothing,Vector{UInt}} = nothing,
    y::Union{Nothing,UInt64} = nothing;
    z::Bool = true,
    a::AbstractString = "John Doe",
    b::Integer = 12345,
    c::AbstractString = "XYZ\n\nABC",
)

    for i = 1:b
        println(x[i])
    end

end
[2020-03-13T21:45:05.856] Done.

Troubleshooting

  • vim --version
VIM - Vi IMproved 8.2 (2019 Dec 12, compiled Mar  1 2020 17:21:03)
Included patches: 1-343
Compiled by Arch Linux
Huge version with GTK3 GUI.  Features included (+) or not (-):
+acl               -farsi             -mouse_sysmouse    -tag_old_static
+arabic            +file_in_path      +mouse_urxvt       -tag_any_white
+autocmd           +find_in_path      +mouse_xterm       +tcl/dyn
+autochdir         +float             +multi_byte        +termguicolors
-autoservername    +folding           +multi_lang        +terminal
+balloon_eval      -footer            -mzscheme          +terminfo
+balloon_eval_term +fork()            +netbeans_intg     +termresponse
+browse            +gettext           +num64             +textobjects
++builtin_terms    -hangul_input      +packages          +textprop
+byte_offset       +iconv             +path_extra        +timers
+channel           +insert_expand     +perl/dyn          +title
+cindent           +job               +persistent_undo   +toolbar
+clientserver      +jumplist          +popupwin          +user_commands
+clipboard         +keymap            +postscript        +vartabs
+cmdline_compl     +lambda            +printer           +vertsplit
+cmdline_hist      +langmap           +profile           +virtualedit
+cmdline_info      +libcall           +python/dyn        +visual
+comments          +linebreak         +python3/dyn       +visualextra
+conceal           +lispindent        +quickfix          +viminfo
+cryptv            +listcmds          +reltime           +vreplace
+cscope            +localmap          +rightleft         +wildignore
+cursorbind        +lua/dyn           +ruby/dyn          +wildmenu
+cursorshape       +menu              +scrollbind        +windows
+dialog_con_gui    +mksession         +signs             +writebackup
+diff              +modify_fname      +smartindent       +X11
+digraphs          +mouse             +sound             -xfontset
+dnd               +mouseshape        +spell             +xim
-ebcdic            +mouse_dec         +startuptime       -xpm
+emacs_tags        +mouse_gpm         +statusline        +xsmp_interact
+eval              -mouse_jsbterm     -sun_workshop      +xterm_clipboard
+ex_extra          +mouse_netterm     +syntax            -xterm_save
+extra_search      +mouse_sgr         +tag_binary        
   system vimrc file: "/etc/vimrc"
     user vimrc file: "$HOME/.vimrc"
 2nd user vimrc file: "~/.vim/vimrc"
      user exrc file: "$HOME/.exrc"
  system gvimrc file: "/etc/gvimrc"
    user gvimrc file: "$HOME/.gvimrc"
2nd user gvimrc file: "~/.vim/gvimrc"
       defaults file: "$VIMRUNTIME/defaults.vim"
    system menu file: "$VIMRUNTIME/menu.vim"
  fall-back for $VIM: "/usr/share/vim"
Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H -DFEAT_GUI_GTK  -I/usr/include/gtk-3.0 -I/usr/include/pango-1.0 -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -I/usr/lib/libffi-3.2.1/include -I/usr/include/harfbuzz -I/usr/include/fribidi -I/usr/include/freetype2 -I/usr/include/libpng16 -I/usr/include/cairo -I/usr/include/pixman-1 -I/usr/include/gdk-pixbuf-2.0 -I/usr/include/libmount -I/usr/include/blkid -I/usr/include/gio-unix-2.0 -I/usr/include/atk-1.0 -I/usr/include/at-spi2-atk/2.0 -I/usr/include/dbus-1.0 -I/usr/lib/dbus-1.0/include -I/usr/include/at-spi-2.0 -pthread    -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -D_REENTRANT  -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1       
Linking: gcc   -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,-E -Wl,-rpath,/usr/lib/perl5/5.30/core_perl/CORE  -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -L/usr/local/lib -Wl,--as-needed -o vim   -lgtk-3 -lgdk-3 -lz -lpangocairo-1.0 -lpango-1.0 -lharfbuzz -latk-1.0 -lcairo-gobject -lcairo -lgdk_pixbuf-2.0 -lgio-2.0 -lgobject-2.0 -lglib-2.0  -lSM -lICE -lXt -lX11 -lXdmcp -lSM -lICE  -lm -ltinfo -lelf -lnsl    -lcanberra  -lacl -lattr -lgpm -ldl   -Wl,-E -Wl,-rpath,/usr/lib/perl5/5.30/core_perl/CORE -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -L/usr/local/lib  -L/usr/lib/perl5/5.30/core_perl/CORE -lperl -lpthread -ldl -lm -lcrypt -lutil -lc   -L/usr/lib -ltclstub8.6 -ldl -lz -lpthread -lm  
  • julia --project=/path/to/.local/share/nvim/plugged/JuliaFormatter.vim/ -e "using JuliaFormatter; versioninfo()"
Julia Version 1.3.1
  • Can you reproduce the output using MINRC?
    Yes.

packagecompiler script not working

$ julia
julia> versioninfo()
Julia Version 1.6.1
Commit 6aaedecc44 (2021-04-23 05:59 UTC)
Platform Info:
  OS: Linux (x86_64-pc-linux-gnu)
  CPU: Intel(R) Core(TM) i7-6700HQ CPU @ 2.60GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-11.0.1 (ORCJIT, skylake)
$ julia --project scripts/packagecompiler.jl
ERROR: LoadError: LoadError: Cannot locate artifact 'x86_64-w64-mingw32' for x86_64-linux-gnu-libgfortran4-cxx11-libstdcxx26-julia_version+1.6.1 in '/home/blegat/.julia/packages/PackageCompiler/vsMJE/Artifacts.toml'
Stacktrace:
  [1] error(s::String)
    @ Base ./error.jl:33
  [2] artifact_slash_lookup(name::String, artifact_dict::Dict{String, Any}, artifacts_toml::String, platform::Base.BinaryPlatforms.Platform)
    @ Artifacts /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.6/Artifacts/src/Artifacts.jl:608
  [3] var"@artifact_str"(__source__::LineNumberNode, __module__::Module, name::Any, platform::Nothing)
    @ Artifacts /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.6/Artifacts/src/Artifacts.jl:678
  [4] var"@artifact_str"(__source__::LineNumberNode, __module__::Module, name::Any)
    @ Artifacts /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.6/Artifacts/src/Artifacts.jl:641
  [5] include
    @ ./Base.jl:386 [inlined]
  [6] include_package_for_output(pkg::Base.PkgId, input::String, depot_path::Vector{String}, dl_load_path::Vector{String}, load_path::Vector{String}, concrete_deps::Vector{Pair{Base.PkgId, UInt64}}, source::String)
    @ Base ./loading.jl:1213
  [7] top-level scope
    @ none:1
  [8] eval
    @ ./boot.jl:360 [inlined]
  [9] eval(x::Expr)
    @ Base.MainInclude ./client.jl:446
 [10] top-level scope
    @ none:1
in expression starting at /home/blegat/.julia/packages/PackageCompiler/vsMJE/src/PackageCompiler.jl:103
in expression starting at /home/blegat/.julia/packages/PackageCompiler/vsMJE/src/PackageCompiler.jl:1
ERROR: LoadError: Failed to precompile PackageCompiler [9b87118b-4619-50d2-8e1e-99f35a4d4d9d] to /home/blegat/.julia/compiled/v1.6/PackageCompiler/jl_pqtqM6.
Stacktrace:
 [1] error(s::String)
   @ Base ./error.jl:33
 [2] compilecache(pkg::Base.PkgId, path::String, internal_stderr::Base.TTY, internal_stdout::Base.TTY)
   @ Base ./loading.jl:1360
 [3] compilecache(pkg::Base.PkgId, path::String)
   @ Base ./loading.jl:1306
 [4] _require(pkg::Base.PkgId)
   @ Base ./loading.jl:1021
 [5] require(uuidkey::Base.PkgId)
   @ Base ./loading.jl:914
 [6] require(into::Module, mod::Symbol)
   @ Base ./loading.jl:901
in expression starting at /home/blegat/.config/nvim/plugged/JuliaFormatter.vim/scripts/packagecompiler.jl:1

Error in formatting Julia stdlib files

julia> format("./stdlib/", MinimalStyle(); normalize_line_endings = "unix", align_assignment=true)
[ Info: Error in formatting file stdlib/InteractiveUtils/test/runtests.jl
ERROR: ArgumentError: invalid index: nothing of type Nothing

String interpolation error

Sorry, I had added an error in the last commit. Could you replace this in the catch clause in server.jl?

    project_path = joinpath(@__DIR__, "..")
    log("Cannot Instantiate the project! Install dependencies by yourself: `julia --project=$project_path -e 'using Pkg; Pkg.add(\"JuliaFormatter\"); Pkg.add(\"JSON\")'`")
    exit(1)

No version of PackageCompiler meets requirements

(Caveat: I'm new to Julia.)

I installed JuliaFormatter.vim, but it wasn't doing anything. After some poking around, I found the log, which says,

[2023-04-03T10:16:35.764] Cannot Instantiate the project! Install dependencies by yourself: `julia --project=/home/john/config/vim/bundle/JuliaFormatter.vim/ -e 'using Pkg; Pkg.add("JuliaFormatter"); Pkg.add("JSON")'`

So I tried that, but I get this error:

john:JuliaFormatter.vim/ (main) $ julia --project=/home/john/config/vim/bundle/JuliaFormatter.vim/ -e 'using Pkg; Pkg.add("JuliaFormatter"); Pkg.add("JSON")'
   Updating registry at `~/.julia/registries/General`
ERROR: LoadError: Unsatisfiable requirements detected for package PackageCompiler [9b87118b]:
 PackageCompiler [9b87118b] log:
 ├─possible versions are: [0.5.0-0.5.1, 0.6.0-0.6.5, 1.0.0-1.0.2, 1.1.0-1.1.1, 1.2.0-1.2.8, 1.3.0, 1.4.0-1.4.1, 1.5.0, 1.6.0, 1.7.0-1.7.7, 2.0.0-2.0.11, 2.1.0-2.1.5] or uninstalled
 ├─restricted to versions 2 by an explicit requirement, leaving only versions [2.0.0-2.0.11, 2.1.0-2.1.5]
 └─restricted by julia compatibility requirements to versions: [0.5.0-0.5.1, 0.6.0-0.6.5, 1.0.0-1.0.2, 1.1.0-1.1.1, 1.2.0-1.2.8, 1.3.0, 1.4.0-1.4.1] or uninstalled — no versions left
...

I'm on Ubuntu 20.04, with Julia 1.4.1 installed, and neovim 0.8.3.

Problem parsing files with UTF-8 characters

Troubleshooting

Every time I try to format a file that has UTF-8 characters, I get an error. For example, if I try to parse this file:

https://raw.githubusercontent.com/ronisbr/PrettyTables.jl/master/src/backends/text/print_aux.jl

I get this:

[2021-05-29T18:56:19.760] calling main ...
[2021-05-29T18:56:21.233] Connected.
[2021-05-29T18:56:21.994] Unable to parse json: "{"method": "format", "params": {"options": {"whitespace_in_kwargs": true, "style": "blue"}, "filepath": "/Users/ronan.arraes/tmp/print_aux.jl", "text": ["# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #", "#", "# Description", "# ==============================================================================", "#", "#   Auxiliary functions to print the parts of the table.", "#", "# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #", "", "# Flush the content of `buf` to `io`.", "function _flush_buffer!(io::IO,", "                        buf::IO,", "                        overwrite::Bool,", "                        newline_at_end::Bool,", "                        num_displayed_rows::Int)", "", "    # If `overwrite` is `true`, then delete the exact number of lines of the", "    # table. This can be used to replace the table in the display continuously.", "    str_overwrite = overwrite ? \"\\e[1F\\e[2K\"^(num_displayed_rows - 1) : \"\"", "", "    output_str = String(take!(buf))", "", "    # Check if the user does not want a newline at end.", "    !newline_at_end && (output_str = String(chomp(output_str)))", "", "    print(io, str_overwrite * output_str)", "", "    return nothing", "end", "", "function _print_omitted_cell_summary(buf::IO,", "                                     has_color::Bool,", "                                     num_omitted_cols::Int,", "                                     num_omitted_rows::Int,", "                                     omitted_cell_summary_crayon::Crayon,", "                                     show_omitted_cell_summary::Bool,", "                                     table_width::Int)", "", "    if show_omitted_cell_summary && ((num_omitted_cols + num_omitted_rows) > 0)", "        cs_str_col = \"\"", "        cs_str_and = \"\"", "        cs_str_row = \"\"", "", "        if num_omitted_cols > 0", "            cs_str_col = string(num_omitted_cols)", "            cs_str_col *= num_omitted_cols > 1 ? \" columns\" : \" column\"", "        end", "", "        if num_omitted_rows > 0", "            cs_str_row = string(num_omitted_rows)", "            cs_str_row *= num_omitted_rows > 1 ? \" rows\" : \" row\"", "", "            num_omitted_cols > 0 && (cs_str_and = \" and \")", "        end", "", "        cs_str = cs_str_col * cs_str_and * cs_str_row * \" omitted\"", "", "        textwidth(cs_str) < table_width &&", "            (cs_str = _str_aligned(cs_str, :r, table_width))", "", "        has_color && print(buf, omitted_cell_summary_crayon)", "        print(buf, cs_str)", "        has_color && print(buf, _reset_crayon)", "        println(buf)", "    end", "end", "", "# Print the table header without the horizontal lines.", "function _print_table_header!(buf::IO,", "                              display::Display,", "                              (@nospecialize header::Any),", "                              header_str::Matrix{String},", "                              id_cols::Vector{Int},", "                              id_rows::Vector{Int},", "                              num_printed_cols::Int,", "                              Δc::Int,", "                              cols_width::Vector{Int},", "                              vlines::Vector{Int},", "                              # Configurations.", "                              alignment::Vector{Symbol},", "                              header_alignment::Vector{Symbol},", "                              (@nospecialize header_cell_alignment::Ref{Any}),", "                              show_row_names::Bool,", "                              show_row_number::Bool,", "                              tf::TextFormat,", "                              # Crayons.", "                              border_crayon::Crayon,", "                              header_crayon::Vector{Crayon},", "                              subheader_crayon::Vector{Crayon},", "                              rownum_header_crayon::Crayon,", "                              row_name_header_crayon::Crayon)", "", "    header_num_rows, ~ = size(header_str)", "", "    @inbounds @views for i = 1:header_num_rows", "        0 ∈ vlines && _p!(display, border_crayon, tf.column, false)", "", "        for j = 1:num_printed_cols", "            # Get the information about the alignment and the crayon.", "            if j ≤ Δc", "                if show_row_number && (j == 1)", "                    crayon_ij    = rownum_header_crayon", "                    alignment_ij = alignment[1]", "                elseif show_row_names", "                    crayon_ij    = row_name_header_crayon", "                    alignment_ij = alignment[Δc]", "                end", "            else", "                jc = id_cols[j-Δc]", "                crayon_ij    = (i == 1) ? header_crayon[jc] : subheader_crayon[jc]", "                alignment_ij = header_alignment[jc]", "", "                # Check for cell alignment override.", "                for f in header_cell_alignment.x", "                    aux = f(header, i, jc)", "", "                    if aux ∈ (:l, :c, :r, :L, :C, :R, :s, :S)", "                        alignment_ij = aux", "                        break", "                    end", "                end", "", "                # If alignment is `:s`, then we must use the column", "                # alignment.", "                alignment_ij ∈ (:s,:S) && (alignment_ij = alignment[jc+Δc])", "            end", "", "            # Prepare the text to be printed.", "            header_ij_str = _str_aligned(header_str[i,j],", "                                         alignment_ij,", "                                         cols_width[j])", "            header_ij_str  = \" \" * header_ij_str * \" \"", "", "            flp = j == num_printed_cols", "", "            # Print the text.", "            _p!(display, crayon_ij, header_ij_str, false)", "", "            # Check if we need to draw a vertical line here.", "            _pc!(j ∈ vlines, display, border_crayon, tf.column, \"\", flp, 1, 0)", "", "            _eol(display) && break", "        end", "", "        i != header_num_rows && _nl!(display, buf)", "    end", "", "    _nl!(display, buf)", "end", "", "# Print the entire table data.", "function _print_table_data(buf::IO,", "                           display::Display,", "                           (@nospecialize data::Any),", "                           data_str::Matrix{Vector{String}},", "                           id_cols::Vector{Int},", "                           id_rows::Vector{Int},", "                           Δc::Int,", "                           cols_width::Vector{Int},", "                           vlines::Vector{Int},", "                           row_printing_recipe::Vector{NTuple{4, Int}},", "                           col_printing_recipe::Vector{Int},", "                           # Configurations.", "                           alignment::Vector{Symbol},", "                           body_hlines_format::NTuple{4, Char},", "                           cell_alignment_override::Dict{Tuple{Int, Int}, Symbol},", "                           continuation_row_alignment::Symbol,", "                           ellipsis_line_skip::Integer,", "                           (@nospecialize highlighters::Ref{Any}),", "                           noheader::Bool,", "                           show_row_names::Bool,", "                           show_row_number::Bool,", "                           tf::TextFormat,", "                           # Crayons.", "                           border_crayon::Crayon,", "                           row_name_crayon::Crayon,", "                           text_crayon::Crayon)", "", "    line_count = 0", "", "    for r in row_printing_recipe", "        if r[1] < 0", "            if r[1] == _ROW_LINE[1]", "                _draw_line!(display, buf, body_hlines_format..., border_crayon,", "                            cols_width, vlines)", "            elseif r[1] == _CONTINUATION_LINE[1]", "                _draw_continuation_row(display, buf, tf, text_crayon,", "                                      ". Unexpected end of input
Line: 0
Around: ...         ...
                    ^

Stacktrace:
  [1] error(s::String)
    @ Base ./error.jl:33
  [2] _error(message::String, ps::JSON.Parser.MemoryParserState)
    @ JSON.Parser ~/.julia/packages/JSON/3rsiS/src/Parser.jl:140
  [3] predict_string(ps::JSON.Parser.MemoryParserState)
    @ JSON.Parser ~/.julia/packages/JSON/3rsiS/src/specialized.jl:77
  [4] parse_string(ps::JSON.Parser.MemoryParserState)
    @ JSON.Parser ~/.julia/packages/JSON/3rsiS/src/specialized.jl:9
  [5] parse_value(pc::JSON.Parser.ParserContext{Dict{String, Any}, Int64, true, nothing}, ps::JSON.Parser.MemoryParserState)
    @ JSON.Parser ~/.julia/packages/JSON/3rsiS/src/Parser.jl:162
  [6] parse_array(pc::JSON.Parser.ParserContext{Dict{String, Any}, Int64, true, nothing}, ps::JSON.Parser.MemoryParserState)
    @ JSON.Parser ~/.julia/packages/JSON/3rsiS/src/Parser.jl:203
  [7] parse_value(pc::JSON.Parser.ParserContext{Dict{String, Any}, Int64, true, nothing}, ps::JSON.Parser.MemoryParserState)
    @ JSON.Parser ~/.julia/packages/JSON/3rsiS/src/Parser.jl:168
  [8] parse_object(pc::JSON.Parser.ParserContext{Dict{String, Any}, Int64, true, nothing}, ps::JSON.Parser.MemoryParserState)
    @ JSON.Parser ~/.julia/packages/JSON/3rsiS/src/Parser.jl:230
  [9] parse_value(pc::JSON.Parser.ParserContext{Dict{String, Any}, Int64, true, nothing}, ps::JSON.Parser.MemoryParserState)
    @ JSON.Parser ~/.julia/packages/JSON/3rsiS/src/Parser.jl:166
 [10] parse_object(pc::JSON.Parser.ParserContext{Dict{String, Any}, Int64, true, nothing}, ps::JSON.Parser.MemoryParserState)
    @ JSON.Parser ~/.julia/packages/JSON/3rsiS/src/Parser.jl:230
 [11] parse_value(pc::JSON.Parser.ParserContext{Dict{String, Any}, Int64, true, nothing}, ps::JSON.Parser.MemoryParserState)
    @ JSON.Parser ~/.julia/packages/JSON/3rsiS/src/Parser.jl:166
 [12] parse(str::String; dicttype::Type, inttype::Type{Int64}, allownan::Bool, null::Nothing)
    @ JSON.Parser ~/.julia/packages/JSON/3rsiS/src/Parser.jl:460
 [13] parse(str::String)
    @ JSON.Parser ~/.julia/packages/JSON/3rsiS/src/Parser.jl:458
 [14] main()
    @ Main ~/.local/share/nvim/site/pack/packer/opt/JuliaFormatter.vim/scripts/server.jl:45
 [15] top-level scope
    @ ~/.local/share/nvim/site/pack/packer/opt/JuliaFormatter.vim/scripts/server.jl:125
 [16] include(mod::Module, _path::String)
    @ Base ./Base.jl:386
 [17] exec_options(opts::Base.JLOptions)
    @ Base ./client.jl:285
 [18] _start()
    @ Base ./client.jl:485
[2021-05-29T18:56:21.998] Unable to parse json: " border_crayon, cols_width, vlines,", "                                       continuation_row_alignment)", "            else", "                error(\"Internal error: wrong symbol in row printing recipe.\")", "            end", "", "        else", "            i, ir, num_lines, l₀ = r", "", "            for l = l₀:(l₀+num_lines-1)", "", "                # Check if we should print the ellipsis here.", "                display.cont_char =", "                    line_count % (ellipsis_line_skip + 1) == 0 ? '⋯' : ' '", "                line_count += 1", "", "                num_col_recipes = length(col_printing_recipe)", "", "                for c_id = 1:num_col_recipes", "                    c = col_printing_recipe[c_id]", "", "                    flp = c_id == num_col_recipes", "", "                    if c < 0", "                        if c == _LEFT_LINE", "                            _p!(display, border_crayon, tf.column, flp, 1)", "                        elseif c == _COLUMN_LINE", "                            _p!(display, border_crayon, tf.column, flp, 1)", "                        elseif c == _RIGHT_LINE", "                            _p!(display, border_crayon, tf.column, flp, 1)", "                        else", "                            error(\"Internal error: wrong symbol in column printing recipe.\")", "                        end", "                    else", "                        j = c", "", "                        # Get the information about the alignment and the", "                        # crayon.", "                        #", "                        # NOTE: The variable `data_cell` is used to avoid", "                        # applying formatters and highlighters to the row number", "                        # and row name columns.", "                        if j ≤ Δc", "                            if show_row_number && (j == 1)", "                                crayon_ij    = text_crayon", "                                alignment_ij = alignment[1]", "                            elseif show_row_names", "                                crayon_ij    = row_name_crayon", "                                alignment_ij = alignment[Δc]", "                            end", "                            jc = 0", "                            data_cell = false", "                        else", "                            jc = id_cols[j-Δc]", "                            crayon_ij    = text_crayon", "                            alignment_ij = alignment[jc+Δc]", "                            data_cell    = true", "                        end", "", "                        # String to be processed.", "                        if length(data_str[i,j]) >= l", "                            data_ij_str = data_str[i,j][l]", "                        else", "                            data_ij_str = \"\"", "                        end", "", "                        # Check if the alignment of this cell is overridden by", "                        # the user.", "                        if haskey(cell_alignment_override, (ir, jc))", "                            alignment_ij = cell_alignment_override[(ir, jc)]", "                        end", "", "                        # Process the string with the correct alignment and also", "                        # apply the highlighters.", "                        data_ij_str, crayon_ij =", "                            _process_cell_text(data,", "                                               ir,", "                                               jc,", "                                               data_cell,", "                                               data_ij_str,", "                                               cols_width[j],", "                                               crayon_ij,", "                                               alignment_ij,", "                                               highlighters)", "", "                        # Compute the printable size of the string.", "                        data_ij_len = _printable_textwidth(data_ij_str)", "", "                        _p!(display, crayon_ij, data_ij_str, false, data_ij_len)", "                    end", "                end", "                _nl!(display, buf)", "            end", "        end", "    end", "end"]}}". Unexpected character
Line: 0
Around: ... border_crayon, cols_wi...
             ^

Stacktrace:
  [1] error(s::String)
    @ Base ./error.jl:33
  [2] _error(message::String, ps::JSON.Parser.MemoryParserState)
    @ JSON.Parser ~/.julia/packages/JSON/3rsiS/src/Parser.jl:140
  [3] parse_jsconstant(#unused#::JSON.Parser.ParserContext{Dict{String, Any}, Int64, true, nothing}, ps::JSON.Parser.MemoryParserState)
    @ JSON.Parser ~/.julia/packages/JSON/3rsiS/src/Parser.jl:193
  [4] parse_value(pc::JSON.Parser.ParserContext{Dict{String, Any}, Int64, true, nothing}, ps::JSON.Parser.MemoryParserState)
    @ JSON.Parser ~/.julia/packages/JSON/3rsiS/src/Parser.jl:170
  [5] parse(str::String; dicttype::Type, inttype::Type{Int64}, allownan::Bool, null::Nothing)
    @ JSON.Parser ~/.julia/packages/JSON/3rsiS/src/Parser.jl:460
  [6] parse(str::String)
    @ JSON.Parser ~/.julia/packages/JSON/3rsiS/src/Parser.jl:458
  [7] main()
    @ Main ~/.local/share/nvim/site/pack/packer/opt/JuliaFormatter.vim/scripts/server.jl:45
  [8] top-level scope
    @ ~/.local/share/nvim/site/pack/packer/opt/JuliaFormatter.vim/scripts/server.jl:125
  [9] include(mod::Module, _path::String)
    @ Base ./Base.jl:386
 [10] exec_options(opts::Base.JLOptions)
    @ Base ./client.jl:285
 [11] _start()
    @ Base ./client.jl:485

It works if I call format_file or format_text in Julia directly.

  • vim --version

NVIM v0.5.0-dev+b227cedf8

  • julia --project=/path/to/JuliaFormatter.vim/ -e "using Pkg; Pkg.status()"
      Status `~/.local/share/nvim/site/pack/packer/opt/JuliaFormatter.vim/Project.toml`
  [682c06a0] JSON v0.21.1
  [98e50ef6] JuliaFormatter v0.14.4
  [9b87118b] PackageCompiler v1.2.5
  • julia --project=/path/to/JuliaFormatter.vim/ -e "using JuliaFormatter; versioninfo()"

Julia 1.6.1

  • Can you reproduce the output using MINRC?

Yes.

  • Post relevant section from log file below:

Add command (or instructions) on how to update

With #40 the user now has to update the dependencies manually from time to time (it does not happen through Pkg.instantiate anymore). This should probably be documented. Or do we want a command like JuliaFormatterUpdate to run the updates from within vim?

Use compat bounds instead of Manifest.toml

I would like to suggest to remove the Manifest.toml from this repository and add compat bounds to the Project.toml instead. The use of a fixed Manifest.toml causes instantiation to fail if the users Julia version differs (in minor version) from the version that created the manifest.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.