From 3e76ead2077ec866761bf243dd8750f4dc69f945 Mon Sep 17 00:00:00 2001 From: Christian Höltje Date: Fri, 13 Apr 2018 00:22:37 -0400 Subject: Start using prettier default arguments This is one approach for handling default prettier arguments. It is a little verbose, but I think ejecting the flags that don't have to be set by the editor (in favor of .prettierrc files) is a win. --- autoload/prettier.vim | 91 ++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 68 insertions(+), 23 deletions(-) (limited to 'autoload/prettier.vim') diff --git a/autoload/prettier.vim b/autoload/prettier.vim index 4b5a4e9..7cf9cca 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -287,36 +287,81 @@ function! s:Apply_Prettier_Format(lines, startSelection, endSelection) abort call winrestview(l:winview) endfunction +" Returns either '--use-tabs' or an empty string. +function! s:Flag_use_tabs(config) abort + let l:value = get(a:config, 'useTabs', g:prettier#config#use_tabs) + if (l:value ==# 'auto') + let l:value = &expandtab ? 'false' : 'true' + endif + + if ( l:value ==# 'true' ) + return '--use-tabs' + else + return '' + endif +endfunction + +" Backwards compatable version of shiftwidth() +function! s:sw() abort + if exists('*shiftwidth') + return shiftwidth() + else + return &shiftwidth + endif +endfunction + +" Returns '--tab-width=NN' +function! s:Flag_tab_width(config) abort + let l:value = get(a:config, 'tabWidth', g:prettier#config#tab_width) + + if (l:value ==# 'auto') + let l:value = s:sw() + endif + + return '--tab-width=' . l:value +endfunction + +" Returns '--print-width=NN' or '' +function! s:Flag_print_width(config) abort + let l:value = get(a:config, 'printWidth', g:prettier#config#print_width) + + if (l:value ==# 'auto') + let l:value = &textwidth + endif + + if (l:value > 0) + return '--print-width=' . l:value + else + return '' + endif +endfunction + +" Returns '--parser=PARSER' or '' +function! s:Flag_parser(config) abort + let l:value = get(a:config, 'parser', g:prettier#config#parser) + + if (l:value !=# '') + return '--parser=' . l:value + else + return '' + endif +endfunction + " By default we will default to our internal " configuration settings for prettier function! s:Get_Prettier_Exec_Args(config) abort " Allow params to be passed as json format " convert bellow usage of globals to a get function o the params defaulting to global - let l:cmd = ' --print-width ' . - \ get(a:config, 'printWidth', g:prettier#config#print_width) . - \ ' --tab-width ' . - \ get(a:config, 'tabWidth', g:prettier#config#tab_width) . - \ ' --use-tabs ' . - \ get(a:config, 'useTabs', g:prettier#config#use_tabs) . - \ ' --semi ' . - \ get(a:config, 'semi', g:prettier#config#semi) . - \ ' --single-quote ' . - \ get(a:config, 'singleQuote', g:prettier#config#single_quote) . - \ ' --bracket-spacing ' . - \ get(a:config, 'bracketSpacing', g:prettier#config#bracket_spacing) . - \ ' --jsx-bracket-same-line ' . - \ get(a:config, 'jsxBracketSameLine', g:prettier#config#jsx_bracket_same_line) . - \ ' --arrow-parens ' . - \ get(a:config, 'arrowParens', g:prettier#config#arrow_parens) . - \ ' --trailing-comma ' . - \ get(a:config, 'trailingComma', g:prettier#config#trailing_comma) . - \ ' --parser ' . - \ get(a:config, 'parser', g:prettier#config#parser) . - \ ' --config-precedence ' . + " TODO: Use a list, filter() and join() to get a nicer list of args. + let l:cmd = s:Flag_use_tabs(a:config) . ' ' . + \ s:Flag_tab_width(a:config) . ' ' . + \ s:Flag_print_width(a:config) . ' ' . + \ s:Flag_parser(a:config) . ' ' . + \ ' --config-precedence=' . \ get(a:config, 'configPrecedence', g:prettier#config#config_precedence) . - \ ' --prose-wrap ' . + \ ' --prose-wrap=' . \ get(a:config, 'proseWrap', g:prettier#config#prose_wrap) . - \ ' --stdin-filepath ' . + \ ' --stdin-filepath=' . \ simplify(expand('%:p')) . \ ' --no-editorconfig '. \ ' --loglevel error '. -- cgit v1.3-5-g45d5 From a9326e2596c56b7717562b9dc7f749c7c5faf7b4 Mon Sep 17 00:00:00 2001 From: mitermayer Date: Wed, 2 May 2018 16:55:44 -0700 Subject: Starting refactoring methods out to components - This is the first commit on refactoring methods outs on self contained components, this will help on unit testing and maintainability --- autoload/prettier.vim | 6 +++--- autoload/prettier/logging/error.vim | 12 ++++++++++++ 2 files changed, 15 insertions(+), 3 deletions(-) create mode 100644 autoload/prettier/logging/error.vim (limited to 'autoload/prettier.vim') diff --git a/autoload/prettier.vim b/autoload/prettier.vim index 7cf9cca..71f21d6 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -204,7 +204,7 @@ function! s:Prettier_Job_Close(channel, startSelection, endSelection, bufferName silent exec 'sp '. escape(bufname(bufnr(a:bufferName)), ' \') call s:Prettier_Format_And_Save(l:out, a:startSelection, a:endSelection) catch - echohl WarningMsg | echom 'Prettier: failed to parse buffer: ' . a:bufferName | echohl NONE + call prettier#logging#error#log('PARSING_ERROR', a:bufferName) finally " we should then hide this buffer again if a:bufferName == bufname('%') @@ -453,7 +453,7 @@ function! s:Traverse_Dir_Search(rootDir) abort endfunction function! s:Prettier_Parse_Error(errors) abort - echohl WarningMsg | echom 'Prettier: failed to parse buffer.' | echohl NONE + call prettier#logging#error#log('PARSING_ERROR') if g:prettier#quickfix_enabled call s:Handle_Parsing_Errors(a:errors) endif @@ -461,5 +461,5 @@ endfunction " If we can't find any prettier installing we then suggest where to get it from function! s:Suggest_Install_Prettier() abort - echohl WarningMsg | echom 'Prettier: no prettier executable installation found.' | echohl NONE + call prettier#logging#error#log('EXECUTABLE_NOT_FOUND_ERROR') endfunction diff --git a/autoload/prettier/logging/error.vim b/autoload/prettier/logging/error.vim new file mode 100644 index 0000000..48ad048 --- /dev/null +++ b/autoload/prettier/logging/error.vim @@ -0,0 +1,12 @@ +let s:PREFIX_MSG = 'Prettier: ' +let s:ERRORS = { + \ 'EXECUTABLE_NOT_FOUND_ERROR': 'no prettier executable installation found', + \ 'PARSING_ERROR': 'failed to parse buffer', + \ } +let s:DEFAULT_ERROR = get(s:, 'PARSING_ERROR') + +function! prettier#logging#error#log(...) abort + let l:error = a:0 > 0 ? a:1 : s:DEFAULT_ERROR + let l:msg = a:0 > 1 ? ': ' . a:2 : '' + echohl WarningMsg | echom s:PREFIX_MSG . get(s:ERRORS, l:error, s:DEFAULT_ERROR) . l:msg | echohl NONE +endfunction -- cgit v1.3-5-g45d5 From bfd9fc654c34a7ffea5dd0f98dc17472ffe2baee Mon Sep 17 00:00:00 2001 From: mitermayer Date: Wed, 2 May 2018 21:36:47 -0700 Subject: Cleaning up unecessary function --- autoload/prettier.vim | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) (limited to 'autoload/prettier.vim') diff --git a/autoload/prettier.vim b/autoload/prettier.vim index 71f21d6..bd47e60 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -21,7 +21,7 @@ function! prettier#PrettierCliPath() abort if l:execCmd != -1 echom l:execCmd else - call s:Suggest_Install_Prettier() + call prettier#logging#error#log('EXECUTABLE_NOT_FOUND_ERROR') endif endfunction @@ -32,7 +32,7 @@ function! prettier#PrettierCli(user_input) abort let l:out = system(l:execCmd. ' ' . a:user_input) echom l:out else - call s:Suggest_Install_Prettier() + call prettier#logging#error#log('EXECUTABLE_NOT_FOUND_ERROR') endif endfunction @@ -61,7 +61,7 @@ function! prettier#Prettier(...) abort call s:Prettier_Exec_Sync(l:cmd, l:startSelection, l:endSelection) endif else - call s:Suggest_Install_Prettier() + call prettier#logging#error#log('EXECUTABLE_NOT_FOUND_ERROR') endif endfunction @@ -458,8 +458,3 @@ function! s:Prettier_Parse_Error(errors) abort call s:Handle_Parsing_Errors(a:errors) endif endfunction - -" If we can't find any prettier installing we then suggest where to get it from -function! s:Suggest_Install_Prettier() abort - call prettier#logging#error#log('EXECUTABLE_NOT_FOUND_ERROR') -endfunction -- cgit v1.3-5-g45d5 From b36bc58f36237a7b6f87057b8877fb31ef0c3f0b Mon Sep 17 00:00:00 2001 From: mitermayer Date: Wed, 2 May 2018 21:59:24 -0700 Subject: Adding bridge handler - Refactoring parser out into its own module in order to make it easier to test --- autoload/prettier.vim | 34 +++------------------------------- autoload/prettier/bridge/parser.vim | 28 ++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 31 deletions(-) create mode 100644 autoload/prettier/bridge/parser.vim (limited to 'autoload/prettier.vim') diff --git a/autoload/prettier.vim b/autoload/prettier.vim index bd47e60..2708caa 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -96,6 +96,7 @@ function! s:Prettier_Job_Nvim_Exit(status, info, out, err) abort echoerr join(a:err, "\n") return endif + if len(a:out) == 0 | return | endif let l:last = a:out[len(a:out) - 1] @@ -230,35 +231,6 @@ function! s:Prettier_Job_Error(msg) abort let s:prettier_job_running = 0 endfunction -function! s:Handle_Parsing_Errors(out) abort - let l:errors = [] - - for l:line in a:out - " matches: - " file.ext: SyntaxError: Unexpected token (2:8)sd - " stdin: SyntaxError: Unexpected token (2:8) - " [error] file.ext: SyntaxError: Unexpected token (2:8) - let l:match = matchlist(l:line, '^.*: \(.*\) (\(\d\{1,}\):\(\d\{1,}\)*)') - if !empty(l:match) - call add(l:errors, { 'bufnr': bufnr('%'), - \ 'text': l:match[1], - \ 'lnum': l:match[2], - \ 'col': l:match[3] }) - endif - endfor - - if len(l:errors) - let l:winnr = winnr() - call setqflist(l:errors, 'r') - botright copen - if !g:prettier#quickfix_auto_focus - " Return the cursor back to the main buffer. - exe l:winnr . 'wincmd w' - endif - let s:prettier_quickfix_open = 1 - endif -endfunction - function! s:Has_Content_Changed(content, startLine, endLine) abort return getbufline(bufnr('%'), 1, line('$')) == s:Get_New_Buffer(a:content, a:startLine, a:endLine) ? 0 : 1 endfunction @@ -454,7 +426,7 @@ endfunction function! s:Prettier_Parse_Error(errors) abort call prettier#logging#error#log('PARSING_ERROR') - if g:prettier#quickfix_enabled - call s:Handle_Parsing_Errors(a:errors) + if g:prettier#quickfix_enabled && prettier#bridge#parser#onError(a:errors) + let s:prettier_quickfix_open = 1 endif endfunction diff --git a/autoload/prettier/bridge/parser.vim b/autoload/prettier/bridge/parser.vim new file mode 100644 index 0000000..eb23210 --- /dev/null +++ b/autoload/prettier/bridge/parser.vim @@ -0,0 +1,28 @@ +function! prettier#bridge#parser#onError(out) abort + let l:errors = [] + + for l:line in a:out + " matches: + " file.ext: SyntaxError: Unexpected token (2:8)sd + " stdin: SyntaxError: Unexpected token (2:8) + " [error] file.ext: SyntaxError: Unexpected token (2:8) + let l:match = matchlist(l:line, '^.*: \(.*\) (\(\d\{1,}\):\(\d\{1,}\)*)') + if !empty(l:match) + call add(l:errors, { 'bufnr': bufnr('%'), + \ 'text': l:match[1], + \ 'lnum': l:match[2], + \ 'col': l:match[3] }) + endif + endfor + + if len(l:errors) + let l:winnr = winnr() + call setqflist(l:errors, 'r') + botright copen + if !g:prettier#quickfix_auto_focus + " Return the cursor back to the main buffer. + exe l:winnr . 'wincmd w' + endif + return 1 + endif +endfunction -- cgit v1.3-5-g45d5 From 7048c8cc4a821a7b6d99f3ef8ff5da3dc69dd62e Mon Sep 17 00:00:00 2001 From: mitermayer Date: Wed, 2 May 2018 22:33:06 -0700 Subject: Refactoring executable resolver out into its own module - Refactoring the executable resolver into its own module for making it easier to test --- autoload/prettier.vim | 89 ++----------------------------- autoload/prettier/resolver/executable.vim | 74 +++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 86 deletions(-) create mode 100644 autoload/prettier/resolver/executable.vim (limited to 'autoload/prettier.vim') diff --git a/autoload/prettier.vim b/autoload/prettier.vim index 2708caa..c6b89fd 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -16,7 +16,7 @@ let s:prettier_job_running = 0 let s:prettier_quickfix_open = 0 function! prettier#PrettierCliPath() abort - let l:execCmd = s:Get_Prettier_Exec() + let l:execCmd = prettier#resolver#executable#getPath() if l:execCmd != -1 echom l:execCmd @@ -26,7 +26,7 @@ function! prettier#PrettierCliPath() abort endfunction function! prettier#PrettierCli(user_input) abort - let l:execCmd = s:Get_Prettier_Exec() + let l:execCmd = prettier#resolver#executable#getPath() if l:execCmd != -1 let l:out = system(l:execCmd. ' ' . a:user_input) @@ -37,7 +37,7 @@ function! prettier#PrettierCli(user_input) abort endfunction function! prettier#Prettier(...) abort - let l:execCmd = s:Get_Prettier_Exec() + let l:execCmd = prettier#resolver#executable#getPath() let l:async = a:0 > 0 ? a:1 : 0 let l:startSelection = a:0 > 1 ? a:2 : 1 let l:endSelection = a:0 > 2 ? a:3 : line('$') @@ -341,89 +341,6 @@ function! s:Get_Prettier_Exec_Args(config) abort return l:cmd endfunction -" By default we will search for the following -" => user defined prettier cli path from vim configuration file -" => locally installed prettier inside node_modules on any parent folder -" => globally installed prettier -" => vim-prettier prettier installation -" => if all fails suggest install -function! s:Get_Prettier_Exec() abort - let l:user_defined_exec_path = fnamemodify(g:prettier#exec_cmd_path, ':p') - if executable(l:user_defined_exec_path) - return l:user_defined_exec_path - endif - - let l:local_exec = s:Get_Prettier_Local_Exec() - if executable(l:local_exec) - return fnameescape(l:local_exec) - endif - - let l:global_exec = s:Get_Prettier_Global_Exec() - if executable(l:global_exec) - return fnameescape(l:global_exec) - endif - - let l:plugin_exec = s:Get_Prettier_Plugin_Exec() - if executable(l:plugin_exec) - return fnameescape(l:plugin_exec) - endif - - return -1 -endfunction - -function! s:Get_Prettier_Local_Exec() abort - return s:Get_Exec(getcwd()) -endfunction - -function! s:Get_Prettier_Global_Exec() abort - return s:Get_Exec() -endfunction - -function! s:Get_Prettier_Plugin_Exec() abort - return s:Get_Exec(s:root_dir) -endfunction - -function! s:Get_Exec(...) abort - let l:rootDir = a:0 > 0 ? a:1 : 0 - let l:exec = -1 - - if isdirectory(l:rootDir) - let l:dir = s:Traverse_Dir_Search(l:rootDir) - if l:dir != -1 - let l:exec = s:Get_Path_To_Exec(l:dir) - endif - else - let l:exec = s:Get_Path_To_Exec() - endif - - return l:exec -endfunction - -function! s:Get_Path_To_Exec(...) abort - let l:rootDir = a:0 > 0 ? a:1 : -1 - let l:dir = l:rootDir != -1 ? l:rootDir . '/.bin/' : '' - return l:dir . 'prettier' -endfunction - -function! s:Traverse_Dir_Search(rootDir) abort - let l:root = a:rootDir - let l:dir = 'node_modules' - - while 1 - let l:search_dir = l:root . '/' . l:dir - if isdirectory(l:search_dir) - return l:search_dir - endif - - let l:parent = fnamemodify(l:root, ':h') - if l:parent == l:root - return -1 - endif - - let l:root = l:parent - endwhile -endfunction - function! s:Prettier_Parse_Error(errors) abort call prettier#logging#error#log('PARSING_ERROR') if g:prettier#quickfix_enabled && prettier#bridge#parser#onError(a:errors) diff --git a/autoload/prettier/resolver/executable.vim b/autoload/prettier/resolver/executable.vim new file mode 100644 index 0000000..8d233ab --- /dev/null +++ b/autoload/prettier/resolver/executable.vim @@ -0,0 +1,74 @@ +let s:ROOT_DIR = fnamemodify(resolve(expand(':p')), ':h') + +" By default we will search for the following +" => user defined prettier cli path from vim configuration file +" => locally installed prettier inside node_modules on any parent folder +" => globally installed prettier +" => vim-prettier prettier installation +" => if all fails suggest install +function! prettier#resolver#executable#getPath() abort + let l:user_defined_exec_path = fnamemodify(g:prettier#exec_cmd_path, ':p') + if executable(l:user_defined_exec_path) + return l:user_defined_exec_path + endif + + let l:localExec = s:ResolveExecutable(getcwd()) + if executable(l:localExec) + return fnameescape(l:localExec) + endif + + let l:globalExec = s:ResolveExecutable() + if executable(l:globalExec) + return fnameescape(l:globalExec) + endif + + let l:pluginExec = s:ResolveExecutable(s:ROOT_DIR) + if executable(l:pluginExec) + return fnameescape(l:pluginExec) + endif + + return -1 +endfunction + +function! s:GetExecPath(...) abort + let l:rootDir = a:0 > 0 ? a:1 : -1 + let l:dir = l:rootDir != -1 ? l:rootDir . '/.bin/' : '' + return l:dir . 'prettier' +endfunction + +" Searches for the existence of a directory accross +" ancestral parents +function! s:TraverseAncestorDirSearch(rootDir) abort + let l:root = a:rootDir + let l:dir = 'node_modules' + + while 1 + let l:searchDir = l:root . '/' . l:dir + if isdirectory(l:searchDir) + return l:searchDir + endif + + let l:parent = fnamemodify(l:root, ':h') + if l:parent == l:root + return -1 + endif + + let l:root = l:parent + endwhile +endfunction + +function! s:ResolveExecutable(...) abort + let l:rootDir = a:0 > 0 ? a:1 : 0 + let l:exec = -1 + + if isdirectory(l:rootDir) + let l:dir = s:TraverseAncestorDirSearch(l:rootDir) + if l:dir != -1 + let l:exec = s:GetExecPath(l:dir) + endif + else + let l:exec = s:GetExecPath() + endif + + return l:exec +endfunction -- cgit v1.3-5-g45d5 From 7765555504669f643d799189230f21ba051c51ae Mon Sep 17 00:00:00 2001 From: mitermayer Date: Wed, 2 May 2018 22:45:49 -0700 Subject: Creating shim utils to handle backwards compatiblity functions - Movingthe shiftwidth compat helper to a shim module responsible for dealing with backwards compatiblity --- autoload/prettier.vim | 11 +---------- autoload/prettier/utils/shim.vim | 8 ++++++++ 2 files changed, 9 insertions(+), 10 deletions(-) create mode 100644 autoload/prettier/utils/shim.vim (limited to 'autoload/prettier.vim') diff --git a/autoload/prettier.vim b/autoload/prettier.vim index c6b89fd..d7c4338 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -273,21 +273,12 @@ function! s:Flag_use_tabs(config) abort endif endfunction -" Backwards compatable version of shiftwidth() -function! s:sw() abort - if exists('*shiftwidth') - return shiftwidth() - else - return &shiftwidth - endif -endfunction - " Returns '--tab-width=NN' function! s:Flag_tab_width(config) abort let l:value = get(a:config, 'tabWidth', g:prettier#config#tab_width) if (l:value ==# 'auto') - let l:value = s:sw() + let l:value = prettier#utils#shim#shiftwidth() endif return '--tab-width=' . l:value diff --git a/autoload/prettier/utils/shim.vim b/autoload/prettier/utils/shim.vim new file mode 100644 index 0000000..228829e --- /dev/null +++ b/autoload/prettier/utils/shim.vim @@ -0,0 +1,8 @@ +" Backwards compatable version of shiftwidth() +function! prettier#utils#shim#shiftwidth() abort + if exists('*shiftwidth') + return shiftwidth() + else + return &shiftwidth + endif +endfunction -- cgit v1.3-5-g45d5 From 6672adfa1b05d8dc7450052df69a1ffd559eca1e Mon Sep 17 00:00:00 2001 From: mitermayer Date: Thu, 3 May 2018 13:46:30 -0700 Subject: Moving argument build into config resolver module --- autoload/prettier.vim | 75 +---------------------------------- autoload/prettier/resolver/config.vim | 72 +++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 74 deletions(-) create mode 100644 autoload/prettier/resolver/config.vim (limited to 'autoload/prettier.vim') diff --git a/autoload/prettier.vim b/autoload/prettier.vim index d7c4338..c1aa35b 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -44,7 +44,7 @@ function! prettier#Prettier(...) abort let l:config = getbufvar(bufnr('%'), 'prettier_ft_default_args', {}) if l:execCmd != -1 - let l:cmd = l:execCmd . s:Get_Prettier_Exec_Args(l:config) + let l:cmd = l:execCmd . prettier#resolver#config#buildCliArgs(l:config) " close quickfix if it is opened if s:prettier_quickfix_open @@ -259,79 +259,6 @@ function! s:Apply_Prettier_Format(lines, startSelection, endSelection) abort call winrestview(l:winview) endfunction -" Returns either '--use-tabs' or an empty string. -function! s:Flag_use_tabs(config) abort - let l:value = get(a:config, 'useTabs', g:prettier#config#use_tabs) - if (l:value ==# 'auto') - let l:value = &expandtab ? 'false' : 'true' - endif - - if ( l:value ==# 'true' ) - return '--use-tabs' - else - return '' - endif -endfunction - -" Returns '--tab-width=NN' -function! s:Flag_tab_width(config) abort - let l:value = get(a:config, 'tabWidth', g:prettier#config#tab_width) - - if (l:value ==# 'auto') - let l:value = prettier#utils#shim#shiftwidth() - endif - - return '--tab-width=' . l:value -endfunction - -" Returns '--print-width=NN' or '' -function! s:Flag_print_width(config) abort - let l:value = get(a:config, 'printWidth', g:prettier#config#print_width) - - if (l:value ==# 'auto') - let l:value = &textwidth - endif - - if (l:value > 0) - return '--print-width=' . l:value - else - return '' - endif -endfunction - -" Returns '--parser=PARSER' or '' -function! s:Flag_parser(config) abort - let l:value = get(a:config, 'parser', g:prettier#config#parser) - - if (l:value !=# '') - return '--parser=' . l:value - else - return '' - endif -endfunction - -" By default we will default to our internal -" configuration settings for prettier -function! s:Get_Prettier_Exec_Args(config) abort - " Allow params to be passed as json format - " convert bellow usage of globals to a get function o the params defaulting to global - " TODO: Use a list, filter() and join() to get a nicer list of args. - let l:cmd = s:Flag_use_tabs(a:config) . ' ' . - \ s:Flag_tab_width(a:config) . ' ' . - \ s:Flag_print_width(a:config) . ' ' . - \ s:Flag_parser(a:config) . ' ' . - \ ' --config-precedence=' . - \ get(a:config, 'configPrecedence', g:prettier#config#config_precedence) . - \ ' --prose-wrap=' . - \ get(a:config, 'proseWrap', g:prettier#config#prose_wrap) . - \ ' --stdin-filepath=' . - \ simplify(expand('%:p')) . - \ ' --no-editorconfig '. - \ ' --loglevel error '. - \ ' --stdin ' - return l:cmd -endfunction - function! s:Prettier_Parse_Error(errors) abort call prettier#logging#error#log('PARSING_ERROR') if g:prettier#quickfix_enabled && prettier#bridge#parser#onError(a:errors) diff --git a/autoload/prettier/resolver/config.vim b/autoload/prettier/resolver/config.vim new file mode 100644 index 0000000..ffdd8ff --- /dev/null +++ b/autoload/prettier/resolver/config.vim @@ -0,0 +1,72 @@ +" By default we will default to our internal +" configuration settings for prettier +function! prettier#resolver#config#buildCliArgs(config) abort + " Allow params to be passed as json format + " convert bellow usage of globals to a get function o the params defaulting to global + " TODO: Use a list, filter() and join() to get a nicer list of args. + let l:cmd = s:Flag_use_tabs(a:config) . ' ' . + \ s:Flag_tab_width(a:config) . ' ' . + \ s:Flag_print_width(a:config) . ' ' . + \ s:Flag_parser(a:config) . ' ' . + \ ' --config-precedence=' . + \ get(a:config, 'configPrecedence', g:prettier#config#config_precedence) . + \ ' --prose-wrap=' . + \ get(a:config, 'proseWrap', g:prettier#config#prose_wrap) . + \ ' --stdin-filepath=' . + \ simplify(expand('%:p')) . + \ ' --no-editorconfig '. + \ ' --loglevel error '. + \ ' --stdin ' + return l:cmd +endfunction + +" Returns '--tab-width=NN' +function! s:Flag_tab_width(config) abort + let l:value = get(a:config, 'tabWidth', g:prettier#config#tab_width) + + if (l:value ==# 'auto') + let l:value = prettier#utils#shim#shiftwidth() + endif + + return '--tab-width=' . l:value +endfunction + +" Returns either '--use-tabs' or an empty string. +function! s:Flag_use_tabs(config) abort + let l:value = get(a:config, 'useTabs', g:prettier#config#use_tabs) + if (l:value ==# 'auto') + let l:value = &expandtab ? 'false' : 'true' + endif + + if ( l:value ==# 'true' ) + return '--use-tabs' + else + return '' + endif +endfunction + +" Returns '--print-width=NN' or '' +function! s:Flag_print_width(config) abort + let l:value = get(a:config, 'printWidth', g:prettier#config#print_width) + + if (l:value ==# 'auto') + let l:value = &textwidth + endif + + if (l:value > 0) + return '--print-width=' . l:value + else + return '' + endif +endfunction + +" Returns '--parser=PARSER' or '' +function! s:Flag_parser(config) abort + let l:value = get(a:config, 'parser', g:prettier#config#parser) + + if (l:value !=# '') + return '--parser=' . l:value + else + return '' + endif +endfunction -- cgit v1.3-5-g45d5 From 314e4053ca3676dce8deceaa432667ab2f3a0058 Mon Sep 17 00:00:00 2001 From: mitermayer Date: Fri, 4 May 2018 09:37:26 -0700 Subject: Moving formating ultils to buffer module - moving formating utils to buffer module to make it easier to interact and test --- autoload/prettier.vim | 36 ++++-------------------------------- autoload/prettier/utils/buffer.vim | 29 +++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 32 deletions(-) create mode 100644 autoload/prettier/utils/buffer.vim (limited to 'autoload/prettier.vim') diff --git a/autoload/prettier.vim b/autoload/prettier.vim index c1aa35b..b4cc7d7 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -151,11 +151,11 @@ function! s:Prettier_Exec_Sync(cmd, startSelection, endSelection) abort return endif - if (s:Has_Content_Changed(l:out, a:startSelection, a:endSelection) == 0) + if (prettier#utils#buffer#willUpdatedLinesChangeBuffer(l:out, a:startSelection, a:endSelection) == 0) return endif - call s:Apply_Prettier_Format(l:out, a:startSelection, a:endSelection) + call prettier#utils#buffer#replace(l:out, a:startSelection, a:endSelection) endfunction function! s:Prettier_Exec_Async(cmd, startSelection, endSelection) abort @@ -189,7 +189,7 @@ function! s:Prettier_Job_Close(channel, startSelection, endSelection, bufferName endwhile " nothing to update - if (s:Has_Content_Changed(l:out, a:startSelection, a:endSelection) == 0) + if (prettier#utils#buffer#willUpdatedLinesChangeBuffer(l:out, a:startSelection, a:endSelection) == 0) let s:prettier_job_running = 0 return endif @@ -222,7 +222,7 @@ function! s:Prettier_Job_Close(channel, startSelection, endSelection, bufferName endfunction function! s:Prettier_Format_And_Save(lines, start, end) abort - call s:Apply_Prettier_Format(a:lines, a:start, a:end) + call prettier#utils#buffer#replace(a:lines, a:start, a:end) write endfunction @@ -231,34 +231,6 @@ function! s:Prettier_Job_Error(msg) abort let s:prettier_job_running = 0 endfunction -function! s:Has_Content_Changed(content, startLine, endLine) abort - return getbufline(bufnr('%'), 1, line('$')) == s:Get_New_Buffer(a:content, a:startLine, a:endLine) ? 0 : 1 -endfunction - -function! s:Get_New_Buffer(lines, start, end) abort - return getbufline(bufnr('%'), 1, a:start - 1) + a:lines + getbufline(bufnr('%'), a:end + 1, '$') -endfunction - -function! s:Apply_Prettier_Format(lines, startSelection, endSelection) abort - " store view - let l:winview = winsaveview() - let l:newBuffer = s:Get_New_Buffer(a:lines, a:startSelection, a:endSelection) - - " we should not replace contents if the newBuffer is empty - if empty(l:newBuffer) - return - endif - - " delete all lines on the current buffer - silent! execute len(l:newBuffer) . ',' . line('$') . 'delete _' - - " replace all lines from the current buffer with output from prettier - call setline(1, l:newBuffer) - - " Restore view - call winrestview(l:winview) -endfunction - function! s:Prettier_Parse_Error(errors) abort call prettier#logging#error#log('PARSING_ERROR') if g:prettier#quickfix_enabled && prettier#bridge#parser#onError(a:errors) diff --git a/autoload/prettier/utils/buffer.vim b/autoload/prettier/utils/buffer.vim new file mode 100644 index 0000000..06fd7ff --- /dev/null +++ b/autoload/prettier/utils/buffer.vim @@ -0,0 +1,29 @@ +function! prettier#utils#buffer#replace(lines, startSelection, endSelection) abort + " store view + let l:winview = winsaveview() + let l:newBuffer = prettier#utils#buffer#createBufferFromUpdatedLines(a:lines, a:startSelection, a:endSelection) + + " we should not replace contents if the newBuffer is empty + if empty(l:newBuffer) + return + endif + + " delete all lines on the current buffer + silent! execute len(l:newBuffer) . ',' . line('$') . 'delete _' + + " replace all lines from the current buffer with output from prettier + call setline(1, l:newBuffer) + + " Restore view + call winrestview(l:winview) +endfunction + +" Returns 1 if content has changed +function! prettier#utils#buffer#willUpdatedLinesChangeBuffer(lines, start, end) abort + return getbufline(bufnr('%'), 1, line('$')) == prettier#utils#buffer#createBufferFromUpdatedLines(a:lines, a:start, a:end) ? 0 : 1 +endfunction + +" Returns a new buffer with lines replacing start and end of the contents of the current buffer +function! prettier#utils#buffer#createBufferFromUpdatedLines(lines, start, end) abort + return getbufline(bufnr('%'), 1, a:start - 1) + a:lines + getbufline(bufnr('%'), a:end + 1, '$') +endfunction -- cgit v1.3-5-g45d5 From e78c17a9fa8aab9067a44f9836d46fa9dc2d5914 Mon Sep 17 00:00:00 2001 From: mitermayer Date: Fri, 4 May 2018 12:09:01 -0700 Subject: Refactoring out sync jobs and quickfix module --- autoload/prettier.vim | 35 +++-------------------- autoload/prettier/bridge/parser.vim | 14 ++++------ autoload/prettier/job/runner.vim | 54 ++++++++++++++++++++++++++++++++---- autoload/prettier/utils/quickfix.vim | 22 +++++++++++++++ 4 files changed, 80 insertions(+), 45 deletions(-) create mode 100644 autoload/prettier/utils/quickfix.vim (limited to 'autoload/prettier.vim') diff --git a/autoload/prettier.vim b/autoload/prettier.vim index b4cc7d7..331d0f1 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -11,9 +11,7 @@ "========================================================================================================== " }}} -let s:root_dir = fnamemodify(resolve(expand(':p')), ':h') let s:prettier_job_running = 0 -let s:prettier_quickfix_open = 0 function! prettier#PrettierCliPath() abort let l:execCmd = prettier#resolver#executable#getPath() @@ -47,18 +45,14 @@ function! prettier#Prettier(...) abort let l:cmd = l:execCmd . prettier#resolver#config#buildCliArgs(l:config) " close quickfix if it is opened - if s:prettier_quickfix_open - call setqflist([], 'r') - cclose - let s:prettier_quickfix_open = 0 - endif + call prettier#utils#quickfix#close() if l:async && v:version >= 800 && exists('*job_start') call s:Prettier_Exec_Async(l:cmd, l:startSelection, l:endSelection) elseif l:async && has('nvim') && g:prettier#nvim_unstable_async call s:Prettier_Exec_Async_Nvim(l:cmd, l:startSelection, l:endSelection) else - call s:Prettier_Exec_Sync(l:cmd, l:startSelection, l:endSelection) + call prettier#job#runner#run(l:cmd, l:startSelection, l:endSelection, l:async) endif else call prettier#logging#error#log('EXECUTABLE_NOT_FOUND_ERROR') @@ -137,27 +131,6 @@ function! prettier#Autoformat(...) abort let @/=l:search endfunction -function! s:Prettier_Exec_Sync(cmd, startSelection, endSelection) abort - let l:bufferLinesList = getbufline(bufnr('%'), a:startSelection, a:endSelection) - - " vim 7 does not have support for passing a list to system() - let l:bufferLines = v:version <= 800 ? join(l:bufferLinesList, "\n") : l:bufferLinesList - - let l:out = split(system(a:cmd, l:bufferLines), '\n') - - " check system exit code - if v:shell_error - call s:Prettier_Parse_Error(l:out) - return - endif - - if (prettier#utils#buffer#willUpdatedLinesChangeBuffer(l:out, a:startSelection, a:endSelection) == 0) - return - endif - - call prettier#utils#buffer#replace(l:out, a:startSelection, a:endSelection) -endfunction - function! s:Prettier_Exec_Async(cmd, startSelection, endSelection) abort let l:async_cmd = a:cmd @@ -233,7 +206,7 @@ endfunction function! s:Prettier_Parse_Error(errors) abort call prettier#logging#error#log('PARSING_ERROR') - if g:prettier#quickfix_enabled && prettier#bridge#parser#onError(a:errors) - let s:prettier_quickfix_open = 1 + if g:prettier#quickfix_enabled + call prettier#bridge#parser#onError(a:errors, g:prettier#quickfix_auto_focus) endif endfunction diff --git a/autoload/prettier/bridge/parser.vim b/autoload/prettier/bridge/parser.vim index eb23210..51c4069 100644 --- a/autoload/prettier/bridge/parser.vim +++ b/autoload/prettier/bridge/parser.vim @@ -1,4 +1,7 @@ -function! prettier#bridge#parser#onError(out) abort +" TODO +" this function should just returns the parsed errors list instead +" of opening the quickfix +function! prettier#bridge#parser#onError(out, autoFocus) abort let l:errors = [] for l:line in a:out @@ -16,13 +19,6 @@ function! prettier#bridge#parser#onError(out) abort endfor if len(l:errors) - let l:winnr = winnr() - call setqflist(l:errors, 'r') - botright copen - if !g:prettier#quickfix_auto_focus - " Return the cursor back to the main buffer. - exe l:winnr . 'wincmd w' - endif - return 1 + call prettier#utils#quickfix#open(l:errors, a:autoFocus) endif endfunction diff --git a/autoload/prettier/job/runner.vim b/autoload/prettier/job/runner.vim index 3c6b3d9..f5291dd 100644 --- a/autoload/prettier/job/runner.vim +++ b/autoload/prettier/job/runner.vim @@ -1,9 +1,53 @@ +" TODO +" move the bellow vim checks to UTILS +" +" TODO +" we are currently feature protecting async on NVIM with g:prettier#nvim_unstable_async +" we should remove this once its fully supported +let s:isNeoVim = has('nvim') && g:prettier#nvim_unstable_async +let s:isAsyncVim = v:version >= 800 && exists('*job_start') +let s:isLegacyVim = v:version <= 800 + function! prettier#job#runner#run(cmd, startSelection, endSelection, async) abort - if a:async && v:version >= 800 && exists('*job_start') - "call s:Prettier_Exec_Async(l:cmd, l:startSelection, l:endSelection) - elseif a:async && has('nvim') && g:prettier#nvim_unstable_async - "call s:Prettier_Exec_Async_Nvim(l:cmd, l:startSelection, l:endSelection) + if a:async && (s:isAsyncVim || s:isNeoVim) + call s:asyncFormat(a:cmd, a:startSelection, a:endSelection) else - "call s:Prettier_Exec_Sync(l:cmd, l:startSelection, l:endSelection) + call s:format(a:cmd, a:startSelection, a:endSelection) endif endfunction + +function! prettier#job#runner#onError(errors) abort + call prettier#logging#error#log('PARSING_ERROR') + if g:prettier#quickfix_enabled + call prettier#bridge#parser#onError(a:errors, g:prettier#quickfix_auto_focus) + endif +endfunction + +function! s:asyncFormat(cmd, startSelection, endSelection, autoFocus) abort + if s:isAsyncVim + echom 'async vim' + else + echom 'neovim' + endif +endfunction + +function! s:format(cmd, startSelection, endSelection) abort + let l:bufferLinesList = getbufline(bufnr('%'), a:startSelection, a:endSelection) + + " vim 7 does not have support for passing a list to system() + let l:bufferLines = s:isLegacyVim ? join(l:bufferLinesList, "\n") : l:bufferLinesList + + let l:out = split(system(a:cmd, l:bufferLines), '\n') + + " check system exit code + if v:shell_error + call prettier#job#runner#onError(l:out) + return + endif + + if (prettier#utils#buffer#willUpdatedLinesChangeBuffer(l:out, a:startSelection, a:endSelection) == 0) + return + endif + + call prettier#utils#buffer#replace(l:out, a:startSelection, a:endSelection) +endfunction diff --git a/autoload/prettier/utils/quickfix.vim b/autoload/prettier/utils/quickfix.vim new file mode 100644 index 0000000..b4766a7 --- /dev/null +++ b/autoload/prettier/utils/quickfix.vim @@ -0,0 +1,22 @@ +" We use this flag so that we ensure only clearing quickfix if it was created by prettier itself +let s:prettier_quickfix_open = 0 + +function! prettier#utils#quickfix#close() abort + " close quickfix if it is opened + if s:prettier_quickfix_open + call setqflist([], 'r') + cclose + let s:prettier_quickfix_open = 0 + endif +endfunction + +function! prettier#utils#quickfix#open(errors, focus) abort + let s:prettier_quickfix_open = 1 + let l:winnr = winnr() + call setqflist(a:errors, 'r') + botright copen + if !a:focus + " Return the cursor back to the main buffer. + exe l:winnr . 'wincmd w' + endif +endfunction -- cgit v1.3-5-g45d5 From 4217bfb37ccd261110b9bac0903807f6db7f0aaa Mon Sep 17 00:00:00 2001 From: mitermayer Date: Fri, 4 May 2018 12:13:46 -0700 Subject: Removing unecessary method --- autoload/prettier.vim | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) (limited to 'autoload/prettier.vim') diff --git a/autoload/prettier.vim b/autoload/prettier.vim index 331d0f1..f0ab148 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -200,13 +200,6 @@ function! s:Prettier_Format_And_Save(lines, start, end) abort endfunction function! s:Prettier_Job_Error(msg) abort - call s:Prettier_Parse_Error(split(a:msg, '\n')) + call prettier#job#runner#onError(split(a:msg, '\n')) let s:prettier_job_running = 0 endfunction - -function! s:Prettier_Parse_Error(errors) abort - call prettier#logging#error#log('PARSING_ERROR') - if g:prettier#quickfix_enabled - call prettier#bridge#parser#onError(a:errors, g:prettier#quickfix_auto_focus) - endif -endfunction -- cgit v1.3-5-g45d5 From e3be094d12b56e3d1cb88e657267ae0702f3e376 Mon Sep 17 00:00:00 2001 From: mitermayer Date: Fri, 4 May 2018 12:40:40 -0700 Subject: Moving modern vim async formater into its own module --- autoload/prettier.vim | 77 +------------------------------------ autoload/prettier/job/async/vim.vim | 77 +++++++++++++++++++++++++++++++++++++ autoload/prettier/job/runner.vim | 8 ++-- 3 files changed, 83 insertions(+), 79 deletions(-) (limited to 'autoload/prettier.vim') diff --git a/autoload/prettier.vim b/autoload/prettier.vim index f0ab148..a25459d 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -47,9 +47,7 @@ function! prettier#Prettier(...) abort " close quickfix if it is opened call prettier#utils#quickfix#close() - if l:async && v:version >= 800 && exists('*job_start') - call s:Prettier_Exec_Async(l:cmd, l:startSelection, l:endSelection) - elseif l:async && has('nvim') && g:prettier#nvim_unstable_async + if l:async && has('nvim') && g:prettier#nvim_unstable_async call s:Prettier_Exec_Async_Nvim(l:cmd, l:startSelection, l:endSelection) else call prettier#job#runner#run(l:cmd, l:startSelection, l:endSelection, l:async) @@ -130,76 +128,3 @@ function! prettier#Autoformat(...) abort " Restore search let @/=l:search endfunction - -function! s:Prettier_Exec_Async(cmd, startSelection, endSelection) abort - let l:async_cmd = a:cmd - - if has('win32') || has('win64') - let l:async_cmd = 'cmd.exe /c ' . a:cmd - endif - - let l:bufferName = bufname('%') - - if s:prettier_job_running != 1 - let s:prettier_job_running = 1 - call job_start([&shell, &shellcmdflag, l:async_cmd], { - \ 'in_io': 'buffer', - \ 'in_top': a:startSelection, - \ 'in_bot': a:endSelection, - \ 'in_name': l:bufferName, - \ 'err_cb': {channel, msg -> s:Prettier_Job_Error(msg)}, - \ 'close_cb': {channel -> s:Prettier_Job_Close(channel, a:startSelection, a:endSelection, l:bufferName)}}) - endif -endfunction - -function! s:Prettier_Job_Close(channel, startSelection, endSelection, bufferName) abort - let l:out = [] - let l:currentBufferName = bufname('%') - let l:isInsideAnotherBuffer = a:bufferName != l:currentBufferName ? 1 : 0 - - while ch_status(a:channel) ==# 'buffered' - call add(l:out, ch_read(a:channel)) - endwhile - - " nothing to update - if (prettier#utils#buffer#willUpdatedLinesChangeBuffer(l:out, a:startSelection, a:endSelection) == 0) - let s:prettier_job_running = 0 - return - endif - - if len(l:out) - " This is required due to race condition when user quickly switch buffers while the async - " cli has not finished running, vim 8.0.1039 has introduced setbufline() which can be used - " to fix this issue in a cleaner way, however since we still need to support older vim versions - " we will apply a more generic solution - if (l:isInsideAnotherBuffer) - if (bufloaded(str2nr(a:bufferName))) - try - silent exec 'sp '. escape(bufname(bufnr(a:bufferName)), ' \') - call s:Prettier_Format_And_Save(l:out, a:startSelection, a:endSelection) - catch - call prettier#logging#error#log('PARSING_ERROR', a:bufferName) - finally - " we should then hide this buffer again - if a:bufferName == bufname('%') - silent hide - endif - endtry - endif - else - call s:Prettier_Format_And_Save(l:out, a:startSelection, a:endSelection) - endif - - let s:prettier_job_running = 0 - endif -endfunction - -function! s:Prettier_Format_And_Save(lines, start, end) abort - call prettier#utils#buffer#replace(a:lines, a:start, a:end) - write -endfunction - -function! s:Prettier_Job_Error(msg) abort - call prettier#job#runner#onError(split(a:msg, '\n')) - let s:prettier_job_running = 0 -endfunction diff --git a/autoload/prettier/job/async/vim.vim b/autoload/prettier/job/async/vim.vim index e69de29..0fd8f6c 100644 --- a/autoload/prettier/job/async/vim.vim +++ b/autoload/prettier/job/async/vim.vim @@ -0,0 +1,77 @@ +let s:prettier_job_running = 0 + +function! prettier#job#async#vim#run(cmd, startSelection, endSelection) abort + let l:cmd = a:cmd + + if has('win32') || has('win64') + let l:cmd = 'cmd.exe /c ' . a:cmd + endif + + let l:bufferName = bufname('%') + + if s:prettier_job_running != 1 + let s:prettier_job_running = 1 + call job_start([&shell, &shellcmdflag, l:cmd], { + \ 'in_io': 'buffer', + \ 'in_top': a:startSelection, + \ 'in_bot': a:endSelection, + \ 'in_name': l:bufferName, + \ 'err_cb': {channel, msg -> s:onError(msg)}, + \ 'close_cb': {channel -> s:onClose(channel, a:startSelection, a:endSelection, l:bufferName)}}) + endif +endfunction + +function! s:onError(msg) abort + call prettier#job#runner#onError(split(a:msg, '\n')) + let s:prettier_job_running = 0 +endfunction + +function! s:onClose(channel, startSelection, endSelection, bufferName) abort + let l:out = [] + let l:currentBufferName = bufname('%') + let l:isInsideAnotherBuffer = a:bufferName != l:currentBufferName ? 1 : 0 + + while ch_status(a:channel) ==# 'buffered' + call add(l:out, ch_read(a:channel)) + endwhile + + " nothing to update + if (prettier#utils#buffer#willUpdatedLinesChangeBuffer(l:out, a:startSelection, a:endSelection) == 0) + let s:prettier_job_running = 0 + return + endif + + if len(l:out) + " This is required due to race condition when user quickly switch buffers while the async + " cli has not finished running, vim 8.0.1039 has introduced setbufline() which can be used + " to fix this issue in a cleaner way, however since we still need to support older vim versions + " we will apply a more generic solution + if (l:isInsideAnotherBuffer) + if (bufloaded(str2nr(a:bufferName))) + try + silent exec 'sp '. escape(bufname(bufnr(a:bufferName)), ' \') + call s:formatAndSave(l:out, a:startSelection, a:endSelection) + catch + call prettier#logging#error#log('PARSING_ERROR', a:bufferName) + finally + " we should then hide this buffer again + if a:bufferName == bufname('%') + silent hide + endif + endtry + endif + else + call s:formatAndSave(l:out, a:startSelection, a:endSelection) + endif + + let s:prettier_job_running = 0 + endif +endfunction + +" TODO +" make the buffer replace method accerpt an extra arg to +" decide if it should save it or not and delete this method +function! s:formatAndSave(lines, start, end) abort + call prettier#utils#buffer#replace(a:lines, a:start, a:end) + write +endfunction diff --git a/autoload/prettier/job/runner.vim b/autoload/prettier/job/runner.vim index 02dc9d9..b4b1f77 100644 --- a/autoload/prettier/job/runner.vim +++ b/autoload/prettier/job/runner.vim @@ -23,11 +23,13 @@ function! prettier#job#runner#onError(errors) abort endif endfunction -function! s:asyncFormat(cmd, startSelection, endSelection, autoFocus) abort +function! s:asyncFormat(cmd, startSelection, endSelection) abort if s:isAsyncVim - echom 'async vim' - else + call prettier#job#async#vim#run(a:cmd, a:startSelection, a:endSelection) + elseif s:isNeoVim echom 'neovim' + else + call s:format(a:cmd, a:startSelection, a:endSelection) endif endfunction -- cgit v1.3-5-g45d5 From 7bb76288d4c8edf162c24f20fc939bff289857bf Mon Sep 17 00:00:00 2001 From: mitermayer Date: Fri, 4 May 2018 12:49:42 -0700 Subject: Simple heading comments --- autoload/prettier.vim | 3 +++ 1 file changed, 3 insertions(+) (limited to 'autoload/prettier.vim') diff --git a/autoload/prettier.vim b/autoload/prettier.vim index a25459d..63a72d2 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -13,6 +13,7 @@ let s:prettier_job_running = 0 +" Displays the resolve prettier CLI path function! prettier#PrettierCliPath() abort let l:execCmd = prettier#resolver#executable#getPath() @@ -23,6 +24,7 @@ function! prettier#PrettierCliPath() abort endif endfunction +" Allows user commands to be passed straight to the prettier CLI function! prettier#PrettierCli(user_input) abort let l:execCmd = prettier#resolver#executable#getPath() @@ -34,6 +36,7 @@ function! prettier#PrettierCli(user_input) abort endif endfunction +" Main prettier command function! prettier#Prettier(...) abort let l:execCmd = prettier#resolver#executable#getPath() let l:async = a:0 > 0 ? a:1 : 0 -- cgit v1.3-5-g45d5 From 4dfc50d5a689cf27d5915cbff8520388e517f0e5 Mon Sep 17 00:00:00 2001 From: mitermayer Date: Fri, 4 May 2018 12:51:14 -0700 Subject: Removing unused variable --- autoload/prettier.vim | 2 -- 1 file changed, 2 deletions(-) (limited to 'autoload/prettier.vim') diff --git a/autoload/prettier.vim b/autoload/prettier.vim index 63a72d2..0c52358 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -11,8 +11,6 @@ "========================================================================================================== " }}} -let s:prettier_job_running = 0 - " Displays the resolve prettier CLI path function! prettier#PrettierCliPath() abort let l:execCmd = prettier#resolver#executable#getPath() -- cgit v1.3-5-g45d5 From 866a7ac514ff70ce40476a792db2d979f6b20268 Mon Sep 17 00:00:00 2001 From: mitermayer Date: Fri, 4 May 2018 13:27:03 -0700 Subject: Adding neovim runner module --- autoload/prettier.vim | 89 ++++++++-------------------------- autoload/prettier/job/async/neovim.vim | 43 ++++++++++++++++ autoload/prettier/job/runner.vim | 2 +- 3 files changed, 65 insertions(+), 69 deletions(-) (limited to 'autoload/prettier.vim') diff --git a/autoload/prettier.vim b/autoload/prettier.vim index 0c52358..9be30f5 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -34,74 +34,6 @@ function! prettier#PrettierCli(user_input) abort endif endfunction -" Main prettier command -function! prettier#Prettier(...) abort - let l:execCmd = prettier#resolver#executable#getPath() - let l:async = a:0 > 0 ? a:1 : 0 - let l:startSelection = a:0 > 1 ? a:2 : 1 - let l:endSelection = a:0 > 2 ? a:3 : line('$') - let l:config = getbufvar(bufnr('%'), 'prettier_ft_default_args', {}) - - if l:execCmd != -1 - let l:cmd = l:execCmd . prettier#resolver#config#buildCliArgs(l:config) - - " close quickfix if it is opened - call prettier#utils#quickfix#close() - - if l:async && has('nvim') && g:prettier#nvim_unstable_async - call s:Prettier_Exec_Async_Nvim(l:cmd, l:startSelection, l:endSelection) - else - call prettier#job#runner#run(l:cmd, l:startSelection, l:endSelection, l:async) - endif - else - call prettier#logging#error#log('EXECUTABLE_NOT_FOUND_ERROR') - endif -endfunction - -function! s:Prettier_Exec_Async_Nvim(cmd, startSelection, endSelection) abort - let l:async_cmd = a:cmd - - if has('win32') || has('win64') - let l:async_cmd = 'cmd.exe /c ' . a:cmd - endif - - let l:lines = getline(a:startSelection, a:endSelection) - let l:dict = { - \ 'start': a:startSelection - 1, - \ 'end': a:endSelection, - \ 'buf_nr': bufnr('%'), - \ 'content': join(l:lines, "\n"), - \} - let l:out = [] - let l:err = [] - - let l:job = jobstart([&shell, &shellcmdflag, l:async_cmd], { - \ 'on_stdout': {job_id, data, event -> extend(l:out, data)}, - \ 'on_stderr': {job_id, data, event -> extend(l:err, data)}, - \ 'on_exit': {job_id, status, event -> s:Prettier_Job_Nvim_Exit(status, l:dict, l:out, l:err)}, - \ }) - call jobsend(l:job, l:lines) - call jobclose(l:job, 'stdin') -endfunction - -function! s:Prettier_Job_Nvim_Exit(status, info, out, err) abort - if a:status != 0 - echoerr join(a:err, "\n") - return - endif - - if len(a:out) == 0 | return | endif - - let l:last = a:out[len(a:out) - 1] - let l:out = l:last ==? '' ? a:out[0:len(a:out) - 2] : a:out - if a:info.content == join(l:out, "\n") - " no change - return - endif - - call nvim_buf_set_lines(a:info.buf_nr, a:info.start, a:info.end, 0, l:out) -endfunction - function! prettier#Autoformat(...) abort let l:curPos = getpos('.') let l:maxLineLookup = 50 @@ -129,3 +61,24 @@ function! prettier#Autoformat(...) abort " Restore search let @/=l:search endfunction + +" Main prettier command +function! prettier#Prettier(...) abort + let l:execCmd = prettier#resolver#executable#getPath() + let l:async = a:0 > 0 ? a:1 : 0 + let l:startSelection = a:0 > 1 ? a:2 : 1 + let l:endSelection = a:0 > 2 ? a:3 : line('$') + let l:config = getbufvar(bufnr('%'), 'prettier_ft_default_args', {}) + + if l:execCmd != -1 + let l:cmd = l:execCmd . prettier#resolver#config#buildCliArgs(l:config) + + " close quickfix if it is opened + call prettier#utils#quickfix#close() + + " format buffer + call prettier#job#runner#run(l:cmd, l:startSelection, l:endSelection, l:async) + else + call prettier#logging#error#log('EXECUTABLE_NOT_FOUND_ERROR') + endif +endfunction diff --git a/autoload/prettier/job/async/neovim.vim b/autoload/prettier/job/async/neovim.vim index e69de29..9844579 100644 --- a/autoload/prettier/job/async/neovim.vim +++ b/autoload/prettier/job/async/neovim.vim @@ -0,0 +1,43 @@ +function! prettier#job#async#neovim#run(cmd, startSelection, endSelection) abort + let l:async_cmd = a:cmd + + if has('win32') || has('win64') + let l:async_cmd = 'cmd.exe /c ' . a:cmd + endif + + let l:lines = getline(a:startSelection, a:endSelection) + let l:dict = { + \ 'start': a:startSelection - 1, + \ 'end': a:endSelection, + \ 'buf_nr': bufnr('%'), + \ 'content': join(l:lines, "\n"), + \} + let l:out = [] + let l:err = [] + + let l:job = jobstart([&shell, &shellcmdflag, l:async_cmd], { + \ 'on_stdout': {job_id, data, event -> extend(l:out, data)}, + \ 'on_stderr': {job_id, data, event -> extend(l:err, data)}, + \ 'on_exit': {job_id, status, event -> s:Prettier_Job_Nvim_Exit(status, l:dict, l:out, l:err)}, + \ }) + call jobsend(l:job, l:lines) + call jobclose(l:job, 'stdin') +endfunction + +function! s:Prettier_Job_Nvim_Exit(status, info, out, err) abort + if a:status != 0 + echoerr join(a:err, "\n") + return + endif + + if len(a:out) == 0 | return | endif + + let l:last = a:out[len(a:out) - 1] + let l:out = l:last ==? '' ? a:out[0:len(a:out) - 2] : a:out + if a:info.content == join(l:out, "\n") + " no change + return + endif + + call nvim_buf_set_lines(a:info.buf_nr, a:info.start, a:info.end, 0, l:out) +endfunction diff --git a/autoload/prettier/job/runner.vim b/autoload/prettier/job/runner.vim index b4b1f77..67cdb3c 100644 --- a/autoload/prettier/job/runner.vim +++ b/autoload/prettier/job/runner.vim @@ -27,7 +27,7 @@ function! s:asyncFormat(cmd, startSelection, endSelection) abort if s:isAsyncVim call prettier#job#async#vim#run(a:cmd, a:startSelection, a:endSelection) elseif s:isNeoVim - echom 'neovim' + call prettier#job#async#neovim#run(a:cmd, a:startSelection, a:endSelection) else call s:format(a:cmd, a:startSelection, a:endSelection) endif -- cgit v1.3-5-g45d5 From 51f1f8ed69c8106da665cfa46261caf9a6cbd728 Mon Sep 17 00:00:00 2001 From: mitermayer Date: Fri, 4 May 2018 14:00:00 -0700 Subject: Making sure only single job is executed at a time with neovim --- autoload/prettier.vim | 1 + autoload/prettier/job/async/neovim.vim | 18 +++++++++++++----- autoload/prettier/job/async/vim.vim | 23 +++++++++++++---------- 3 files changed, 27 insertions(+), 15 deletions(-) (limited to 'autoload/prettier.vim') diff --git a/autoload/prettier.vim b/autoload/prettier.vim index 9be30f5..c5e21e5 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -34,6 +34,7 @@ function! prettier#PrettierCli(user_input) abort endif endfunction +" Allows @format pragma support function! prettier#Autoformat(...) abort let l:curPos = getpos('.') let l:maxLineLookup = 50 diff --git a/autoload/prettier/job/async/neovim.vim b/autoload/prettier/job/async/neovim.vim index 9844579..b369406 100644 --- a/autoload/prettier/job/async/neovim.vim +++ b/autoload/prettier/job/async/neovim.vim @@ -1,8 +1,14 @@ +let s:prettier_job_running = 0 + function! prettier#job#async#neovim#run(cmd, startSelection, endSelection) abort - let l:async_cmd = a:cmd + if s:prettier_job_running == 1 + return + endif + + let l:cmd = a:cmd if has('win32') || has('win64') - let l:async_cmd = 'cmd.exe /c ' . a:cmd + let l:cmd = 'cmd.exe /c ' . a:cmd endif let l:lines = getline(a:startSelection, a:endSelection) @@ -15,16 +21,18 @@ function! prettier#job#async#neovim#run(cmd, startSelection, endSelection) abort let l:out = [] let l:err = [] - let l:job = jobstart([&shell, &shellcmdflag, l:async_cmd], { + let l:job = jobstart([&shell, &shellcmdflag, l:cmd], { \ 'on_stdout': {job_id, data, event -> extend(l:out, data)}, \ 'on_stderr': {job_id, data, event -> extend(l:err, data)}, - \ 'on_exit': {job_id, status, event -> s:Prettier_Job_Nvim_Exit(status, l:dict, l:out, l:err)}, + \ 'on_exit': {job_id, status, event -> s:onExit(status, l:dict, l:out, l:err)}, \ }) call jobsend(l:job, l:lines) call jobclose(l:job, 'stdin') endfunction -function! s:Prettier_Job_Nvim_Exit(status, info, out, err) abort +function! s:onExit(status, info, out, err) abort + let s:prettier_job_running = 0 + if a:status != 0 echoerr join(a:err, "\n") return diff --git a/autoload/prettier/job/async/vim.vim b/autoload/prettier/job/async/vim.vim index 4db6522..ef9e37d 100644 --- a/autoload/prettier/job/async/vim.vim +++ b/autoload/prettier/job/async/vim.vim @@ -1,6 +1,12 @@ let s:prettier_job_running = 0 function! prettier#job#async#vim#run(cmd, startSelection, endSelection) abort + if s:prettier_job_running == 1 + return + endif + + let s:prettier_job_running = 1 + let l:cmd = a:cmd if has('win32') || has('win64') @@ -9,16 +15,13 @@ function! prettier#job#async#vim#run(cmd, startSelection, endSelection) abort let l:bufferName = bufname('%') - if s:prettier_job_running != 1 - let s:prettier_job_running = 1 - call job_start([&shell, &shellcmdflag, l:cmd], { - \ 'in_io': 'buffer', - \ 'in_top': a:startSelection, - \ 'in_bot': a:endSelection, - \ 'in_name': l:bufferName, - \ 'err_cb': {channel, msg -> s:onError(msg)}, - \ 'close_cb': {channel -> s:onClose(channel, a:startSelection, a:endSelection, l:bufferName)}}) - endif + call job_start([&shell, &shellcmdflag, l:cmd], { + \ 'in_io': 'buffer', + \ 'in_top': a:startSelection, + \ 'in_bot': a:endSelection, + \ 'in_name': l:bufferName, + \ 'err_cb': {channel, msg -> s:onError(msg)}, + \ 'close_cb': {channel -> s:onClose(channel, a:startSelection, a:endSelection, l:bufferName)}}) endfunction function! s:onError(msg) abort -- cgit v1.3-5-g45d5 From 98845cdbbe243f4a62adbd73cbe7febec1f41efa Mon Sep 17 00:00:00 2001 From: mitermayer Date: Thu, 10 May 2018 13:36:09 -0700 Subject: Adding presets - adding facebook presets as a configurable option to overwrite prettier defaults --- autoload/prettier.vim | 2 +- autoload/prettier/presets/fb.vim | 13 +++++++++++++ autoload/prettier/resolver/config.vim | 14 ++++++++++++++ autoload/prettier/resolver/preset.vim | 8 ++++++++ plugin/prettier.vim | 34 ++++++++++++++++++++++++++++++++-- 5 files changed, 68 insertions(+), 3 deletions(-) create mode 100644 autoload/prettier/presets/fb.vim create mode 100644 autoload/prettier/resolver/preset.vim (limited to 'autoload/prettier.vim') diff --git a/autoload/prettier.vim b/autoload/prettier.vim index c5e21e5..fae1ef8 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -72,7 +72,7 @@ function! prettier#Prettier(...) abort let l:config = getbufvar(bufnr('%'), 'prettier_ft_default_args', {}) if l:execCmd != -1 - let l:cmd = l:execCmd . prettier#resolver#config#buildCliArgs(l:config) + let l:cmd = l:execCmd . prettier#resolver#config#buildCliArgs(prettier#resolver#preset#build(l:config)) " close quickfix if it is opened call prettier#utils#quickfix#close() diff --git a/autoload/prettier/presets/fb.vim b/autoload/prettier/presets/fb.vim new file mode 100644 index 0000000..4715b88 --- /dev/null +++ b/autoload/prettier/presets/fb.vim @@ -0,0 +1,13 @@ +" Return facebook style config overwrite presets +function! prettier#presets#fb#config() abort + return { + \ 'bracketSpacing': 'false', + \ 'jsxBracketSameLine': 'true', + \ 'printWidth': 80, + \ 'parser': 'flow', + \ 'singleQuote': 'true', + \ 'tabWidth': 2, + \ 'trailingComma': 'all', + \ 'useTabs': 'false', + \ } +endfunction diff --git a/autoload/prettier/resolver/config.vim b/autoload/prettier/resolver/config.vim index ffdd8ff..91fc247 100644 --- a/autoload/prettier/resolver/config.vim +++ b/autoload/prettier/resolver/config.vim @@ -8,6 +8,18 @@ function! prettier#resolver#config#buildCliArgs(config) abort \ s:Flag_tab_width(a:config) . ' ' . \ s:Flag_print_width(a:config) . ' ' . \ s:Flag_parser(a:config) . ' ' . + \ ' --semi=' . + \ get(a:config, 'semi', g:prettier#config#semi) . + \ ' --single-quote=' . + \ get(a:config, 'singleQuote', g:prettier#config#single_quote) . + \ ' --bracket-spacing=' . + \ get(a:config, 'bracketSpacing', g:prettier#config#bracket_spacing) . + \ ' --jsx-bracket-same-line=' . + \ get(a:config, 'jsxBracketSameLine', g:prettier#config#jsx_bracket_same_line) . + \ ' --arrow-parens=' . + \ get(a:config, 'arrowParens', g:prettier#config#arrow_parens) . + \ ' --trailing-comma=' . + \ get(a:config, 'trailingComma', g:prettier#config#trailing_comma) . \ ' --config-precedence=' . \ get(a:config, 'configPrecedence', g:prettier#config#config_precedence) . \ ' --prose-wrap=' . @@ -17,6 +29,8 @@ function! prettier#resolver#config#buildCliArgs(config) abort \ ' --no-editorconfig '. \ ' --loglevel error '. \ ' --stdin ' + " TODO + " check to see if --no-editorconfig is still needed return l:cmd endfunction diff --git a/autoload/prettier/resolver/preset.vim b/autoload/prettier/resolver/preset.vim new file mode 100644 index 0000000..a0891d2 --- /dev/null +++ b/autoload/prettier/resolver/preset.vim @@ -0,0 +1,8 @@ +" Build config using predefined preset +function! prettier#resolver#preset#build(fileTypeConfigOverwrites) abort + if ( g:prettier#preset#config ==# 'fb' ) + return extend(prettier#presets#fb#config(), a:fileTypeConfigOverwrites) + endif + + return a:fileTypeConfigOverwrites +endfunction diff --git a/plugin/prettier.vim b/plugin/prettier.vim index 5de9caf..2bb5a39 100644 --- a/plugin/prettier.vim +++ b/plugin/prettier.vim @@ -29,6 +29,13 @@ let g:prettier#exec_cmd_async = get(g:, 'prettier#exec_cmd_async', 0) " when having formatting errors will open the quickfix by default let g:prettier#quickfix_enabled = get(g:, 'prettier#quickfix_enabled', 1) +" Don't leave the quicklist focused on error. +let g:prettier#quickfix_auto_focus = get(g:, 'prettier#quickfix_auto_focus', 1) + +" default|fb +" Use prettier defaults +let g:prettier#preset#config = get(g:,'prettier#preset#config', 'default') + " => Prettier CLI config " Max line length that prettier will wrap on: a number or 'auto' (use " textwidth). @@ -57,8 +64,31 @@ let g:prettier#config#config_precedence = get(g:, 'prettier#config#config_preced " default: 'preserve' let g:prettier#config#prose_wrap = get(g:, 'prettier#config#prose_wrap', 'preserve') -" Don't leave the quicklist focused on error. -let g:prettier#quickfix_auto_focus = get(g:, 'prettier#quickfix_auto_focus', 1) +" print semicolons +" default: 'true' +let g:prettier#config#semi = get(g:,'prettier#config#semi', 'true') + +" Use single quotes instead of double quotes. +" default: 'false' +let g:prettier#config#single_quote = get(g:,'prettier#config#single_quote', 'false') + +" print spaces between brackets +" default: 'true' +let g:prettier#config#bracket_spacing = get(g:,'prettier#config#bracket_spacing', 'true') + +" put > on the last line instead of new line +" default: 'false' +let g:prettier#config#jsx_bracket_same_line = get(g:,'prettier#config#jsx_bracket_same_line', 'false') + +" avoid wrapping a single arrow function param in parens +" avoid|always +" default: 'avoid' +let g:prettier#config#arrow_parens = get(g:,'prettier#config#arrow_parens', 'avoid') + +" Print trailing commas wherever possible when multi-line. +" none|es5|all +" default: 'none' +let g:prettier#config#trailing_comma = get(g:,'prettier#config#trailing_comma', 'none') " synchronous by default command! -nargs=? -range=% Prettier call prettier#Prettier(g:prettier#exec_cmd_async, , ) -- cgit v1.3-5-g45d5 From ec6ede90f3b9948ed7063402189653f8d6721326 Mon Sep 17 00:00:00 2001 From: mitermayer Date: Mon, 28 May 2018 20:53:30 -0700 Subject: Enabling partial formatting but still maintaining support for fragment formatting --- README.md | 2 +- autoload/prettier.vim | 18 +++++++++++++++++- autoload/prettier/resolver/config.vim | 14 +++++++++++++- autoload/prettier/resolver/preset.vim | 2 +- autoload/prettier/utils/buffer.vim | 21 +++++++++++++++++++++ plugin/prettier.vim | 15 +++++++++++++-- 6 files changed, 66 insertions(+), 6 deletions(-) (limited to 'autoload/prettier.vim') diff --git a/README.md b/README.md index 442a821..d0ec620 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ By default it will auto format **javascript**, **typescript**, **less**, **scss**, **css**, **json**, **graphql** and **markdown** files if they have/support the "@format" pragma annotation in the header of the file. -![vim-prettier](/media/vim-prettier.gif?raw=true "vim-prettier") +![vim-prettier](/media/vim-prettier.gif?raw=true 'vim-prettier') ### INSTALL diff --git a/autoload/prettier.vim b/autoload/prettier.vim index fae1ef8..0e8ade3 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -69,14 +69,30 @@ function! prettier#Prettier(...) abort let l:async = a:0 > 0 ? a:1 : 0 let l:startSelection = a:0 > 1 ? a:2 : 1 let l:endSelection = a:0 > 2 ? a:3 : line('$') + let l:hasSelection = a:0 > 2 ? 1 : 0 + let l:partialFormat = a:0 > 3 && a:4 ? a:4 : 0 let l:config = getbufvar(bufnr('%'), 'prettier_ft_default_args', {}) + let l:partialFormatEnabled = l:hasSelection && l:partialFormat if l:execCmd != -1 - let l:cmd = l:execCmd . prettier#resolver#config#buildCliArgs(prettier#resolver#preset#build(l:config)) + " TODO + " => we should make sure we can resolve --range-start and --range-end when required + " => when the above is required we should also update l:startSelection to '1' and l:endSelection to line('$') + let l:cmd = l:execCmd . prettier#resolver#config#resolve( + \ prettier#resolver#preset#resolve(l:config), + \ l:partialFormatEnabled, + \ l:startSelection, + \ l:endSelection) " close quickfix if it is opened call prettier#utils#quickfix#close() + " we will be using portion formatting, so we need to send entire buffer to prettier + if l:partialFormatEnabled + let l:startSelection = 1 + let l:endSelection = line('$') + endif + " format buffer call prettier#job#runner#run(l:cmd, l:startSelection, l:endSelection, l:async) else diff --git a/autoload/prettier/resolver/config.vim b/autoload/prettier/resolver/config.vim index 91fc247..eae6725 100644 --- a/autoload/prettier/resolver/config.vim +++ b/autoload/prettier/resolver/config.vim @@ -1,6 +1,6 @@ " By default we will default to our internal " configuration settings for prettier -function! prettier#resolver#config#buildCliArgs(config) abort +function! prettier#resolver#config#resolve(config, hasSelection, start, end) abort " Allow params to be passed as json format " convert bellow usage of globals to a get function o the params defaulting to global " TODO: Use a list, filter() and join() to get a nicer list of args. @@ -8,6 +8,7 @@ function! prettier#resolver#config#buildCliArgs(config) abort \ s:Flag_tab_width(a:config) . ' ' . \ s:Flag_print_width(a:config) . ' ' . \ s:Flag_parser(a:config) . ' ' . + \ s:Flag_range_delimiter(a:config, a:hasSelection, a:start, a:end) . ' ' . \ ' --semi=' . \ get(a:config, 'semi', g:prettier#config#semi) . \ ' --single-quote=' . @@ -34,6 +35,17 @@ function! prettier#resolver#config#buildCliArgs(config) abort return l:cmd endfunction +" Returns either '--range-start X --range-end Y' or an empty string. +function! s:Flag_range_delimiter(config, partialFormatEnabled, start, end) abort + if (!a:partialFormatEnabled) + return '' + endif + + let l:range = prettier#utils#buffer#getCharRange(a:start, a:end) + + return '--range-start=' . l:range[0] . ' --range-end=' . l:range[1] +endfunction + " Returns '--tab-width=NN' function! s:Flag_tab_width(config) abort let l:value = get(a:config, 'tabWidth', g:prettier#config#tab_width) diff --git a/autoload/prettier/resolver/preset.vim b/autoload/prettier/resolver/preset.vim index a0891d2..03f98ee 100644 --- a/autoload/prettier/resolver/preset.vim +++ b/autoload/prettier/resolver/preset.vim @@ -1,5 +1,5 @@ " Build config using predefined preset -function! prettier#resolver#preset#build(fileTypeConfigOverwrites) abort +function! prettier#resolver#preset#resolve(fileTypeConfigOverwrites) abort if ( g:prettier#preset#config ==# 'fb' ) return extend(prettier#presets#fb#config(), a:fileTypeConfigOverwrites) endif diff --git a/autoload/prettier/utils/buffer.vim b/autoload/prettier/utils/buffer.vim index 1e11ddb..0b3c619 100644 --- a/autoload/prettier/utils/buffer.vim +++ b/autoload/prettier/utils/buffer.vim @@ -33,3 +33,24 @@ endfunction function! prettier#utils#buffer#createBufferFromUpdatedLines(lines, start, end) abort return getbufline(bufnr('%'), 1, a:start - 1) + a:lines + getbufline(bufnr('%'), a:end + 1, '$') endfunction + +" Adapted from https://github.com/farazdagi/vim-go-ide +function! s:getCharPosition(line, col) + if &encoding !=# 'utf-8' + " On utf-8 enconding we can't just use bytes so we need to make sure we can count the + " characters, we do that by adding the text into a temporary buffer and counting the chars + let l:buf = a:line == 1 ? '' : (join(getline(1, a:line - 1), "\n") . "\n") + let l:buf .= a:col == 1 ? '' : getline('.')[:a:col - 2] + return len(iconv(l:buf, &encoding, 'utf-8')) + endif + " On non utf-8 the line byte should match the character + return line2byte(a:line) + (a:col - 2) +endfun + +" Returns [start, end] byte range when on visual mode +function! prettier#utils#buffer#getCharRange(startSelection, endSelection) abort + let l:range = [] + call add(l:range, s:getCharPosition(a:startSelection, col("'<"))) + call add(l:range, s:getCharPosition(a:endSelection, col("'>"))) + return l:range +endfunction diff --git a/plugin/prettier.vim b/plugin/prettier.vim index 2bb5a39..4a3db64 100644 --- a/plugin/prettier.vim +++ b/plugin/prettier.vim @@ -32,6 +32,9 @@ let g:prettier#quickfix_enabled = get(g:, 'prettier#quickfix_enabled', 1) " Don't leave the quicklist focused on error. let g:prettier#quickfix_auto_focus = get(g:, 'prettier#quickfix_auto_focus', 1) +" Send to prettier entire buffer and use --range-start and --range-end as delimter +let g:prettier#partial_format = get(g:, 'prettier#partial_format', 0) + " default|fb " Use prettier defaults let g:prettier#preset#config = get(g:,'prettier#preset#config', 'default') @@ -91,10 +94,10 @@ let g:prettier#config#arrow_parens = get(g:,'prettier#config#arrow_parens', 'avo let g:prettier#config#trailing_comma = get(g:,'prettier#config#trailing_comma', 'none') " synchronous by default -command! -nargs=? -range=% Prettier call prettier#Prettier(g:prettier#exec_cmd_async, , ) +command! -nargs=? -range=% Prettier call prettier#Prettier(g:prettier#exec_cmd_async, , , g:prettier#partial_format) " prettier async -command! -nargs=? -range=% PrettierAsync call prettier#Prettier(1, , ) +command! -nargs=? -range=% PrettierAsync call prettier#Prettier(1, , , g:prettier#partial_format) " prints vim-prettier version command! -nargs=? -range=% PrettierVersion echom '0.2.6' @@ -108,12 +111,20 @@ command! -nargs=? -range=% PrettierCliVersion call prettier#PrettierCli('--versi " prints prettier resolved cli path command! -nargs=? -range=% PrettierCliPath call prettier#PrettierCliPath() +" sends selected text to prettier cli for formatting +command! -nargs=? -range=% PrettierFragment call prettier#Prettier(g:prettier#exec_cmd_async, , , 0) + +" sends entire buffer to prettier cli but format just selection +command! -nargs=? -range=% PrettierPartial call prettier#Prettier(g:prettier#exec_cmd_async, , , 1) + " map command if !hasmapto('(Prettier)') && maparg('p', 'n') ==# '' nmap p (Prettier) endif nnoremap (Prettier) :Prettier nnoremap (PrettierAsync) :PrettierAsync +nnoremap (PrettierFragment) :PrettierFragment +nnoremap (PrettierPartial) :PrettierPartial nnoremap (PrettierVersion) :PrettierVersion nnoremap (PrettierCli) :PrettierCli nnoremap (PrettierCliVersion) :PrettierCliVersion -- cgit v1.3-5-g45d5 From be9d60045f40928f425937e62ec1b8fbf3601b4a Mon Sep 17 00:00:00 2001 From: mitermayer Date: Mon, 5 Nov 2018 12:28:45 -0800 Subject: Bumping 1.0 tag to alpha --- autoload/prettier.vim | 2 +- doc/prettier.txt | 2 +- package.json | 2 +- plugin/prettier.vim | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) (limited to 'autoload/prettier.vim') diff --git a/autoload/prettier.vim b/autoload/prettier.vim index e2ba919..3241f48 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -5,7 +5,7 @@ " Name Of File: prettier.vim " Description: A vim plugin wrapper for prettier, pre-configured with custom default prettier settings. " Maintainer: Mitermayer Reis -" Version: 0.2.7 +" Version: 1.0.0-alpha " Usage: Use :help vim-prettier-usage, or visit https://github.com/prettier/vim-prettier " "========================================================================================================== diff --git a/doc/prettier.txt b/doc/prettier.txt index db4223d..3760ca7 100644 --- a/doc/prettier.txt +++ b/doc/prettier.txt @@ -8,7 +8,7 @@ Author: Mitermayer Reis WebSite: https://prettier.io/ Repository: https://github.com/prettier/vim-prettier License: MIT style license -Version: 0.2.7 +Version: 1.0.0-alpha ============================================================================== CONTENTS *vim-prettier-contents* diff --git a/package.json b/package.json index 901597e..cc35f7c 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "vim-prettier", "author": "Mitermayer Reis ", - "version": "0.2.7", + "version": "1.0.0-alpha", "description": "Vim plugin for prettier", "license": "MIT", "repository": { diff --git a/plugin/prettier.vim b/plugin/prettier.vim index 4bb0773..bad2ab0 100644 --- a/plugin/prettier.vim +++ b/plugin/prettier.vim @@ -5,7 +5,7 @@ " Name Of File: prettier.vim " Description: A vim plugin wrapper for prettier, pre-configured with custom default prettier settings. " Maintainer: Mitermayer Reis -" Version: 0.2.7 +" Version: 1.0.0-alpha " Usage: Use :help vim-prettier-usage, or visit https://github.com/prettier/vim-prettier " "========================================================================================================== @@ -100,7 +100,7 @@ command! -nargs=? -range=% Prettier call prettier#Prettier(g:prettier#exec_cmd_a command! -nargs=? -range=% PrettierAsync call prettier#Prettier(1, , , g:prettier#partial_format) " prints vim-prettier version -command! -nargs=? -range=% PrettierVersion echom '0.2.7' +command! -nargs=? -range=% PrettierVersion echom '1.0.0-alpha' " call prettier cli command! -nargs=? -range=% PrettierCli call prettier#PrettierCli() -- cgit v1.3-5-g45d5 From 3dc6684302ff2749570d938e1d49862db0e2648c Mon Sep 17 00:00:00 2001 From: mitermayer Date: Fri, 13 Sep 2019 21:38:53 +0000 Subject: issues/184-fixing-undo-step - Removing previous naive implementation of requirePragma - This commit ensures that we use `prettier` default way to identify pragmas for the auto save and remove our previous naive implementation --- autoload/prettier.vim | 33 ++++++--------------------------- ftplugin/html.vim | 7 ------- plugin/prettier.vim | 7 +++++++ 3 files changed, 13 insertions(+), 34 deletions(-) (limited to 'autoload/prettier.vim') diff --git a/autoload/prettier.vim b/autoload/prettier.vim index 3241f48..e66f4b7 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -34,33 +34,9 @@ function! prettier#PrettierCli(user_input) abort endif endfunction -" Allows @format pragma support +" Allows @format and @prettier pragma support upon saving function! prettier#Autoformat(...) abort - let l:curPos = getpos('.') - let l:maxLineLookup = 50 - let l:maxTimeLookupMs = 500 - let l:pattern = '@format' - let l:search = @/ - let l:winview = winsaveview() - - " we need to move selection to the top before looking up to avoid - " scanning a very long file - call cursor(1, 1) - - " Search starting at the start of the document - if search(l:pattern, 'n', l:maxLineLookup, l:maxTimeLookupMs) > 0 - " autoformat async - call prettier#Prettier(1) - endif - - " Restore the selection and if greater then before it defaults to end - call cursor(l:curPos[1], l:curPos[2]) - - " Restore view - call winrestview(l:winview) - - " Restore search - let @/=l:search + call prettier#Prettier(1, 1, line('$'), 0, { 'requirePragma': 'true'}) endfunction " Main prettier command @@ -71,9 +47,12 @@ function! prettier#Prettier(...) abort let l:endSelection = a:0 > 2 ? a:3 : line('$') let l:hasSelection = a:0 > 2 ? 1 : 0 let l:partialFormat = a:0 > 3 && a:4 ? a:4 : 0 - let l:config = getbufvar(bufnr('%'), 'prettier_ft_default_args', {}) let l:partialFormatEnabled = l:hasSelection && l:partialFormat + let l:overWrite = a:0 > 4 ? a:5 : {} + let l:bufferConfig = getbufvar(bufnr('%'), 'prettier_ft_default_args', {}) + let l:config = extend(l:bufferConfig, l:overWrite) + if l:execCmd != -1 " TODO " => we should make sure we can resolve --range-start and --range-end when required diff --git a/ftplugin/html.vim b/ftplugin/html.vim index d2f059d..58ab258 100644 --- a/ftplugin/html.vim +++ b/ftplugin/html.vim @@ -5,10 +5,3 @@ if &filetype !~# 'markdown' \ 'parser': 'html', \ } endif - -augroup Prettier - autocmd! - if g:prettier#autoformat - autocmd BufWritePre *.html call prettier#Autoformat() - endif -augroup end diff --git a/plugin/prettier.vim b/plugin/prettier.vim index d3bee5a..aafa7a2 100644 --- a/plugin/prettier.vim +++ b/plugin/prettier.vim @@ -136,3 +136,10 @@ nnoremap (PrettierVersion) :PrettierVersion nnoremap (PrettierCli) :PrettierCli nnoremap (PrettierCliVersion) :PrettierCliVersion nnoremap (PrettierCliPath) :PrettierCliPath + +augroup Prettier + autocmd! + if g:prettier#autoformat + autocmd BufWritePre *.js,*.jsx,*.mjs,*.ts,*.tsx,*.css,*.less,*.scss,*.json,*.graphql,*.md,*.vue,*.yaml,*.html call prettier#Autoformat() + endif +augroup end -- cgit v1.3-5-g45d5 From 41d9c4778a8dc0439afee9c9000d7fa5b4b8be17 Mon Sep 17 00:00:00 2001 From: Adam Macumber Date: Wed, 9 Oct 2019 15:44:55 -0400 Subject: Toggle the autoformat setting based on config file presence. --- autoload/prettier.vim | 10 ++++++++++ plugin/prettier.vim | 21 +++++++++++++++++++++ 2 files changed, 31 insertions(+) (limited to 'autoload/prettier.vim') diff --git a/autoload/prettier.vim b/autoload/prettier.vim index e66f4b7..f55fb21 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -78,3 +78,13 @@ function! prettier#Prettier(...) abort call prettier#logging#error#log('EXECUTABLE_NOT_FOUND_ERROR') endif endfunction + +" Set autoformat toggle based on whether config file was found. +function! prettier#IsConfigPresent(config_files) + for config_file in a:config_files + if filereadable(findfile(config_file, '.;')) + return 1 + endif + endfor + return 0 +endfunction diff --git a/plugin/prettier.vim b/plugin/prettier.vim index 83656d3..4ffa9cb 100644 --- a/plugin/prettier.vim +++ b/plugin/prettier.vim @@ -20,6 +20,19 @@ let g:loaded_prettier = 1 " autoformating disabled by default upon saving let g:prettier#autoformat = get(g:, 'prettier#autoformat', 0) +" whether to turn autoformatting on if a prettier config file is found +let g:prettier#autoformat_config_present = get(g:, 'prettier#autoformat_config_present', 0) + +" prettier config files to search current directory and parent directories for +let g:prettier#autoformat_config_files = get(g:, 'prettier#autoformat_config_files', [ + \'.prettierrc', + \'.prettierrc.yml', + \'.prettierrc.yaml', + \'.prettierrc.js', + \'.prettierrc.config.js', + \'.prettierrc.json' + \'.prettierrc.toml']) + " path to prettier cli let g:prettier#exec_cmd_path = get(g:, 'prettier#exec_cmd_path', 0) @@ -139,6 +152,14 @@ nnoremap (PrettierCliPath) :PrettierCliPath augroup Prettier autocmd! + if g:prettier#autoformat_config_present + if prettier#IsConfigPresent(g:prettier#autoformat_config_files) + let g:prettier#autoformat = 1 + else + let g:prettier#autoformat = 0 + endif + endif + if g:prettier#autoformat autocmd BufWritePre *.js,*.jsx,*.mjs,*.ts,*.tsx,*.css,*.less,*.scss,*.json,*.graphql,*.md,*.vue,*.yaml,*.html noautocmd | call prettier#Autoformat() endif -- cgit v1.3-5-g45d5 From 59c4644692e10613b78e8746fe0832d33a2e1216 Mon Sep 17 00:00:00 2001 From: Atom Mac Date: Sun, 13 Oct 2019 09:51:05 -0400 Subject: Fix linting issue: autoloaded func needed 'abort' --- autoload/prettier.vim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'autoload/prettier.vim') diff --git a/autoload/prettier.vim b/autoload/prettier.vim index f55fb21..d4c3171 100644 --- a/autoload/prettier.vim +++ b/autoload/prettier.vim @@ -80,7 +80,7 @@ function! prettier#Prettier(...) abort endfunction " Set autoformat toggle based on whether config file was found. -function! prettier#IsConfigPresent(config_files) +function! prettier#IsConfigPresent(config_files) abort for config_file in a:config_files if filereadable(findfile(config_file, '.;')) return 1 -- cgit v1.3-5-g45d5