|
19 | 19 | -- @module format |
20 | 20 | local M = {} |
21 | 21 |
|
22 | | ---- Helper function that returns whether or not the given config file exists in the current or |
23 | | --- a parent directory of the current buffer's filename. |
24 | | -local function has_config_file(filename) |
| 22 | +--- Returns whether or not the given config file exists in the current or a parent directory of |
| 23 | +-- the current buffer's filename. |
| 24 | +-- Also returns the config file's filename. |
| 25 | +-- @param filename String config filename. |
| 26 | +function M.config_file_exists(filename) |
25 | 27 | if not buffer.filename then return false end |
26 | 28 | local dir = buffer.filename:match('^(.+)[/\\]') |
27 | 29 | while dir do |
28 | | - if lfs.attributes(dir .. '/' .. filename) then return true end |
| 30 | + local config_file = dir .. '/' .. filename |
| 31 | + if lfs.attributes(config_file) then return true, config_file end |
29 | 32 | dir = dir:match('^(.+)[/\\]') |
30 | 33 | end |
31 | | - return false |
| 34 | + return false, nil |
| 35 | +end |
| 36 | + |
| 37 | +--- Returns whether or not the given config file exists in the current or a parent directory of |
| 38 | +-- the current buffer's filename, and whether or not it contains the given text. |
| 39 | +-- @param filename String config filename. |
| 40 | +-- @param text String text to look for. |
| 41 | +function M.config_file_contains(filename, text) |
| 42 | + local exists, config_file = M.config_file_exists(filename) |
| 43 | + if not exists then return false end |
| 44 | + local f<close> = io.open(filename) |
| 45 | + return f:read('a'):find(text, 1, true) ~= nil |
32 | 46 | end |
33 | 47 |
|
34 | 48 | --- Map of lexer languages to string code formatter commands or functions that return such |
35 | 49 | -- commands. |
36 | 50 | M.commands = { |
37 | | - lua = function() return has_config_file('.lua-format') and 'lua-format' or nil end, |
38 | | - cpp = function() return has_config_file('.clang-format') and 'clang-format -style=file' or nil end, |
| 51 | + lua = function() return M.config_file_exists('.lua-format') and 'lua-format' or nil end, |
| 52 | + cpp = function() |
| 53 | + return M.config_file_exists('.clang-format') and 'clang-format -style=file' or nil |
| 54 | + end, -- |
39 | 55 | go = 'gofmt', dart = 'dart format' |
40 | 56 | } |
41 | 57 | M.commands.c = M.commands.cpp |
|
0 commit comments