aboutsummaryrefslogtreecommitdiff
path: root/plugins/editorconfig/init.lua
blob: 99dd57d5f5bec6bd2cf242373b0d7dc693491ebd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
-- mod-version:3.1
--
-- EditorConfig plugin for Pragtical
-- @copyright Jefferson Gonzalez <jgmdev@gmail.com>
-- @license MIT
--
-- Note: this plugin needs to be loaded after detectindent plugin,
-- since the name editorconfig.lua is ordered after detectindent.lua
-- there shouldn't be any issues. Just a reminder for the future in
-- case of a plugin that could also handle document identation type
-- and size, and has a name with more weight than this plugin.
--
local core = require "core"
local common = require "core.common"
local config = require "core.config"
local trimwhitespace = require "plugins.trimwhitespace"
local Doc = require "core.doc"
local Parser = require "plugins.editorconfig.parser"

---@class config.plugins.editorconfig
---@field debug boolean
---@field fallback_path string
config.plugins.editorconfig = common.merge({
  debug = false,
  fallback_path = nil,
  -- The config specification used by the settings gui
  config_spec = {
    name = "EditorConfig",
    {
      label = "Debug",
      description = "Display debugging messages on the log.",
      path = "debug",
      type = "toggle",
      default = false
    },
    {
      label = "Fallback Config Path",
      description = "Path to a fallback .editorconfig if none is found in the project.",
      path = "fallback_path",
      type = "file",
      default = nil
    }
  }
}, config.plugins.editorconfig)

---Cache of .editorconfig options to reduce parsing for every opened file.
---@type table<string, plugins.editorconfig.parser>
local project_configs = {}

---Keep track of main project directory so when changed we can assign a new
---.editorconfig object if neccesary.
---@type string
local main_project = core.root_project().path

---Functionality that will be exposed by the plugin.
---@class plugins.editorconfig
local editorconfig = {}

---Load global .editorconfig options for a project.
---@param project_dir string
---@return boolean loaded
function editorconfig.load(project_dir)
  local editor_config = project_dir .. "/" .. ".editorconfig"
  local file = io.open(editor_config)
  if file then
    file:close()
    project_configs[project_dir] = Parser.new(editor_config)
    return true
  end
  return false
end

