nvim/after/ftplugin/php.lua

63 lines
2.1 KiB
Lua

-- PHP-specific settings and enhancements
-- Loaded automatically for PHP files
-- Enable includeexpr for intelligent gf (goto file) behavior
-- Handles common WordPress/PHP path patterns like:
-- require_once __DIR__ . '/../path/to/file.php';
-- include __FILE__ . '/relative/path.php';
vim.opt_local.includeexpr = "v:lua.resolve_php_gf_path(v:fname)"
-- Global function to resolve PHP file paths for gf command
function _G.resolve_php_gf_path(fname)
local line = vim.api.nvim_get_current_line()
local current_dir = vim.fn.expand('%:p:h')
local current_file = vim.fn.expand('%:p')
-- Pattern 1: __DIR__ . '/path' or __DIR__ . '/../path'
-- Most common in modern PHP/WordPress
local path = line:match("__DIR__%s*%.%s*['\"]([^'\"]+)['\"]")
if path then
path = current_dir .. path
return vim.fn.simplify(path)
end
-- Pattern 2: __FILE__ . '/path'
-- Less common but appears in legacy WordPress code
-- __FILE__ resolves to the current file's full path, so we use its directory
path = line:match("__FILE__%s*%.%s*['\"]([^'\"]+)['\"]")
if path then
-- __FILE__ is the file itself, but when concatenated with a path,
-- it's typically used like __DIR__, so we use the directory
path = current_dir .. path
return vim.fn.simplify(path)
end
-- Pattern 3: dirname(__FILE__) . '/path'
-- Old-style equivalent to __DIR__
path = line:match("dirname%s*%(%s*__FILE__%s*%)%s*%.%s*['\"]([^'\"]+)['\"]")
if path then
path = current_dir .. path
return vim.fn.simplify(path)
end
-- Pattern 4: Simple quoted path in require/include statements
-- Fallback for basic relative paths
path = line:match("require[_%w]*%s*['\"]([^'\"]+)['\"]")
if path then
-- Try relative to current file's directory
path = current_dir .. '/' .. path
return vim.fn.simplify(path)
end
path = line:match("include[_%w]*%s*['\"]([^'\"]+)['\"]")
if path then
-- Try relative to current file's directory
path = current_dir .. '/' .. path
return vim.fn.simplify(path)
end
-- Fallback: return as-is (normal gf behavior)
-- This allows standard gf to work for simple filenames
return fname
end