---Helper to add or substract final new line, it also makes final new line
---visible which pragtical does not.
---@param doc core.doc
---@param raw? boolean If true does not register change on undo stack
---@return boolean handled_new_line
local function handle_final_new_line(doc, raw)
  local handled = false
  ---@diagnostic disable-next-line
  if doc.insert_final_newline then
    handled = true
    if doc.lines[#doc.lines] ~= "\n" then
      if not raw then
        doc:insert(#doc.lines, math.huge, "\n")
      else
        table.insert(doc.lines, "\n")
      end
    end
  ---@diagnostic disable-next-line
  elseif type(doc.insert_final_newline) == "boolean" then
    handled = true
    if trimwhitespace.trim_empty_end_lines then
      trimwhitespace.trim_empty_end_lines(doc, raw)
    -- TODO: remove this once 2.1.1 is released
    else
      for _=#doc.lines, 1, -1 do
        local l = #doc.lines
        if l > 1 and doc.lines[l] == "\n" then
          local current_line = doc:get_selection()
          if current_line == l then
            doc:set_selection(l-1, math.huge, l-1, math.huge)
          end
          if not raw then
            doc:remove(l-1, math.huge, l, math.huge)
          else
            table.remove(doc.lines, l)
          end
        end
      end
    end
  end
  return handled
end

---Split the given relative path by / or \ separators.
---@param path string The path to split
---@return table
local function split_path(path)
  local result = {};
  for match in (path.."/"):gmatch("(.-)".."[\\/]") do
    table.insert(result, match);
  end
  return result;
end

---Check if the given file path exists.
---@param file_path string
local function file_exists(file_path)
  local file = io.open(file_path, "r")
  if not file then return false end
  file:close()
  return true
end

---Merge a config options to target if they don't already exists on target.
---@param config_target? plugins.editorconfig.parser.section
---@param config_from? plugins.editorconfig.parser.section
local function merge_config(config_target, config_from)
  if config_target and config_from then
    for name, value in pairs(config_from) do
      if type(config_target[name]) == "nil" then
        config_target[name] = value
      end
    end
  end
end

---Scan for .editorconfig files from current file path to upper project path
---if root attribute is not found first and returns matching config.
---@param file_path string
---@return plugins.editorconfig.parser.section?
local function recursive_get_config(file_path)
  local project_dir = ""

  local root_config
	local has_config = false
  for path, editor_config in pairs(project_configs) do
    if common.path_belongs_to(file_path, path) then
      project_dir = path
      has_config = true
      root_config = editor_config:getConfig(
        common.relative_path(path, file_path)
      )
      break
    end
  end

  if project_dir == "" then
    for _, project in ipairs(core.projects) do
      if common.path_belongs_to(file_path, project.path) then
        project_dir = project.path
        break
      end
    end
  end

  local relative_file_path = common.relative_path(project_dir, file_path)
  local dir = common.dirname(relative_file_path)

  local editor_config = {}
  local config_found = false
  if not dir and root_config then
    editor_config = root_config
    config_found = true
  elseif dir then
    local path_list = split_path(dir)
    local root_found = false
    for p=#path_list, 1, -1 do
      local path = project_dir .. "/" .. table.concat(path_list, "/", 1, p)
      if file_exists(path .. "/" .. ".editorconfig") then
        ---@type plugins.editorconfig.parser
        local parser = Parser.new(path .. "/" .. ".editorconfig")
        local pconfig = parser:getConfig(common.relative_path(path, file_path))
        if pconfig then
          merge_config(editor_config, pconfig)
          config_found = true
          has_config = true
        end
        if parser.root then
          root_found = true
          has_config = true
          break
        end
      end
    end
    if not root_found and root_config then
      merge_config(editor_config, root_config)
      config_found = true
    end
  end

  if not config_found and not has_config then
    local fallback_path = config.plugins.editorconfig.fallback_path
    if fallback_path and fallback_path ~= "" then
      if file_exists(fallback_path) then
        local parser = Parser.new(fallback_path)
        local fallback_config_options = parser:getConfig(relative_file_path)
        if fallback_config_options then
          editor_config = fallback_config_options
          config_found = true
          core.log_quiet("[EditorConfig]: using fallback %s", fallback_path)
        end
      end
    end
  end

  -- clean unset options
  if config_found then
    local all_unset = true
    for name, value in pairs(editor_config) do
      if value == "unset" then
        editor_config[name] = nil
      else
        all_unset = false
      end
    end
    if all_unset then config_found = false end
  end

  return config_found and editor_config or nil
end

---Apply editorconfig rules to given doc if possible.
---@param doc core.doc
function editorconfig.apply(doc)
  if not doc.abs_filename and not doc.filename then return end
  local file_path = doc.abs_filename or (main_project .. "/" .. doc.filename)
  local options = recursive_get_config(file_path)
  if options then
    if config.plugins.editorconfig.debug then
      core.log_quiet(
        "[EditorConfig]: %s applied %s",
        file_path, common.serialize(options, {pretty = true})
      )
    end
    local indent_type, indent_size = doc:get_indent_info()
    if options.indent_style then
      if options.indent_style == "tab" then
        indent_type = "hard"
      else
        indent_type = "soft"
      end
    end

    if options.indent_size and options.indent_size == "tab" then
      if options.tab_width then
        options.indent_size = options.tab_width
      else
        options.indent_size = config.indent_size or 2
      end
    end

    if options.indent_size then
      indent_size = options.indent_size
    end

    if doc.indent_info then
      doc.indent_info.type = indent_type
      doc.indent_info.size = indent_size
      doc.indent_info.confirmed = true
    else
      doc.indent_info = {
        type = indent_type,
        size = indent_size,
        confirmed = true
      }
    end

    if options.end_of_line then
      if options.end_of_line == "crlf" then
        doc.crlf = true
      elseif options.end_of_line == "lf" then
        doc.crlf = false
      end
    end

    if options.trim_trailing_whitespace then
      doc.trim_trailing_whitespace = true
    elseif options.trim_trailing_whitespace == false then
      doc.trim_trailing_whitespace = false
    else
      doc.trim_trailing_whitespace = nil
    end

    if options.insert_final_newline then
      doc.insert_final_newline = true
    elseif options.insert_final_newline == false then
      doc.insert_final_newline = false
    else
      doc.insert_final_newline = nil
    end

    if options.charset then
      local charset, add_bom = options.charset, false
      if charset:find("%-bom$") then
        charset = charset:sub(1, -5)
        add_bom = true
      end
      doc.encoding = string.upper(charset)
      if add_bom then
        doc.bom = encoding.get_charset_bom(doc.encoding)
      else
        doc.bom = nil
      end
    end

    if
      (
        type(doc.trim_trailing_whitespace) == "boolean"
        or
        type(doc.insert_final_newline) == "boolean"
      )
      -- TODO: remove this once 2.1.1 is released
      and
      trimwhitespace.disable
    then
      trimwhitespace.disable(doc)
    end

    handle_final_new_line(doc, true)
  end
end

---Applies .editorconfig options to all open documents if possible.
function editorconfig.apply_all()
  for _, doc in ipairs(core.docs) do
    editorconfig.apply(doc)
  end
end

--------------------------------------------------------------------------------
-- Load .editorconfig on all projects loaded at startup and apply it
--------------------------------------------------------------------------------
core.add_thread(function()
  local loaded = false

  -- scan all opened project directories
  if core.projects then
    for i=1, #core.projects do
      local found = editorconfig.load(core.projects[i].path)
      if found then loaded = true end
    end
  end

  -- if an editorconfig was found then try to apply it to opened docs
  if loaded then
    editorconfig.apply_all()
  end
end)

--------------------------------------------------------------------------------
-- Override various core project loading functions for .editorconfig scanning
--------------------------------------------------------------------------------
local core_open_project = core.open_project
function core.open_project(project)
  core_open_project(project)
  if project_configs[main_project] then project_configs[main_project] = nil end
  main_project = core.root_project().path
  editorconfig.load(main_project)
end

local core_remove_project = core.remove_project
function core.remove_project(project, force)
  local out = core_remove_project(project, force)
  local path = project
  if type(project) ~= "string" then
    path = project.path
  end
  if project_configs[path] then project_configs[path] = nil end
  return out
end

local core_add_project = core.add_project
function core.add_project(project)
  local out = core_add_project(project)
  editorconfig.load(out.path)
  return out
end

--------------------------------------------------------------------------------
-- Hook into the core.doc to apply editor config options
--------------------------------------------------------------------------------
local doc_new = Doc.new
function Doc:new(...)
  doc_new(self, ...)
  editorconfig.apply(self)
end

---Cloned trimwitespace plugin until it is exposed for other plugins.
---@param doc core.doc
local function trim_trailing_whitespace(doc)
  if trimwhitespace.trim then
    trimwhitespace.trim(doc)
    return
  end

  -- TODO: remove this once 2.1.1 is released
  local cline, ccol = doc:get_selection()
  for i = 1, #doc.lines do
    local old_text = doc:get_text(i, 1, i, math.huge)
    local new_text = old_text:gsub("%s*$", "")

    -- don't remove whitespace which would cause the caret to reposition
    if cline == i and ccol > #new_text then
      new_text = old_text:sub(1, ccol - 1)
    end

    if old_text ~= new_text then
      doc:insert(i, 1, new_text)
      doc:remove(i, #new_text + 1, i, math.huge)
    end
  end
end

local doc_save = Doc.save
function Doc:save(...)
  local new_file = self.new_file

  ---@diagnostic disable-next-line
  if self.trim_trailing_whitespace then
    trim_trailing_whitespace(self)
  end

  local handle_new_line = handle_final_new_line(self)

  -- remove the unnecesary visible \n\n or the disabled \n
  local lc = #self.lines
  if handle_new_line then
    self.lines[lc] = self.lines[lc]:gsub("\n$", "")
  end

  doc_save(self, ...)

  -- restore the visible \n\n or disabled \n
  lc = #self.lines
  if handle_new_line then
    self.lines[lc] = self.lines[lc] .. "\n"
  end

  if common.basename(self.abs_filename) == ".editorconfig" then
    -- blindlessly reload related project .editorconfig options
    for _, project in ipairs(core.projects) do
      if common.path_belongs_to(self.abs_filename, project.path) then
        editorconfig.load(project.path)
        break
      end
    end
    -- re-apply editorconfig options to all open files
    editorconfig.apply_all()
  elseif new_file then
    -- apply editorconfig options for file that was previously unsaved
    editorconfig.apply(self)
  end
end

--------------------------------------------------------------------------------
-- Run the test suite if requested on CLI with: pragtical test editorconfig
--------------------------------------------------------------------------------
if (MOD_VERSION_MAJOR == 3 and MOD_VERSION_MINOR >= 2) or MOD_VERSION_MAJOR > 3 then
  local cli = require "core.cli"

  ---@type core.cli.command
  local editorconfig_test = {
    command = "editorconfig",
    description = "Run the editorconfig tests",
    max_arguments = 0,
    flags = {
      {
        name = "parsers",
        short_name = "p",
        description = "Only output the path expressions and their conversion into regular expressions",
      }
    },
    execute = function(flags)
      rawset(_G, "PARSERS", false)
      for _, flag in ipairs(flags) do
        if flag.name == "parsers" then
          rawset(_G, "PARSERS", true)
          break
        end
      end
      require "plugins.editorconfig.runtest"
    end
  }

  if not cli.commands["test"] then
    cli.register {
      command = "test",
      description = "Run application or plugin tests.",
      usage = "[<test_name>]",
      execute = function()
        print(cli.colorize("Available tests:", "yellow"))
        print ""
        for _, subcommand in ipairs(cli.commands["test"].subcommands) do
          print(
            cli.colorize(subcommand.command, "green")
            .. "  "
            .. (subcommand.description or "")
          )
        end
      end
    }
  end

  cli.commands["test"].subcommands = cli.commands["test"].subcommands or {}
  table.insert(cli.commands["test"].subcommands, editorconfig_test)
else
  for i, argument in ipairs(ARGS) do
    if argument == "test" and ARGS[i+1] == "editorconfig" then
      require "plugins.editorconfig.runtest"
      os.exit()
    end
  end
end


return editorconfig