// This file is part of Notepad++ project
// Copyright (C)2021 Don HO <don.h@free.fr>

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// at your option any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//此文件是 Notepad++ 项目的一部分
//版权所有 （C）2021 Don HO <don.h@free.fr>

//该程序是免费软件：您可以重新分发和 / 或修改它
//它根据 GNU 通用公共许可证的条款，由
//自由软件基金会（Free Software Foundation），许可证的第 3 版，或
//由您选择任何更高版本。
//
//分发该程序是希望它有用，
//但没有任何保证; 甚至没有默示保证
//适销性或特定用途的适用性。请参阅
//GNU 通用公共许可证了解更多详情。
//
//您应该已经收到了 GNU 通用公共许可证的副本
//以及这个程序。 如果没有，请参阅 < https://www.gnu.org/licenses/>。

#pragma once

#include "tinyxmlA.h"
#include "tinyxml.h"
#include "Scintilla.h"
#include "ScintillaRef.h"
#include "ToolBar.h"
#include "UserDefineLangReference.h"
#include "colors.h"
#include "shortcut.h"
#include "ContextMenu.h"
#include "dpiManager.h"
#include "NppDarkMode.h"
#include <assert.h>
#include <tchar.h>
#include <map>
#include "ILexer.h"
#include "Lexilla.h"

#ifdef _WIN64

#ifdef _M_ARM64
#define ARCH_TYPE IMAGE_FILE_MACHINE_ARM64//图像文件机常量
#else
#define ARCH_TYPE IMAGE_FILE_MACHINE_AMD64//图像文件机常量
#endif

#else
#define ARCH_TYPE IMAGE_FILE_MACHINE_I386//图像文件机常量

#endif

#define CMD_INTERPRETER TEXT("%COMSPEC%")//指向CMD启动

class NativeLangSpeaker;

const bool POS_VERTICAL = true;//垂直向量为1
const bool POS_HORIZOTAL = false;//水平向量为0

const int UDD_SHOW   = 1; // 0000 0001
const int UDD_DOCKED = 2; // 0000 0010

//Docker 将应用程序与该程序的依赖，打包在一个文件里面。运行这个文件，就会生成一个虚拟容器。
// 程序在这个虚拟容器里运行，就好像在真实的物理机上运行一样。有了 Docker，就不用担心环境问题。

// 0 : 0000 0000 hide & undocked 隐藏且非环境化 0
// 1 : 0000 0001 show & undocked 显示且非环境化 1
// 2 : 0000 0010 hide & docked 隐藏且环境化 2
// 3 : 0000 0011 show & docked 显示且环境化 3

const int TAB_DRAWTOPBAR = 1;      //0000 0000 0001
const int TAB_DRAWINACTIVETAB = 2; //0000 0000 0010
const int TAB_DRAGNDROP = 4;       //0000 0000 0100
const int TAB_REDUCE = 8;          //0000 0000 1000
const int TAB_CLOSEBUTTON = 16;    //0000 0001 0000
const int TAB_DBCLK2CLOSE = 32;    //0000 0010 0000
const int TAB_VERTICAL = 64;       //0000 0100 0000
const int TAB_MULTILINE = 128;     //0000 1000 0000
const int TAB_HIDE = 256;          //0001 0000 0000
const int TAB_QUITONEMPTY = 512;   //0010 0000 0000
const int TAB_ALTICONS = 1024;     //0100 0000 0000

const bool activeText = true;
const bool activeNumeric = false;

enum class EolType: std::uint8_t//end of line 类型
{
	windows,
	macos,
	unix,

	// special values
	unknown, // can not be the first value for legacy code
	osdefault = windows,
};

/*!
** \brief Convert an int into a FormatType简单地将int转换为格式类型
** \param value An arbitrary int参数值任意int
** \param defvalue The default value to use if an invalid value is provided如果提供无效值，要使用的默认值
*/
EolType convertIntToFormatType(int value, EolType defvalue = EolType::osdefault);




enum UniMode {uni8Bit=0, uniUTF8=1, uni16BE=2, uni16LE=3, uniCookie=4, uni7Bit=5, uni16BE_NoBOM=6, uni16LE_NoBOM=7, uniEnd};
enum ChangeDetect { cdDisabled = 0x0, cdEnabledOld = 0x01, cdEnabledNew = 0x02, cdAutoUpdate = 0x04, cdGo2end = 0x08 };//改变监控
enum BackupFeature {bak_none = 0, bak_simple = 1, bak_verbose = 2};//备份和还原
enum OpenSaveDirSetting {dir_followCurrent = 0, dir_last = 1, dir_userDef = 2};//打开已保存设置
enum MultiInstSetting {monoInst = 0, multiInstOnSession = 1, multiInst = 2};//
enum writeTechnologyEngine {defaultTechnology = 0, directWriteTechnology = 1};
enum urlMode {urlDisable = 0, urlNoUnderLineFg, urlUnderLineFg, urlNoUnderLineBg, urlUnderLineBg,
              urlMin = urlDisable,
              urlMax = urlUnderLineBg};

const int LANG_INDEX_INSTR = 0;//语言索引指令
const int LANG_INDEX_INSTR2 = 1;
const int LANG_INDEX_TYPE = 2;
const int LANG_INDEX_TYPE2 = 3;
const int LANG_INDEX_TYPE3 = 4;
const int LANG_INDEX_TYPE4 = 5;
const int LANG_INDEX_TYPE5 = 6;
const int LANG_INDEX_TYPE6 = 7;
const int LANG_INDEX_TYPE7 = 8;

const int COPYDATA_PARAMS = 0;//数据拷贝参数
//const int COPYDATA_FILENAMESA = 1; // obsolete, no more useful
const int COPYDATA_FILENAMESW = 2;
const int COPYDATA_FULL_CMDLINE = 3;

#define PURE_LC_NONE	0
#define PURE_LC_BOL	 1
#define PURE_LC_WSP	 2

#define DECSEP_DOT	  0
#define DECSEP_COMMA	1
#define DECSEP_BOTH	 2


#define DROPBOX_AVAILABLE 1
#define ONEDRIVE_AVAILABLE 2
#define GOOGLEDRIVE_AVAILABLE 4

#define NPP_STYLING_FILESIZE_LIMIT_DEFAULT (200 * 1024 * 1024) // 200MB+ file won't be styled

const int FINDREPLACE_INSELECTION_THRESHOLD_DEFAULT = 1024;

const TCHAR fontSizeStrs[][3] = {TEXT(""), TEXT("5"), TEXT("6"), TEXT("7"), TEXT("8"), TEXT("9"), TEXT("10"), TEXT("11"), TEXT("12"), TEXT("14"), TEXT("16"), TEXT("18"), TEXT("20"), TEXT("22"), TEXT("24"), TEXT("26"), TEXT("28")};

const TCHAR localConfFile[] = TEXT("doLocalConf.xml");
const TCHAR notepadStyleFile[] = TEXT("asNotepad.xml");

// issue xml/log file name
const TCHAR nppLogNetworkDriveIssue[] = TEXT("nppLogNetworkDriveIssue");
const TCHAR nppLogNulContentCorruptionIssue[] = TEXT("nppLogNulContentCorruptionIssue");

void cutString(const TCHAR *str2cut, std::vector<std::wstring> & patternVect);
void cutStringBy(const TCHAR *str2cut, std::vector<std::wstring> & patternVect, char byChar, bool allowEmptyStr);

// style names
const wchar_t g_npcStyleName[] = L"Non-printing characters custom color";

struct Position//位置结构体，初始值全部为0
{
	intptr_t _firstVisibleLine = 0;
	intptr_t _startPos = 0;
	intptr_t _endPos = 0;
	intptr_t _xOffset = 0;
	intptr_t _selMode = 0;
	intptr_t _scrollWidth = 1;
	intptr_t _offset = 0;
	intptr_t _wrapCount = 0;
};


struct MapPosition//图位
{
private:
	intptr_t _maxPeekLenInKB = 512; // 512 KB
public:
	intptr_t _firstVisibleDisplayLine = -1;

	intptr_t _firstVisibleDocLine = -1; // map
	intptr_t _lastVisibleDocLine = -1;  // map
	intptr_t _nbLine = -1;              // map
	intptr_t _higherPos = -1;           // map
	intptr_t _width = -1;
	intptr_t _height = -1;
	intptr_t _wrapIndentMode = -1;

	intptr_t _KByteInDoc = _maxPeekLenInKB;

	bool _isWrap = false;
	bool isValid() const { return (_firstVisibleDisplayLine != -1); };
	bool canScroll() const { return (_KByteInDoc < _maxPeekLenInKB); }; // _nbCharInDoc < _maxPeekLen : Don't scroll the document for the performance issue
	//展开文件
};


struct sessionFileInfo : public Position//会话文件信息结构体
{
	sessionFileInfo(const wchar_t* fn, const TCHAR *ln, int encoding, bool userReadOnly, const Position& pos, const TCHAR *backupFilePath, FILETIME originalFileLastModifTimestamp, const MapPosition & mapPos) :
		Position(pos), _encoding(encoding), _isUserReadOnly(userReadOnly), _originalFileLastModifTimestamp(originalFileLastModifTimestamp), _mapPos(mapPos)
	{
		if (fn) _fileName = fn;
		if (ln)	_langName = ln;
		if (backupFilePath) _backupFilePath = backupFilePath;
	}

	sessionFileInfo(std::wstring fn) : _fileName(fn) {}

	std::wstring _fileName;
	std::wstring _langName;
	std::vector<size_t> _marks;
	std::vector<size_t> _foldStates;
	int	_encoding = -1;
	bool _isUserReadOnly = false;
	bool _isMonitoring = false;
	int _individualTabColour = -1;

	std::wstring _backupFilePath;
	FILETIME _originalFileLastModifTimestamp {};

	MapPosition _mapPos;
};


struct Session//会话结构体
{
	size_t nbMainFiles() const {return _mainViewFiles.size();};
	size_t nbSubFiles() const {return _subViewFiles.size();};
	size_t _activeView = 0;
	size_t _activeMainIndex = 0;
	size_t _activeSubIndex = 0;
	bool _includeFileBrowser = false;
	std::wstring _fileBrowserSelectedItem;
	std::vector<sessionFileInfo> _mainViewFiles;
	std::vector<sessionFileInfo> _subViewFiles;
	std::vector<std::wstring> _fileBrowserRoots;
};

//定义了两个结构体，CmdLineParams和CmdLineParamsDTO，分别用来保存命令行参数和通过WM_COPYDATA和Notepad_plus::loadCommandlineParams发送CmdLineParams。
struct CmdLineParams
{
	bool _isNoPlugin = false;
	bool _isReadOnly = false;
	bool _isNoSession = false;
	bool _isNoTab = false;
	bool _isPreLaunch = false;
	bool _showLoadingTime = false;
	bool _alwaysOnTop = false;
	intptr_t _line2go   = -1;
	intptr_t _column2go = -1;
	intptr_t _pos2go = -1;

	POINT _point = {};
	bool _isPointXValid = false;
	bool _isPointYValid = false;

	bool _isSessionFile = false;
	bool _isRecursive = false;
	bool _openFoldersAsWorkspace = false;
	bool _monitorFiles = false;

	LangType _langType = L_EXTERNAL;
	std::wstring _localizationPath;
	std::wstring _udlName;
	std::wstring _pluginMessage;

	std::wstring _easterEggName;
	unsigned char _quoteType = 0;
	int _ghostTypingSpeed = -1; // -1: initial value  1: slow  2: fast  3: speed of light

	CmdLineParams()
	{
		_point.x = 0;
		_point.y = 0;
	}

	bool isPointValid() const
	{
		return _isPointXValid && _isPointYValid;
	}
};

// A POD class to send CmdLineParams through WM_COPYDATA and to Notepad_plus::loadCommandlineParams
//CmdLineParams结构体定义了一系列bool、intptr_t、POINT、LangType和std::wstring类型的成员变量，用于保存命令行参数的各个属性。其中，isPointValid()函数用于检查_point的坐标值是否有效。
//CmdLineParamsDTO结构体是一个POD（普通数据类型）类，用于通过WM_COPYDATA和Notepad_plus::loadCommandlineParams发送CmdLineParams。它定义了与CmdLineParams相同类型的成员变量，并提供了一个静态的FromCmdLineParams函数，用于将CmdLineParams转换为CmdLineParamsDTO。
//在FromCmdLineParams函数中，通过将CmdLineParams的成员变量赋值给CmdLineParamsDTO的对应成员变量，实现了将CmdLineParams转换为CmdLineParamsDTO的功能。
//整个代码主要是为了实现CmdLineParams和CmdLineParamsDTO之间的数据传递和转换。

struct CmdLineParamsDTO
{
	bool _isReadOnly = false;
	bool _isNoSession = false;
	bool _isSessionFile = false;
	bool _isRecursive = false;
	bool _openFoldersAsWorkspace = false;
	bool _monitorFiles = false;

	intptr_t _line2go = 0;
	intptr_t _column2go = 0;
	intptr_t _pos2go = 0;

	LangType _langType = L_EXTERNAL;
	wchar_t _udlName[MAX_PATH] = {'\0'};
	wchar_t _pluginMessage[MAX_PATH] = {'\0'};

	static CmdLineParamsDTO FromCmdLineParams(const CmdLineParams& params)
	{
		CmdLineParamsDTO dto;
		dto._isReadOnly = params._isReadOnly;
		dto._isNoSession = params._isNoSession;
		dto._isSessionFile = params._isSessionFile;
		dto._isRecursive = params._isRecursive;
		dto._openFoldersAsWorkspace = params._openFoldersAsWorkspace;
		dto._monitorFiles = params._monitorFiles;

		dto._line2go = params._line2go;
		dto._column2go = params._column2go;
		dto._pos2go = params._pos2go;

		dto._langType = params._langType;
		wcsncpy(dto._udlName, params._udlName.c_str(), MAX_PATH);
		wcsncpy(dto._pluginMessage, params._pluginMessage.c_str(), MAX_PATH);
		return dto;
	}
};

struct FloatingWindowInfo//浮动窗口信息结构体
{
	int _cont = 0;
	RECT _pos = {};

	FloatingWindowInfo(int cont, int x, int y, int w, int h)//浮动窗口位置参数
		: _cont(cont)
	{
		_pos.left	= x;
		_pos.top	= y;
		_pos.right	= w;
		_pos.bottom = h;
	}
};


struct PluginDlgDockingInfo final
{
	std::wstring _name;
	int _internalID = -1;

	int _currContainer = -1;
	int _prevContainer = -1;
	bool _isVisible = false;

	PluginDlgDockingInfo(const TCHAR* pluginName, int id, int curr, int prev, bool isVis)
		: _name(pluginName), _internalID(id), _currContainer(curr), _prevContainer(prev), _isVisible(isVis)
	{}

	bool operator == (const PluginDlgDockingInfo& rhs) const
	{
		return _internalID == rhs._internalID and _name == rhs._name;
	}
};


struct ContainerTabInfo final
{
	int _cont = 0;
	int _activeTab = 0;

	ContainerTabInfo(int cont, int activeTab) : _cont(cont), _activeTab(activeTab) {};
};


struct DockingManagerData final
{
	int _leftWidth = 200;
	int _rightWidth = 200;
	int _topHeight = 200;
	int _bottomHight = 200;

	std::vector<FloatingWindowInfo> _flaotingWindowInfo;
	std::vector<PluginDlgDockingInfo> _pluginDockInfo;
	std::vector<ContainerTabInfo> _containerTabInfo;

	bool getFloatingRCFrom(int floatCont, RECT& rc) const
	{
		for (size_t i = 0, fwiLen = _flaotingWindowInfo.size(); i < fwiLen; ++i)
		{
			if (_flaotingWindowInfo[i]._cont == floatCont)
			{
				rc.left   = _flaotingWindowInfo[i]._pos.left;
				rc.top	= _flaotingWindowInfo[i]._pos.top;
				rc.right  = _flaotingWindowInfo[i]._pos.right;
				rc.bottom = _flaotingWindowInfo[i]._pos.bottom;
				return true;
			}
		}
		return false;
	}
};


//这段代码定义了几个用于样式处理的数据结构和函数。
//首先是Style结构体，表示一个样式。其中包括了以下成员：
//_styleID: 样式的ID，用于标识不同的样式。
//_styleDesc: 样式的描述。
//_fgColor和_bgColor：前景色和背景色，用于设置文本的颜色。
//_colorStyle：颜色样式，指定了是对前景色、背景色还是都设置颜色。
//_isFontEnabled：是否启用了字体样式。
//_fontName：字体名称。
//_fontStyle：字体样式。
//_fontSize：字体大小。
//_nesting：嵌套样式，用于处理嵌套样式的情况。
////_keywords：关键字列表。
//然后是GlobalOverride结构体，表示全局的样式覆盖设置。其中包括了以下成员：

//isEnable()方法：判断是否启用了样式覆盖。
//enableFg、enableBg、enableFont、enableFontSize、enableBold、enableItalic、enableUnderLine：每个成员都表示是否启用了相应的样式覆盖。
//接下来是StyleArray结构体，用于管理多个样式。其中有以下成员函数：

//begin()和end()：返回迭代器，用于遍历样式数组。
//clear()：清空样式数组。
//getStyler(size_t index)：根据索引返回样式。
//addStyler(int styleID, TiXmlNode* styleNode)：根据给定的样式ID和XML节点，添加一个样式。
//addStyler(int styleID, const std::wstring& styleName)：根据给定的样式ID和样式名称，添加一个样式。
//findByID(int id)：根据样式ID查找样式。
//findByName(const std::wstring& name)：根据样式名称查找样式。
//接下来是LexerStyler结构体，表示一个语法分析器的样式器。其中包括以下成员：

//operator=：重载赋值运算符。
//setLexerName(const TCHAR* lexerName)：设置语法分析器名称。
//setLexerDesc(const TCHAR* lexerDesc)：设置语法分析器描述。
//setLexerUserExt(const TCHAR* lexerUserExt)：设置语法分析器的用户扩展。
//getLexerName() const、getLexerDesc() const、getLexerUserExt() const：分别返回语法分析器名称、描述和用户扩展。
//_lexerName、_lexerDesc、_lexerUserExt：分别存储语法分析器的名称、描述和用户扩展。
//然后是SortLexersInAlphabeticalOrder结构体，用于对LexerStyler进行按字母顺序排序。

//最后是LexerStylerArray结构体，用于管理多个语法分析器的样式器。其中有以下成员函数：

//getNbLexer() const：返回语法分析器的数量。
//clear()：清空语法分析器数组。
//getLexerFromIndex(size_t index)：根据索引返回语法分析器样式器。
//getLexerNameFromIndex(size_t index) const、getLexerDescFromIndex(size_t index) const：分别根据索引返回语法分析器的名称和描述。
//getLexerStylerByName(const TCHAR* lexerName)：根据语法分析器名称查找语法分析器样式器。
//addLexerStyler(const TCHAR* lexerName, const TCHAR* lexerDesc, const TCHAR* lexerUserExt, TiXmlNode* lexerNode)：根据语法分析器的名称、描述、用户扩展和XML节点，添加一个语法分析器样式器。
//sort()：对语法分析器样式器按字母顺序排序。
//这段代码的作用是定义了一些数据结构和函数，用于管理编辑器中的样式和语法分析器的样式。通过定义这些数据结构和函数，可以方便地管理和设置编辑器的样式和语法分析器的样式。
//
//

const int FONTSTYLE_NONE = 0;
const int FONTSTYLE_BOLD = 1;
const int FONTSTYLE_ITALIC = 2;
const int FONTSTYLE_UNDERLINE = 4;

const int STYLE_NOT_USED = -1;

const int COLORSTYLE_FOREGROUND = 0x01;
const int COLORSTYLE_BACKGROUND = 0x02;
const int COLORSTYLE_ALL = COLORSTYLE_FOREGROUND|COLORSTYLE_BACKGROUND;




struct Style final
{
	int _styleID = STYLE_NOT_USED;
	std::wstring _styleDesc;

	COLORREF _fgColor = COLORREF(STYLE_NOT_USED);
	COLORREF _bgColor = COLORREF(STYLE_NOT_USED);
	int _colorStyle = COLORSTYLE_ALL;

	bool _isFontEnabled = false;
	std::wstring _fontName;
	int _fontStyle = STYLE_NOT_USED;
	int _fontSize = STYLE_NOT_USED;

	int _nesting = FONTSTYLE_NONE;

	int _keywordClass = STYLE_NOT_USED;
	std::wstring _keywords;
};


//
//
//
//
//
//
//

struct GlobalOverride final
{
	bool isEnable() const {return (enableFg || enableBg || enableFont || enableFontSize || enableBold || enableItalic || enableUnderLine);}
	bool enableFg = false;
	bool enableBg = false;
	bool enableFont = false;
	bool enableFontSize = false;
	bool enableBold = false;
	bool enableItalic = false;
	bool enableUnderLine = false;
};

//
//
//
//
//
//
//

struct StyleArray
{
	auto begin() { return _styleVect.begin(); };
	auto end() { return _styleVect.end(); };
	void clear() { _styleVect.clear(); };

	Style& getStyler(size_t index) {
		if (index >=  _styleVect.size())
			throw std::out_of_range("Styler index out of range");
		return _styleVect[index];
	};

	void addStyler(int styleID, TiXmlNode *styleNode);

	void addStyler(int styleID, const std::wstring& styleName) {
		_styleVect.emplace_back();
		Style& s = _styleVect.back();
		s._styleID = styleID;
		s._styleDesc = styleName;
		s._fgColor = black;
		s._bgColor = white;
	};

	Style* findByID(int id) {
		for (size_t i = 0; i < _styleVect.size(); ++i)
		{
			if (_styleVect[i]._styleID == id)
				return &(_styleVect[i]);
		}
		return nullptr;
	};

	Style* findByName(const std::wstring& name) {
		for (size_t i = 0; i < _styleVect.size(); ++i)
		{
			if (_styleVect[i]._styleDesc == name)
				return &(_styleVect[i]);
		}
		return nullptr;
	};

protected:
	std::vector<Style> _styleVect;
};


//
//
//
//
//
//
//


struct LexerStyler : public StyleArray
{
public:
	LexerStyler & operator=(const LexerStyler & ls)
	{
		if (this != &ls)
		{
			*(static_cast<StyleArray *>(this)) = ls;
			this->_lexerName = ls._lexerName;
			this->_lexerDesc = ls._lexerDesc;
			this->_lexerUserExt = ls._lexerUserExt;
		}
		return *this;
	}

	void setLexerName(const TCHAR *lexerName)
	{
		_lexerName = lexerName;
	}

	void setLexerDesc(const TCHAR *lexerDesc)
	{
		_lexerDesc = lexerDesc;
	}

	void setLexerUserExt(const TCHAR *lexerUserExt) {
		_lexerUserExt = lexerUserExt;
	};

	const TCHAR * getLexerName() const {return _lexerName.c_str();};
	const TCHAR * getLexerDesc() const {return _lexerDesc.c_str();};
	const TCHAR * getLexerUserExt() const {return _lexerUserExt.c_str();};

private :
	std::wstring _lexerName;
	std::wstring _lexerDesc;
	std::wstring _lexerUserExt;
};


//
//
//
//
//
//
//

struct SortLexersInAlphabeticalOrder {
	bool operator() (LexerStyler& l, LexerStyler& r) {
		if (!lstrcmp(l.getLexerDesc(), TEXT("Search result")))
			return false;
		if (!lstrcmp(r.getLexerDesc(), TEXT("Search result")))
			return true;
		return lstrcmp(l.getLexerDesc(), r.getLexerDesc()) < 0;
	}
};


//
//
//
//
//
//
//

struct LexerStylerArray
{
	size_t getNbLexer() const { return _lexerStylerVect.size(); }
	void clear() { _lexerStylerVect.clear(); }

	LexerStyler & getLexerFromIndex(size_t index)
	{
		assert(index < _lexerStylerVect.size());
		return _lexerStylerVect[index];
	};

	const TCHAR * getLexerNameFromIndex(size_t index) const { return _lexerStylerVect[index].getLexerName(); }
	const TCHAR * getLexerDescFromIndex(size_t index) const { return _lexerStylerVect[index].getLexerDesc(); }

	LexerStyler * getLexerStylerByName(const TCHAR *lexerName) {
		if (!lexerName) return nullptr;
		for (size_t i = 0 ; i < _lexerStylerVect.size() ; ++i)
		{
			if (!lstrcmp(_lexerStylerVect[i].getLexerName(), lexerName))
				return &(_lexerStylerVect[i]);
		}
		return nullptr;
	};

	void addLexerStyler(const TCHAR *lexerName, const TCHAR *lexerDesc, const TCHAR *lexerUserExt, TiXmlNode *lexerNode);

	void sort() {
		std::sort(_lexerStylerVect.begin(), _lexerStylerVect.end(), SortLexersInAlphabeticalOrder());
	};

private :
	std::vector<LexerStyler> _lexerStylerVect;
};


//
//
//
//
//
//NewDocDefaultSettings：包含了一些默认的文档设置，包括文件格式、Unicode模式、编码方式等。

//LangMenuItem：定义了一个菜单项，包含了语言类型、命令ID和语言名称。

//PrintSettings：定义了打印设置，包括是否打印行号、打印选项、页眉页脚内容、字体样式等。

//Date：定义了日期类，包含年、月、日，并提供了日期的比较和转换方法。

//这些结构体和类用于在某个编辑器中管理文档、语言、打印、日期等相关的设置和功能。
//


struct NewDocDefaultSettings final
{
	EolType _format = EolType::osdefault;
	UniMode _unicodeMode = uniCookie;
	bool _openAnsiAsUtf8 = true;
	LangType _lang = L_TEXT;
	int _codepage = -1; // -1 when not using
	bool _addNewDocumentOnStartup = false;
};


//
//
//
//
//
//
//


struct LangMenuItem final
{
	LangType _langType = L_TEXT;
	int	_cmdID = -1;
	std::wstring _langName;

	LangMenuItem(LangType lt, int cmdID = 0, const std::wstring& langName = TEXT("")):
	_langType(lt), _cmdID(cmdID), _langName(langName){};
};
//
//
//
//
//
//
//
struct PrintSettings final {
	bool _printLineNumber = true;
	int _printOption = SC_PRINT_COLOURONWHITE;

	std::wstring _headerLeft;
	std::wstring _headerMiddle;
	std::wstring _headerRight;
	std::wstring _headerFontName;
	int _headerFontStyle = 0;
	int _headerFontSize = 0;

	std::wstring _footerLeft;
	std::wstring _footerMiddle;
	std::wstring _footerRight;
	std::wstring _footerFontName;
	int _footerFontStyle = 0;
	int _footerFontSize = 0;

	RECT _marge = {};

	PrintSettings() {
		_marge.left = 0; _marge.top = 0; _marge.right = 0; _marge.bottom = 0;
	};

	bool isHeaderPresent() const {
		return ((_headerLeft != TEXT("")) || (_headerMiddle != TEXT("")) || (_headerRight != TEXT("")));
	};

	bool isFooterPresent() const {
		return ((_footerLeft != TEXT("")) || (_footerMiddle != TEXT("")) || (_footerRight != TEXT("")));
	};

	bool isUserMargePresent() const {
		return ((_marge.left != 0) || (_marge.top != 0) || (_marge.right != 0) || (_marge.bottom != 0));
	};
};
//
//
//
//
//
//
//

class Date final
{
public:
	Date() = default;
	Date(unsigned long year, unsigned long month, unsigned long day)
		: _year(year)
		, _month(month)
		, _day(day)
	{
		assert(year > 0 && year <= 9999); // I don't think Notepad++ will last till AD 10000 :)
		assert(month > 0 && month <= 12);
		assert(day > 0 && day <= 31);
		assert(!(month == 2 && day > 29) &&
			   !(month == 4 && day > 30) &&
			   !(month == 6 && day > 30) &&
			   !(month == 9 && day > 30) &&
			   !(month == 11 && day > 30));
	}

	explicit Date(const TCHAR *dateStr);

	// The constructor which makes the date of number of days from now
	// nbDaysFromNow could be negative if user want to make a date in the past
	// if the value of nbDaysFromNow is 0 then the date will be now
	Date(int nbDaysFromNow);

	void now();

	std::wstring toString() const // Return Notepad++ date format : YYYYMMDD
	{
		TCHAR dateStr[16];
		wsprintf(dateStr, TEXT("%04u%02u%02u"), _year, _month, _day);
		return dateStr;
	}

	bool operator < (const Date & compare) const
	{
		if (this->_year != compare._year)
			return (this->_year < compare._year);
		if (this->_month != compare._month)
			return (this->_month < compare._month);
		return (this->_day < compare._day);
	}

	bool operator > (const Date & compare) const
	{
		if (this->_year != compare._year)
			return (this->_year > compare._year);
		if (this->_month != compare._month)
			return (this->_month > compare._month);
		return (this->_day > compare._day);
	}

	bool operator == (const Date & compare) const
	{
		if (this->_year != compare._year)
			return false;
		if (this->_month != compare._month)
			return false;
		return (this->_day == compare._day);
	}

	bool operator != (const Date & compare) const
	{
		if (this->_year != compare._year)
			return true;
		if (this->_month != compare._month)
			return true;
		return (this->_day != compare._day);
	}

private:
	unsigned long _year  = 2008;
	unsigned long _month = 4;
	unsigned long _day   = 26;
};
//
//
//这段代码定义了一个名为MatchedPairConf的类，该类包含了一些成员变量和成员函数。
//
//MatchedPairConf类的成员变量包括：
//- _matchedPairs：一个包含字符对的向量，用于存储匹配的字符对。
//- _matchedPairsInit：用于在初始化时使用的_matchedPairs的副本。
//- _doHtmlXmlTag、_doParentheses、_doBrackets、_doCurlyBrackets、_doQuotes、_doDoubleQuotes：表示是否执行相应类型的括号匹配的布尔变量。
//
//MatchedPairConf类的成员函数包括：
//- hasUserDefinedPairs() const：判断是否存在用户定义的字符对。
//- hasDefaultPairs() const：判断是否存在默认的字符对，包括圆括号、方括号、花括号、引号等。
//- hasAnyPairsPair() const：判断是否存在任何类型的字符对。
//
//该类的目的是管理匹配括号的设置，包括用户定义的字符对和默认的字符对。
//
//
//
//

class MatchedPairConf final
{
public:
	bool hasUserDefinedPairs() const { return _matchedPairs.size() != 0; }
	bool hasDefaultPairs() const { return _doParentheses||_doBrackets||_doCurlyBrackets||_doQuotes||_doDoubleQuotes||_doHtmlXmlTag; }
	bool hasAnyPairsPair() const { return hasUserDefinedPairs() || hasDefaultPairs(); }

public:
	std::vector<std::pair<char, char>> _matchedPairs;
	std::vector<std::pair<char, char>> _matchedPairsInit; // used only on init
	bool _doHtmlXmlTag = false;
	bool _doParentheses = false;
	bool _doBrackets = false;
	bool _doCurlyBrackets = false;
	bool _doQuotes = false;
	bool _doDoubleQuotes = false;
};
//
//
//
//
//
//
//
struct DarkModeConf final
{
	bool _isEnabled = false;
	bool _isEnabledPlugin = true;
	NppDarkMode::ColorTone _colorTone = NppDarkMode::blackTone;
	NppDarkMode::Colors _customColors = NppDarkMode::getDarkModeDefaultColors();
	NppDarkMode::AdvancedOptions _advOptions{};
};

//
//
//
//
//
//
//
struct LargeFileRestriction final
{
	int64_t _largeFileSizeDefInByte = NPP_STYLING_FILESIZE_LIMIT_DEFAULT;
	bool _isEnabled = true;

	bool _deactivateWordWrap = true;

	bool _allowBraceMatch = false;
	bool _allowAutoCompletion = false;
	bool _allowSmartHilite = false;
	bool _allowClickableLink = false;
	
	bool _suppress2GBWarning = false;
};
//
//
//
//
//
//
//
struct NppGUI final
{
	toolBarStatusType _toolBarStatus = TB_STANDARD;
	bool _toolbarShow = true;
	bool _statusBarShow = true;
	bool _menuBarShow = true;

	// 1st bit : draw top bar;
	// 2nd bit : draw inactive tabs
	// 3rd bit : enable drag & drop
	// 4th bit : reduce the height
	// 5th bit : enable vertical
	// 6th bit : enable multiline

	// 0:don't draw; 1:draw top bar 2:draw inactive tabs 3:draw both 7:draw both+drag&drop
	int _tabStatus = (TAB_DRAWTOPBAR | TAB_DRAWINACTIVETAB | TAB_DRAGNDROP | TAB_REDUCE | TAB_CLOSEBUTTON);

	bool _splitterPos = POS_VERTICAL;
	int _userDefineDlgStatus = UDD_DOCKED;

	int _tabSize = 4;
	bool _tabReplacedBySpace = false;

	bool _finderLinesAreCurrentlyWrapped = false;
	bool _finderPurgeBeforeEverySearch = false;
	bool _finderShowOnlyOneEntryPerFoundLine = true;

	int _fileAutoDetection = cdEnabledNew;

	bool _checkHistoryFiles = false;

	RECT _appPos {0, 0, 1024, 700};

	RECT _findWindowPos {};
	bool _findWindowLessMode = false;

	bool _isMaximized = false;
	bool _isMinimizedToTray = false;
	bool _rememberLastSession = true; // remember next session boolean will be written in the settings
	bool _keepSessionAbsentFileEntries = false;
	bool _isCmdlineNosessionActivated = false; // used for if -nosession is indicated on the launch time
	bool _detectEncoding = true;
	bool _saveAllConfirm = true;
	bool _setSaveDlgExtFiltToAllTypes = false;
	bool _doTaskList = true;
	bool _maitainIndent = true;
	bool _enableSmartHilite = true;

	bool _smartHiliteCaseSensitive = false;
	bool _smartHiliteWordOnly = true;
	bool _smartHiliteUseFindSettings = false;
	bool _smartHiliteOnAnotherView = false;

	bool _markAllCaseSensitive = false;
	bool _markAllWordOnly = true;

	bool _disableSmartHiliteTmp = false;
	bool _enableTagsMatchHilite = true;
	bool _enableTagAttrsHilite = true;
	bool _enableHiliteNonHTMLZone = false;
	bool _styleMRU = true;
	char _leftmostDelimiter = '(';
	char _rightmostDelimiter = ')';
	bool _delimiterSelectionOnEntireDocument = false;
	bool _backSlashIsEscapeCharacterForSql = true;
	bool _fillFindFieldWithSelected = true;
	bool _fillFindFieldSelectCaret = true;
	bool _monospacedFontFindDlg = false;
	bool _findDlgAlwaysVisible = false;
	bool _confirmReplaceInAllOpenDocs = true;
	bool _replaceStopsWithoutFindingNext = false;
	int _inSelectionAutocheckThreshold = FINDREPLACE_INSELECTION_THRESHOLD_DEFAULT;
	bool _muteSounds = false;
	bool _enableFoldCmdToggable = false;
	bool _hideMenuRightShortcuts = false;
	writeTechnologyEngine _writeTechnologyEngine = defaultTechnology;
	bool _isWordCharDefault = true;
	std::string _customWordChars;
	urlMode _styleURL = urlUnderLineFg;
	std::wstring _uriSchemes = TEXT("svn:// cvs:// git:// imap:// irc:// irc6:// ircs:// ldap:// ldaps:// news: telnet:// gopher:// ssh:// sftp:// smb:// skype: snmp:// spotify: steam:// sms: slack:// chrome:// bitcoin:");
	NewDocDefaultSettings _newDocDefaultSettings;

	std::wstring _dateTimeFormat = TEXT("yyyy-MM-dd HH:mm:ss");
	bool _dateTimeReverseDefaultOrder = false;

	void setTabReplacedBySpace(bool b) {_tabReplacedBySpace = b;};
	const NewDocDefaultSettings & getNewDocDefaultSettings() const {return _newDocDefaultSettings;};
	std::vector<LangMenuItem> _excludedLangList;
	bool _isLangMenuCompact = true;

	PrintSettings _printSettings;
	BackupFeature _backup = bak_none;
	bool _useDir = false;
	std::wstring _backupDir;
	DockingManagerData _dockingData;
	GlobalOverride _globalOverride;
	enum AutocStatus{autoc_none, autoc_func, autoc_word, autoc_both};
	AutocStatus _autocStatus = autoc_both;
	UINT  _autocFromLen = 1;
	bool _autocIgnoreNumbers = true;
	bool _autocInsertSelectedUseENTER = true;
	bool _autocInsertSelectedUseTAB = true;
	bool _autocBrief = false;
	bool _funcParams = true;
	MatchedPairConf _matchedPairConf;

	std::wstring _definedSessionExt;
	std::wstring _definedWorkspaceExt;

	// items with no Notepad++ GUI to set
	std::wstring _commandLineInterpreter = CMD_INTERPRETER;

	struct AutoUpdateOptions
	{
		bool _doAutoUpdate = true;
		int _intervalDays = 15;
		Date _nextUpdateDate;
		AutoUpdateOptions(): _nextUpdateDate(Date()) {};
	}
	_autoUpdateOpt;

	bool _doesExistUpdater = false;
	int _caretBlinkRate = 600;
	int _caretWidth = 1;

	bool _shortTitlebar = false;

	OpenSaveDirSetting _openSaveDir = dir_followCurrent;

	TCHAR _defaultDir[MAX_PATH]{};
	TCHAR _defaultDirExp[MAX_PATH]{};	//expanded environment variables
	TCHAR _lastUsedDir[MAX_PATH]{};
	
	std::wstring _themeName;
	MultiInstSetting _multiInstSetting = monoInst;
	bool _clipboardHistoryPanelKeepState = false;
	bool _docListKeepState = false;
	bool _charPanelKeepState = false;
	bool _fileBrowserKeepState = false;
	bool _projectPanelKeepState = false;
	bool _docMapKeepState = false;
	bool _funcListKeepState = false;
	bool _pluginPanelKeepState = false;
	bool _fileSwitcherWithoutExtColumn = false;
	int _fileSwitcherExtWidth = 50;
	bool _fileSwitcherWithoutPathColumn = true;
	int _fileSwitcherPathWidth = 50;
	bool _fileSwitcherDisableListViewGroups = false;
	bool isSnapshotMode() const {return _isSnapshotMode && _rememberLastSession && !_isCmdlineNosessionActivated;};
	bool _isSnapshotMode = true;
	size_t _snapshotBackupTiming = 7000;
	std::wstring _cloudPath; // this option will never be read/written from/to config.xml
	unsigned char _availableClouds = '\0'; // this option will never be read/written from/to config.xml

	enum SearchEngineChoice{ se_custom = 0, se_duckDuckGo = 1, se_google = 2, se_bing = 3, se_yahoo = 4, se_stackoverflow = 5 };
	SearchEngineChoice _searchEngineChoice = se_google;
	std::wstring _searchEngineCustom;

	bool _isFolderDroppedOpenFiles = false;

	bool _isDocPeekOnTab = false;
	bool _isDocPeekOnMap = false;

	// function list should be sorted by default on new file open
	bool _shouldSortFunctionList = false;

	DarkModeConf _darkmode;

	LargeFileRestriction _largeFileRestriction;
};

//
//这段代码定义了三个结构体和一个类。
//
//1. 结构体ScintillaViewParams:
//-成员变量包括一系列布尔变量和枚举类型变量，用于记录Scintilla编辑器的各种参数设置。
//- 成员函数包括一个计算分心模式视图的填充长度的方法。
//
//2. 结构体Lang :
//	-成员变量包括语言ID、语言名称、默认文件扩展名、关键词列表、行注释符号、块注释开始符号和结束符号等。
//	- 成员函数包括设置默认文件扩展名、设置行注释符号、设置块注释开始符号、设置块注释结束符号以及获取 / 设置Tab信息等。
//
//	3. 类UserLangContainer :
//	-成员变量包括样式数组、语言名称、文件扩展名、是否为深色模式、UDL版本、关键词列表、是否为前缀、是否忽略大小写、是否允许折叠注释、强制纯LC、小数分隔符以及是否紧凑折叠等。
//	- 成员函数包括获取名称、获取文件扩展名、获取UDL版本等。
///
//	这些结构体和类都用于记录编辑器的各种设置参数，方便进行管理和访问。
//
//
//
//
//
struct ScintillaViewParams
{
	bool _lineNumberMarginShow = true;
	bool _lineNumberMarginDynamicWidth = true;
	bool _bookMarkMarginShow = true;
	bool _isChangeHistoryEnabled = true;
	bool _isChangeHistoryEnabled4NextSession = true;
	folderStyle  _folderStyle = FOLDER_STYLE_BOX; //"simple", "arrow", "circle", "box" and "none"
	lineWrapMethod _lineWrapMethod = LINEWRAP_ALIGNED;
	bool _foldMarginShow = true;
	bool _indentGuideLineShow = true;
	lineHiliteMode _currentLineHiliteMode = LINEHILITE_HILITE;
	unsigned char _currentLineFrameWidth = 1; // 1-6 pixel
	bool _wrapSymbolShow = false;
	bool _doWrap = false;
	bool _isEdgeBgMode = false;

	std::vector<size_t> _edgeMultiColumnPos;
	intptr_t _zoom = 0;
	intptr_t _zoom2 = 0;
	bool _whiteSpaceShow = false;
	bool _eolShow = false;
	enum crlfMode {plainText = 0, roundedRectangleText = 1, plainTextCustomColor = 2, roundedRectangleTextCustomColor = 3};
	crlfMode _eolMode = roundedRectangleText;
	bool _npcShow = false;
	enum npcMode { identity = 0, abbreviation = 1, codepoint = 2 };
	npcMode _npcMode = abbreviation;
	bool _npcCustomColor = false;
	bool _npcIncludeCcUniEol = false;
	bool _ccUniEolShow = true;

	int _borderWidth = 2;
	bool _virtualSpace = false;
	bool _scrollBeyondLastLine = true;
	bool _rightClickKeepsSelection = false;
	bool _disableAdvancedScrolling = false;
	bool _doSmoothFont = false;
	bool _showBorderEdge = true;

	unsigned char _paddingLeft = 0;  // 0-9 pixel
	unsigned char _paddingRight = 0; // 0-9 pixel

	// distractionFreeDivPart is used for divising the fullscreen pixel width.
	// the result of division will be the left & right padding in Distraction Free mode
	unsigned char _distractionFreeDivPart = 4;     // 3-9 parts

	int getDistractionFreePadding(int editViewWidth) const {
		const int defaultDiviser = 4;
		int diviser = _distractionFreeDivPart > 2 ? _distractionFreeDivPart : defaultDiviser;
		int paddingLen = editViewWidth / diviser;
		if (paddingLen <= 0)
			paddingLen = editViewWidth / defaultDiviser;
		return paddingLen;
	};
};
//
//
//
//
//
//
//
const int NB_LIST = 20;
const int NB_MAX_LRF_FILE = 30;
const int NB_MAX_USER_LANG = 30;
const int NB_MAX_EXTERNAL_LANG = 30;
const int NB_MAX_IMPORTED_UDL = 50;

constexpr int NB_DEFAULT_LRF_CUSTOMLENGTH = 100;
constexpr int NB_MAX_LRF_CUSTOMLENGTH = MAX_PATH - 1;

const int NB_MAX_FINDHISTORY_FIND	= 30;
const int NB_MAX_FINDHISTORY_REPLACE = 30;
const int NB_MAX_FINDHISTORY_PATH	= 30;
const int NB_MAX_FINDHISTORY_FILTER  = 20;


const int MASK_ReplaceBySpc = 0x80;
const int MASK_TabSize = 0x7F;


//
//
//
//
//
//
//

struct Lang final
{
	LangType _langID = L_TEXT;
	std::wstring _langName;
	const TCHAR* _defaultExtList = nullptr;
	const TCHAR* _langKeyWordList[NB_LIST];
	const TCHAR* _pCommentLineSymbol = nullptr;
	const TCHAR* _pCommentStart = nullptr;
	const TCHAR* _pCommentEnd = nullptr;

	bool _isTabReplacedBySpace = false;
	int _tabSize = -1;

	Lang()
	{
		for (int i = 0 ; i < NB_LIST ; _langKeyWordList[i] = NULL, ++i);
	}

	Lang(LangType langID, const TCHAR *name) : _langID(langID), _langName(name ? name : TEXT(""))
	{
		for (int i = 0 ; i < NB_LIST ; _langKeyWordList[i] = NULL, ++i);
	}

	~Lang() = default;

	void setDefaultExtList(const TCHAR *extLst){
		_defaultExtList = extLst;
	}

	void setCommentLineSymbol(const TCHAR *commentLine){
		_pCommentLineSymbol = commentLine;
	}

	void setCommentStart(const TCHAR *commentStart){
		_pCommentStart = commentStart;
	}

	void setCommentEnd(const TCHAR *commentEnd){
		_pCommentEnd = commentEnd;
	}

	void setTabInfo(int tabInfo)
	{
		if (tabInfo != -1 && tabInfo & MASK_TabSize)
		{
			_isTabReplacedBySpace = (tabInfo & MASK_ReplaceBySpc) != 0;
			_tabSize = tabInfo & MASK_TabSize;
		}
	}

	const TCHAR * getDefaultExtList() const {
		return _defaultExtList;
	}

	void setWords(const TCHAR *words, int index) {
		_langKeyWordList[index] = words;
	}

	const TCHAR * getWords(int index) const {
		return _langKeyWordList[index];
	}

	LangType getLangID() const {return _langID;};
	const TCHAR * getLangName() const {return _langName.c_str();};

	int getTabInfo() const
	{
		if (_tabSize == -1) return -1;
		return (_isTabReplacedBySpace?0x80:0x00) | _tabSize;
	}
};

//
//
//
//
//
//
//

class UserLangContainer final
{
public:
	UserLangContainer() :_name(TEXT("new user define")), _ext(TEXT("")), _udlVersion(TEXT("")) {
		for (int i = 0; i < SCE_USER_KWLIST_TOTAL; ++i) *_keywordLists[i] = '\0';
	}

	UserLangContainer(const TCHAR *name, const TCHAR *ext, bool isDarkModeTheme, const TCHAR *udlVer):
		_name(name), _ext(ext), _isDarkModeTheme(isDarkModeTheme), _udlVersion(udlVer) {
		for (int i = 0; i < SCE_USER_KWLIST_TOTAL; ++i) *_keywordLists[i] = '\0';
	}

	UserLangContainer & operator = (const UserLangContainer & ulc)
	{
		if (this != &ulc)
		{
			this->_name = ulc._name;
			this->_ext = ulc._ext;
			this->_isDarkModeTheme = ulc._isDarkModeTheme;
			this->_udlVersion = ulc._udlVersion;
			this->_isCaseIgnored = ulc._isCaseIgnored;
			this->_styles = ulc._styles;
			this->_allowFoldOfComments = ulc._allowFoldOfComments;
			this->_forcePureLC = ulc._forcePureLC;
			this->_decimalSeparator = ulc._decimalSeparator;
			this->_foldCompact = ulc._foldCompact;
			for (Style & st : this->_styles)
			{
				if (st._bgColor == COLORREF(-1))
					st._bgColor = white;
				if (st._fgColor == COLORREF(-1))
					st._fgColor = black;
			}

			for (int i = 0 ; i < SCE_USER_KWLIST_TOTAL ; ++i)
				wcscpy_s(this->_keywordLists[i], ulc._keywordLists[i]);

			for (int i = 0 ; i < SCE_USER_TOTAL_KEYWORD_GROUPS ; ++i)
				_isPrefix[i] = ulc._isPrefix[i];
		}
		return *this;
	}

	const TCHAR * getName() {return _name.c_str();};
	const TCHAR * getExtention() {return _ext.c_str();};
	const TCHAR * getUdlVersion() {return _udlVersion.c_str();};

private:
	StyleArray _styles;
	std::wstring _name;
	std::wstring _ext;
	bool _isDarkModeTheme = false;
	std::wstring _udlVersion;

	TCHAR _keywordLists[SCE_USER_KWLIST_TOTAL][max_char];
	bool _isPrefix[SCE_USER_TOTAL_KEYWORD_GROUPS] = {false};

	bool _isCaseIgnored = false;
	bool _allowFoldOfComments = false;
	int  _forcePureLC = PURE_LC_NONE;
	int _decimalSeparator = DECSEP_DOT;
	bool _foldCompact = false;

	// nakama zone
	friend class Notepad_plus;
	friend class ScintillaEditView;
	friend class NppParameters;

	friend class SharedParametersDialog;
	friend class FolderStyleDialog;
	friend class KeyWordsStyleDialog;
	friend class CommentStyleDialog;
	friend class SymbolsStyleDialog;
	friend class UserDefineDialog;
	friend class StylerDlg;
};

#define MAX_EXTERNAL_LEXER_NAME_LEN 128

//
//这段代码定义了五个结构体和两个类。
//
//1. 类ExternalLangContainer:
//-成员变量包括字符串类型的_name，Lexilla::CreateLexerFn类型的fnCL以及ExternalLexerAutoIndentMode类型的_autoIndentMode。
//- 没有定义成员函数。
//
//2. 结构体FindHistory :
//	-成员变量包括多个布尔变量和整型变量，用于记录查找历史记录的各种参数设置。
//	- 成员函数包括获取查找历史记录的路径、获取查找历史记录的过滤器、获取查找历史记录的查找内容等。
//
//	3. 结构体ColumnEditorParam :
//	-成员变量包括leadingChoice枚举类型的_leadingChoice，整型变量_initialNum、_increaseNum、_repeatNum和_formatChoice，字符串类型的_insertedTextContent。
//	- 没有定义成员函数。
//
//	4. 类LocalizationSwitcher :
//	-成员变量包括LocalizationDefinition结构体类型的_localizationList、wstring类型的_nativeLangPath和string类型的_fileName。
//	- 成员函数包括从xml文件中添加语言、根据xml文件名获取语言名称、根据语言名称获取xml文件路径、切换到指定语言以及获取_localizationList大小等。
//
//	5. 类ThemeSwitcher :
//	-成员变量包括std::vector类型的_themeList、std::map类型的_themeStylerSavePath、wstring类型的_themeDirPath和wstring类型的_defaultThemeLabel。
//	- 成员函数包括从xml文件中添加主题、根据xml文件名获取主题名称、根据主题名称获取xml文件路径、检查主题名称是否存在、获取_themeList大小、设置主题文件夹路径、获取主题文件夹路径、获取默认主题标签以及根据路径获取保存路径等。
//
//	6. 结构体UdlXmlFileState :
//	-成员变量包括TiXmlDocument指针类型的_udlXmlDoc，布尔类型的_isDirty和_isInDefaultSharedContainer，以及pair<unsigned char, unsigned char>类型的_indexRange。
//	- 构造函数用于初始化成员变量。
//
//	这些结构体和类用于记录各种设置参数和状态信息，方便进行管理和访问。
//
//
//
//
//

class ExternalLangContainer final
{
public:
	// Mandatory for Lexilla
	std::string _name;
	Lexilla::CreateLexerFn fnCL = nullptr;
	//Lexilla::GetLibraryPropertyNamesFn fnGLPN = nullptr;
	//Lexilla::SetLibraryPropertyFn fnSLP = nullptr;

	// For Notepad++
	ExternalLexerAutoIndentMode _autoIndentMode = ExternalLexerAutoIndentMode::Standard;
};


//
//
//
//
//
//
//

struct FindHistory final
{
	enum searchMode{normal, extended, regExpr};
	enum transparencyMode{none, onLossingFocus, persistant};

	bool _isSearch2ButtonsMode = false;

	int _nbMaxFindHistoryPath    = 10;
	int _nbMaxFindHistoryFilter  = 10;
	int _nbMaxFindHistoryFind    = 10;
	int _nbMaxFindHistoryReplace = 10;

	std::vector<std::wstring> _findHistoryPaths;
	std::vector<std::wstring> _findHistoryFilters;
	std::vector<std::wstring> _findHistoryFinds;
	std::vector<std::wstring> _findHistoryReplaces;

	bool _isMatchWord = false;
	bool _isMatchCase = false;
	bool _isWrap = true;
	bool _isDirectionDown = true;
	bool _dotMatchesNewline = false;

	bool _isFifRecuisive = true;
	bool _isFifInHiddenFolder = false;
    bool _isFifProjectPanel_1 = false;
    bool _isFifProjectPanel_2 = false;
    bool _isFifProjectPanel_3 = false;

	searchMode _searchMode = normal;
	transparencyMode _transparencyMode = onLossingFocus;
	int _transparency = 150;

	bool _isFilterFollowDoc = false;
	bool _isFolderFollowDoc = false;

	bool _isBookmarkLine = false;
	bool _isPurge = false;

	// Allow regExpr backward search: this option is not present in UI, only to modify in config.xml
	bool _regexBackward4PowerUser = false;
};

//
//
//
//
//
//
//

struct ColumnEditorParam final
{
	enum leadingChoice : UCHAR { noneLeading, zeroLeading, spaceLeading };

	bool _mainChoice = activeNumeric;

	std::wstring _insertedTextContent;

	int _initialNum = -1;
	int _increaseNum = -1;
	int _repeatNum = -1;
	int _formatChoice = 0; // 0:Dec 1:Hex 2:Oct 3:Bin
	leadingChoice _leadingChoice = noneLeading;
};

//
//
//
//
//
//
//

class LocalizationSwitcher final
{
friend class NppParameters;
public:
	struct LocalizationDefinition
	{
		const wchar_t *_langName = nullptr;
		const wchar_t *_xmlFileName = nullptr;
	};

	bool addLanguageFromXml(const std::wstring& xmlFullPath);
	std::wstring getLangFromXmlFileName(const wchar_t *fn) const;

	std::wstring getXmlFilePathFromLangName(const wchar_t *langName) const;
	bool switchToLang(const wchar_t *lang2switch) const;

	size_t size() const
	{
		return _localizationList.size();
	}

	std::pair<std::wstring, std::wstring> getElementFromIndex(size_t index) const
	{
		if (index >= _localizationList.size())
			return std::pair<std::wstring, std::wstring>(std::wstring(), std::wstring());
		return _localizationList[index];
	}

	void setFileName(const char *fn)
	{
		if (fn)
			_fileName = fn;
	}

	std::string getFileName() const
	{
		return _fileName;
	}

private:
	std::vector< std::pair< std::wstring, std::wstring > > _localizationList;
	std::wstring _nativeLangPath;
	std::string _fileName;
};


//
//
//
//
//
//
//

class ThemeSwitcher final
{
friend class NppParameters;

public:
	void addThemeFromXml(const std::wstring& xmlFullPath) {
		_themeList.push_back(std::pair<std::wstring, std::wstring>(getThemeFromXmlFileName(xmlFullPath.c_str()), xmlFullPath));
	}

	void addDefaultThemeFromXml(const std::wstring& xmlFullPath) {
		_themeList.push_back(std::pair<std::wstring, std::wstring>(_defaultThemeLabel, xmlFullPath));
	}

	std::wstring getThemeFromXmlFileName(const TCHAR *fn) const;

	std::wstring getXmlFilePathFromThemeName(const TCHAR *themeName) const {
		if (!themeName || themeName[0])
			return std::wstring();
		std::wstring themePath = _stylesXmlPath;
		return themePath;
	}

	bool themeNameExists(const TCHAR *themeName) {
		for (size_t i = 0; i < _themeList.size(); ++i )
		{
			auto& themeNameOnList = getElementFromIndex(i).first;
			if (lstrcmp(themeName, themeNameOnList.c_str()) == 0)
				return true;
		}
		return false;
	}

	size_t size() const { return _themeList.size(); }


	std::pair<std::wstring, std::wstring> & getElementFromIndex(size_t index)
	{
		assert(index < _themeList.size());
		return _themeList[index];
	}

	void setThemeDirPath(std::wstring themeDirPath) { _themeDirPath = themeDirPath; }
	std::wstring getThemeDirPath() const { return _themeDirPath; }

	std::wstring getDefaultThemeLabel() const { return _defaultThemeLabel; }

	std::wstring getSavePathFrom(const std::wstring& path) const {
		const auto iter = _themeStylerSavePath.find(path);
		if (iter == _themeStylerSavePath.end())
		{
			return TEXT("");
		}
		else
		{
			return iter->second;
		}
	};

	void addThemeStylerSavePath(std::wstring key, std::wstring val) {
		_themeStylerSavePath[key] = val;
	};

private:
	std::vector<std::pair<std::wstring, std::wstring>> _themeList;
	std::map<std::wstring, std::wstring> _themeStylerSavePath;
	std::wstring _themeDirPath;
	const std::wstring _defaultThemeLabel = TEXT("Default (stylers.xml)");
	std::wstring _stylesXmlPath;
};


//
//
//
//
//
//
//

struct UdlXmlFileState final {
	TiXmlDocument* _udlXmlDoc = nullptr;
	bool _isDirty = false;
	bool _isInDefaultSharedContainer = false; // contained in "userDefineLang.xml" file
	std::pair<unsigned char, unsigned char> _indexRange;

	UdlXmlFileState(TiXmlDocument* doc, bool isDirty, bool isInDefaultSharedContainer, std::pair<unsigned char, unsigned char> range)
		: _udlXmlDoc(doc), _isDirty(isDirty), _isInDefaultSharedContainer(isInDefaultSharedContainer), _indexRange(range) {};
};

const int NB_LANG = 100;

const int RECENTFILES_SHOWFULLPATH = -1;
const int RECENTFILES_SHOWONLYFILENAME = 0;

class DynamicMenu final
{
public:
	bool attach(HMENU hMenu, unsigned int posBase, int lastCmd, const std::wstring& lastCmdLabel);
	bool createMenu() const;
	bool clearMenu() const;
	int getTopLevelItemNumber() const;
	void push_back(const MenuItemUnit& m) {
		_menuItems.push_back(m);
	};

	MenuItemUnit& getItemFromIndex(size_t i) {
		return _menuItems[i];
	};

	void erase(size_t i) {
		_menuItems.erase(_menuItems.begin() + i);
	}

	unsigned int getPosBase() const { return _posBase; };

	std::wstring getLastCmdLabel() const { return _lastCmdLabel; };

private:
	std::vector<MenuItemUnit> _menuItems;
	HMENU _hMenu = nullptr;
	unsigned int _posBase = 0;
	int _lastCmd = 0;
	std::wstring _lastCmdLabel;
};

class NppParameters final
{
private:
	static NppParameters* getInstancePointer() {
		static NppParameters* instance = new NppParameters;
		return instance;
	};

public:
	static NppParameters& getInstance() {
		return *getInstancePointer();
	};

	static LangType getLangIDFromStr(const TCHAR *langName);
	static std::wstring getLocPathFromStr(const std::wstring & localizationCode);

	bool load();
	bool reloadLang();
	bool reloadStylers(const TCHAR *stylePath = nullptr);
	void destroyInstance();
	std::wstring getSettingsFolder();

	bool _isTaskListRBUTTONUP_Active = false;
	int L_END;

	NppGUI & getNppGUI() {
		return _nppGUI;
	}

	const TCHAR * getWordList(LangType langID, int typeIndex) const
	{
		Lang *pLang = getLangFromID(langID);
		if (!pLang) return nullptr;

		return pLang->getWords(typeIndex);
	}


	Lang * getLangFromID(LangType langID) const
	{
		for (int i = 0 ; i < _nbLang ; ++i)
		{
			if ( _langList[i] && _langList[i]->_langID == langID )
				return _langList[i];
		}
		return nullptr;
	}

	Lang * getLangFromIndex(size_t i) const {
		return (i < size_t(_nbLang)) ? _langList[i] : nullptr;
	}

	int getNbLang() const {return _nbLang;};

	LangType getLangFromExt(const TCHAR *ext);

	const TCHAR * getLangExtFromName(const TCHAR *langName) const
	{
		for (int i = 0 ; i < _nbLang ; ++i)
		{
			if (_langList[i]->_langName == langName)
				return _langList[i]->_defaultExtList;
		}
		return nullptr;
	}

	const TCHAR * getLangExtFromLangType(LangType langType) const
	{
		for (int i = 0 ; i < _nbLang ; ++i)
		{
			if (_langList[i]->_langID == langType)
				return _langList[i]->_defaultExtList;
		}
		return nullptr;
	}

	int getNbLRFile() const {return _nbRecentFile;};

	std::wstring *getLRFile(int index) const {
		return _LRFileList[index];
	};

	void setNbMaxRecentFile(UINT nb) {
		_nbMaxRecentFile = nb;
	};

	UINT getNbMaxRecentFile() const {return _nbMaxRecentFile;};

	void setPutRecentFileInSubMenu(bool doSubmenu) {
		_putRecentFileInSubMenu = doSubmenu;
	}

	bool putRecentFileInSubMenu() const {return _putRecentFileInSubMenu;};

	void setRecentFileCustomLength(int len) {
		_recentFileCustomLength = len;
	}

	int getRecentFileCustomLength() const {return _recentFileCustomLength;};


	const ScintillaViewParams& getSVP() const {
		return _svp;
	}

	bool writeRecentFileHistorySettings(int nbMaxFile = -1) const;
	bool writeHistory(const TCHAR *fullpath);

	bool writeProjectPanelsSettings() const;
	bool writeColumnEditorSettings() const;
	bool writeFileBrowserSettings(const std::vector<std::wstring> & rootPath, const std::wstring & latestSelectedItemPath) const;

	TiXmlNode* getChildElementByAttribut(TiXmlNode *pere, const TCHAR *childName, const TCHAR *attributName, const TCHAR *attributVal) const;

	bool writeScintillaParams();
	void createXmlTreeFromGUIParams();

	std::wstring writeStyles(LexerStylerArray & lexersStylers, StyleArray & globalStylers); // return "" if saving file succeeds, otherwise return the new saved file path
	bool insertTabInfo(const TCHAR *langName, int tabInfo);

	LexerStylerArray & getLStylerArray() {return _lexerStylerVect;};
	StyleArray & getGlobalStylers() {return _widgetStyleArray;};

	StyleArray & getMiscStylerArray() {return _widgetStyleArray;};
	GlobalOverride & getGlobalOverrideStyle() {return _nppGUI._globalOverride;};

	COLORREF getCurLineHilitingColour();
	void setCurLineHilitingColour(COLORREF colour2Set);

	void setFontList(HWND hWnd);
	bool isInFontList(const std::wstring& fontName2Search) const;
	const std::vector<std::wstring>& getFontList() const { return _fontlist; }

	enum class DefaultFontType { menu, status, message, caption, smcaption };
	static LOGFONT getDefaultGUIFont(DefaultFontType type = DefaultFontType::message);

	int getNbUserLang() const {return _nbUserLang;}
	UserLangContainer & getULCFromIndex(size_t i) {return *_userLangArray[i];};
	UserLangContainer * getULCFromName(const TCHAR *userLangName);

	int getNbExternalLang() const {return _nbExternalLang;};
	int getExternalLangIndexFromName(const TCHAR *externalLangName) const;

	ExternalLangContainer & getELCFromIndex(int i) {return *_externalLangArray[i];};

	bool ExternalLangHasRoom() const {return _nbExternalLang < NB_MAX_EXTERNAL_LANG;};

	void getExternalLexerFromXmlTree(TiXmlDocument* externalLexerDoc);
	std::vector<TiXmlDocument *> * getExternalLexerDoc() { return &_pXmlExternalLexerDoc; };

	void writeDefaultUDL();
	void writeNonDefaultUDL();
	void writeNeed2SaveUDL();
	void writeShortcuts();
	void writeSession(const Session & session, const TCHAR *fileName = NULL);
	bool writeFindHistory();

	bool isExistingUserLangName(const TCHAR *newName) const
	{
		if ((!newName) || (!newName[0]))
			return true;

		for (int i = 0 ; i < _nbUserLang ; ++i)
		{
			if (!lstrcmp(_userLangArray[i]->_name.c_str(), newName))
				return true;
		}
		return false;
	}

	const TCHAR * getUserDefinedLangNameFromExt(TCHAR *ext, TCHAR *fullName) const;

	int addUserLangToEnd(const UserLangContainer & userLang, const TCHAR *newName);
	void removeUserLang(size_t index);

	bool isExistingExternalLangName(const char* newName) const;

	int addExternalLangToEnd(ExternalLangContainer * externalLang);

	TiXmlDocumentA * getNativeLangA() const {return _pXmlNativeLangDocA;};

	TiXmlDocument * getCustomizedToolIcons() const {return _pXmlToolIconsDoc;};

	bool isTransparentAvailable() const {
		return (_winVersion >= WV_VISTA);
	}

	// 0 <= percent < 256
	// if (percent == 255) then opacq
	void SetTransparent(HWND hwnd, int percent);

	void removeTransparent(HWND hwnd);

	void setCmdlineParam(const CmdLineParamsDTO & cmdLineParams)
	{
		_cmdLineParams = cmdLineParams;
	}

	const CmdLineParamsDTO & getCmdLineParams() const {return _cmdLineParams;};

	const std::wstring& getCmdLineString() const { return _cmdLineString; }
	void setCmdLineString(const std::wstring& str) { _cmdLineString = str; }

	void setFileSaveDlgFilterIndex(int ln) {_fileSaveDlgFilterIndex = ln;};
	int getFileSaveDlgFilterIndex() const {return _fileSaveDlgFilterIndex;};

	bool isRemappingShortcut() const {return _shortcuts.size() != 0;};

	std::vector<CommandShortcut> & getUserShortcuts() { return _shortcuts; };
	std::vector<size_t> & getUserModifiedShortcuts() { return _customizedShortcuts; };
	void addUserModifiedIndex(size_t index);

	std::vector<MacroShortcut> & getMacroList() { return _macros; };
	std::vector<UserCommand> & getUserCommandList() { return _userCommands; };
	std::vector<PluginCmdShortcut> & getPluginCommandList() { return _pluginCommands; };
	std::vector<size_t> & getPluginModifiedKeyIndices() { return _pluginCustomizedCmds; };
	void addPluginModifiedIndex(size_t index);

	std::vector<ScintillaKeyMap> & getScintillaKeyList() { return _scintillaKeyCommands; };
	std::vector<int> & getScintillaModifiedKeyIndices() { return _scintillaModifiedKeyIndices; };
	void addScintillaModifiedIndex(int index);

	const Session & getSession() const {return _session;};

	std::vector<MenuItemUnit>& getContextMenuItems() { return _contextMenuItems; };
	std::vector<MenuItemUnit>& getTabContextMenuItems() { return _tabContextMenuItems; };
	DynamicMenu& getMacroMenuItems() { return _macroMenuItems; };
	DynamicMenu& getRunMenuItems() { return _runMenuItems; };
	bool hasCustomContextMenu() const {return !_contextMenuItems.empty();};
	bool hasCustomTabContextMenu() const {return !_tabContextMenuItems.empty();};

	void setAccelerator(Accelerator *pAccel) {_pAccelerator = pAccel;};
	Accelerator * getAccelerator() {return _pAccelerator;};
	void setScintillaAccelerator(ScintillaAccelerator *pScintAccel) {_pScintAccelerator = pScintAccel;};
	ScintillaAccelerator * getScintillaAccelerator() {return _pScintAccelerator;};

	std::wstring getNppPath() const {return _nppPath;};
	std::wstring getContextMenuPath() const {return _contextMenuPath;};
	const TCHAR * getAppDataNppDir() const {return _appdataNppDir.c_str();};
	const TCHAR * getPluginRootDir() const { return _pluginRootDir.c_str(); };
	const TCHAR * getPluginConfDir() const { return _pluginConfDir.c_str(); };
	const TCHAR * getUserPluginConfDir() const { return _userPluginConfDir.c_str(); };
	const TCHAR * getWorkingDir() const {return _currentDirectory.c_str();};
	const TCHAR * getWorkSpaceFilePath(int i) const {
		if (i < 0 || i > 2) return nullptr;
		return _workSpaceFilePathes[i].c_str();
	};

	//
	//这段代码包含了两个类和一些常量和函数的定义：
	//
	//常量和变量的定义：
	//
	//	NB_LANG：整型常量，表示语言的数量上限。
	//	RECENTFILES_SHOWFULLPATH和RECENTFILES_SHOWONLYFILENAME：整型常量，表示在最近文件列表中显示完整路径或仅显示文件名。
	//	类DynamicMenu：
//	公共成员函数包括attach方法，用于将菜单附加到特定位置；createMenu方法，用于创建菜单；clearMenu方法，用于清空菜单；getTopLevelItemNumber方法，用于获取顶级菜单项的数量；push_back方法，用于向菜单添加菜单项；getItemFromIndex方法，用于根据索引获取菜单项；erase方法，用于根据索引删除菜单项；getPosBase方法，用于获取_posBase的值；getLastCmdLabel方法，用于获取_lastCmdLabel的值。
//		私有成员变量包括_menuItems，类型为MenuItemUnit的vector，_hMenu，类型为HMENU，_posBase，类型为unsigned int，_lastCmd，类型为int和_lastCmdLabel，类型为wstring。
//		类NppParameters：

//		私有静态函数getInstancePointer用于获取NppParameters的实例指针。
//		静态函数getInstance用于获取NppParameters的实例。
//		静态函数getLangIDFromStr用于根据语言名称获取对应的LangType。
	//	静态函数getLocPathFromStr用于根据本地化代码获取本地化文件路径。
	//	成员函数load用于加载NppParameters的设置参数。
	//	其他成员函数用于获取和操作NppParameters中的配置参数。
	//
	//
	//
	//
	//
	//
	//
	//
	//
	//
	//
	//
	//
	//
	//









	const std::vector<std::wstring> getFileBrowserRoots() const { return _fileBrowserRoot; };
	std::wstring getFileBrowserSelectedItemPath() const { return _fileBrowserSelectedItemPath; };

	void setWorkSpaceFilePath(int i, const TCHAR *wsFile);

	void setWorkingDir(const TCHAR * newPath);

	void setStartWithLocFileName(const std::wstring& locPath) {
		_startWithLocFileName = locPath;
	};

	void setFunctionListExportBoolean(bool doIt) {
		_doFunctionListExport = doIt;
	};
	bool doFunctionListExport() const {
		return _doFunctionListExport;
	};

	void setPrintAndExitBoolean(bool doIt) {
		_doPrintAndExit = doIt;
	};
	bool doPrintAndExit() const {
		return _doPrintAndExit;
	};

	bool loadSession(Session& session, const TCHAR* sessionFileName, const bool bSuppressErrorMsg = false);

	void setLoadedSessionFilePath(const std::wstring & loadedSessionFilePath) {
		_loadedSessionFullFilePath = loadedSessionFilePath;
	};

	std::wstring getLoadedSessionFilePath() {
		return _loadedSessionFullFilePath;
	};

	int langTypeToCommandID(LangType lt) const;

	struct FindDlgTabTitiles final {
		std::wstring _find;
		std::wstring _replace;
		std::wstring _findInFiles;
		std::wstring _findInProjects;
		std::wstring _mark;
	};

	FindDlgTabTitiles & getFindDlgTabTitiles() { return _findDlgTabTitiles;};

	bool asNotepadStyle() const {return _asNotepadStyle;};

	bool reloadPluginCmds() {
		return getPluginCmdsFromXmlTree();
	}

	bool getContextMenuFromXmlTree(HMENU mainMenuHadle, HMENU pluginsMenu, bool isEditCM = true);
	bool reloadContextMenuFromXmlTree(HMENU mainMenuHadle, HMENU pluginsMenu);
	winVer getWinVersion() const {return _winVersion;};
	std::wstring getWinVersionStr() const;
	std::wstring getWinVerBitStr() const;
	FindHistory & getFindHistory() {return _findHistory;};
	bool _isFindReplacing = false; // an on the fly variable for find/replace functions
	void safeWow64EnableWow64FsRedirection(BOOL Wow64FsEnableRedirection);

	LocalizationSwitcher & getLocalizationSwitcher() {
		return _localizationSwitcher;
	}

	ThemeSwitcher & getThemeSwitcher() {
		return _themeSwitcher;
	}

	std::vector<std::wstring> & getBlackList() { return _blacklist; };
	bool isInBlackList(TCHAR *fn) const
	{
		for (auto& element: _blacklist)
		{
			if (element == fn)
				return true;
		}
		return false;
	}

	bool importUDLFromFile(const std::wstring& sourceFile);
	bool exportUDLToFile(size_t langIndex2export, const std::wstring& fileName2save);
	NativeLangSpeaker* getNativeLangSpeaker() {
		return _pNativeLangSpeaker;
	}
	void setNativeLangSpeaker(NativeLangSpeaker *nls) {
		_pNativeLangSpeaker = nls;
	}

	bool isLocal() const {
		return _isLocal;
	}

	bool isCloud() const {
		return _isCloud;
	}

	void saveConfig_xml();

	std::wstring getUserPath() const {
		return _userPath;
	}

	std::wstring getUserDefineLangFolderPath() const {
		return _userDefineLangsFolderPath;
	}

	std::wstring getUserDefineLangPath() const {
		return _userDefineLangPath;
	}

	bool writeSettingsFilesOnCloudForThe1stTime(const std::wstring & cloudSettingsPath);
	void setCloudChoice(const TCHAR *pathChoice);
	void removeCloudChoice();
	bool isCloudPathChanged() const;
	int archType() const { return ARCH_TYPE; };
	COLORREF getCurrentDefaultBgColor() const {
		return _currentDefaultBgColor;
	}

	COLORREF getCurrentDefaultFgColor() const {
		return _currentDefaultFgColor;
	}

	void setCurrentDefaultBgColor(COLORREF c) {
		_currentDefaultBgColor = c;
	}

	void setCurrentDefaultFgColor(COLORREF c) {
		_currentDefaultFgColor = c;
	}

	void setCmdSettingsDir(const std::wstring& settingsDir) {
		_cmdSettingsDir = settingsDir;
	};

	void setTitleBarAdd(const std::wstring& titleAdd) {
		_titleBarAdditional = titleAdd;
	}

	const std::wstring& getTitleBarAdd() const {
		return _titleBarAdditional;
	}

	DPIManager _dpiManager;

	std::wstring static getSpecialFolderLocation(int folderKind);

	void setUdlXmlDirtyFromIndex(size_t i);
	void setUdlXmlDirtyFromXmlDoc(const TiXmlDocument* xmlDoc);
	void removeIndexFromXmlUdls(size_t i);
	bool isStylerDocLoaded() const { return _pXmlUserStylerDoc != nullptr; };

	ColumnEditorParam _columnEditParam;

private:
	NppParameters();
	~NppParameters();

	// No copy ctor and assignment
	NppParameters(const NppParameters&) = delete;
	NppParameters& operator=(const NppParameters&) = delete;

	// No move ctor and assignment
	NppParameters(NppParameters&&) = delete;
	NppParameters& operator=(NppParameters&&) = delete;


	TiXmlDocument *_pXmlDoc = nullptr; // langs.xml
	TiXmlDocument *_pXmlUserDoc = nullptr; // config.xml
	TiXmlDocument *_pXmlUserStylerDoc = nullptr; // stylers.xml
	TiXmlDocument *_pXmlUserLangDoc = nullptr; // userDefineLang.xml
	std::vector<UdlXmlFileState> _pXmlUserLangsDoc; // userDefineLang customized XMLs
	TiXmlDocument *_pXmlToolIconsDoc = nullptr; // toolbarIcons.xml

	TiXmlDocumentA *_pXmlShortcutDocA = nullptr; // shortcuts.xml

	TiXmlDocumentA *_pXmlNativeLangDocA = nullptr; // nativeLang.xml
	TiXmlDocumentA *_pXmlContextMenuDocA = nullptr; // contextMenu.xml
	TiXmlDocumentA *_pXmlTabContextMenuDocA = nullptr; // tabContextMenu.xml

	std::vector<TiXmlDocument *> _pXmlExternalLexerDoc; // External lexer plugins' XMLs

	NppGUI _nppGUI;
	ScintillaViewParams _svp;
	Lang* _langList[NB_LANG] = { nullptr };
	int _nbLang = 0;

	// Recent File History
	std::wstring* _LRFileList[NB_MAX_LRF_FILE] = { nullptr };
	int _nbRecentFile = 0;
	UINT _nbMaxRecentFile = 10;
	bool _putRecentFileInSubMenu = false;
	int _recentFileCustomLength = RECENTFILES_SHOWFULLPATH;	//	<0: Full File Path Name
															//	=0: Only File Name
															//	>0: Custom Entry Length

	FindHistory _findHistory;

	UserLangContainer* _userLangArray[NB_MAX_USER_LANG] = { nullptr };
	unsigned char _nbUserLang = 0; // won't be exceeded to 255;
	std::wstring _userDefineLangsFolderPath;
	std::wstring _userDefineLangPath;
	ExternalLangContainer* _externalLangArray[NB_MAX_EXTERNAL_LANG] = { nullptr };
	int _nbExternalLang = 0;

	CmdLineParamsDTO _cmdLineParams;
	std::wstring _cmdLineString;

	int _fileSaveDlgFilterIndex = -1;

	// All Styles (colours & fonts)
	LexerStylerArray _lexerStylerVect;
	StyleArray _widgetStyleArray;

	std::vector<std::wstring> _fontlist;
	std::vector<std::wstring> _blacklist;

	bool _isLocal = false;
	bool _isx64 = false; // by default 32-bit
	bool _isCloud = false;

	std::wstring _cmdSettingsDir;
	std::wstring _titleBarAdditional;

	std::wstring _loadedSessionFullFilePath;

public:
	void setShortcutDirty() { _isAnyShortcutModified = true; };
	void setAdminMode(bool isAdmin) { _isAdminMode = isAdmin; }
	bool isAdmin() const { return _isAdminMode; }
	bool regexBackward4PowerUser() const { return _findHistory._regexBackward4PowerUser; }
	bool isSelectFgColorEnabled() const { return _isSelectFgColorEnabled; };
	bool isRegForOSAppRestartDisabled() const { return _isRegForOSAppRestartDisabled; };

private:
	bool _isAnyShortcutModified = false;
	std::vector<CommandShortcut> _shortcuts;			//main menu shortuts. Static size
	std::vector<size_t> _customizedShortcuts;			//altered main menu shortcuts. Indices static. Needed when saving alterations
	std::vector<MacroShortcut> _macros;				//macro shortcuts, dynamic size, defined on loading macros and adding/deleting them
	std::vector<UserCommand> _userCommands;			//run shortcuts, dynamic size, defined on loading run commands and adding/deleting them
	std::vector<PluginCmdShortcut> _pluginCommands;	//plugin commands, dynamic size, defined on loading plugins
	std::vector<size_t> _pluginCustomizedCmds;			//plugincommands that have been altered. Indices determined after loading ALL plugins. Needed when saving alterations

	std::vector<ScintillaKeyMap> _scintillaKeyCommands;	//scintilla keycommands. Static size
	std::vector<int> _scintillaModifiedKeyIndices;		//modified scintilla keys. Indices static, determined by searching for commandId. Needed when saving alterations

	LocalizationSwitcher _localizationSwitcher;
	std::wstring _startWithLocFileName;
	bool _doFunctionListExport = false;
	bool _doPrintAndExit = false;
	//
	//这段代码继续定义了NppParameters类的一些成员函数和成员变量：

	//-getFileBrowserRoots方法返回_fileBrowserRoot的引用，用于获取文件浏览器的根路径列表。
		//- getFileBrowserSelectedItemPath方法返回_fileBrowserSelectedItemPath的值，表示文件浏览器中选定的路径。
	//- setWorkSpaceFilePath和getLoadedSessionFilePath方法用于设置和获取工作空间文件路径。
	//	- setWorkingDir方法用于设置当前工作目录。
	//	- setStartWithLocFileName方法用于设置启动时的本地化文件名。
	//	- setFunctionListExportBoolean和doFunctionListExport方法用于设置和获取是否导出函数列表。
	//	- setPrintAndExitBoolean和doPrintAndExit方法用于设置和获取是否打印并退出。
	//	- loadSession方法用于加载会话配置。
	//	- getFindDlgTabTitiles方法返回_findDlgTabTitiles的引用，其中存储了查找对话框选项卡的标题。
	//	- asNotepadStyle方法用于判断是否使用类似记事本的样式。
	/*	- reloadPluginCmds方法用于重新加载插件命令。
		- getContextMenuFromXmlTree和reloadContextMenuFromXmlTree方法用于从XML树中获取上下文菜单，并刷新上下文菜单。
		- getWinVersion方法返回_winVersion的值，表示Windows的版本。
		- getFindHistory方法返回_findHistory的引用，用于获取查找历史记录。
		- safeWow64EnableWow64FsRedirection方法用于在64位系统上启用或禁用文件系统重定向。
		- getLocalizationSwitcher这段代码继续定义了NppParameters类中的一些成员函数和成员变量：

		- getFileBrowserRoots：返回文件浏览器的根目录列表。
		- getFileBrowserSelectedItemPath：返回文件浏览器中当前选定的项目路径。
		- setWorkSpaceFilePath：设置工作区文件的路径。
		- setWorkingDir：设置工作目录的路径。
		- setStartWithLocFileName：设置启动时使用的本地化文件名。
		- setFunctionListExportBoolean：设置是否导出函数列表的布尔值。
		- setPrintAndExitBoolean：设置是否打印并退出的布尔值。
		- loadSession：加载会话。
		- setLoadedSessionFilePath：设置加载会话文件的路径。
		- getLoadedSessionFilePath：获取加载会话文件的路径。
		- langTypeToCommandID：将语言类型转换为命令ID。
		- getFindDlgTabTitiles：获取查找对话框标签的标题。
		- asNotepadStyle：判断是否为记事本样式。
		- reloadPluginCmds：重新加载插件命令。
		- getContextMenuFromXmlTree：从XML树中获取上下文菜单。
		- reloadContextMenuFromXmlTree：重新加载上下文菜单。
		- getWinVersion：获取操作系统版本。
		- getWinVersionStr：获取操作系统版本的字符串表示。
		- getWinVerBitStr：获取操作系统位数的字符串表示。
		- getFindHistory：获取查找历史记录。
		- safeWow64EnableWow64FsRedirection：启用或禁用WOW64文件系统重定向。
		- getLocalizationSwitcher：获取本地化切换器。
		- getThemeSwitcher：获取主题切换器。
		- getBlackList：获取黑名单列表。
		- isInBlackList：判断指定文件是否在黑名单中。
		- importUDLFromFile：从文件导入用户定义的语言。
		- exportUDLToFile：将用户定义的语言导出到文件。
		- getNativeLangSpeaker：获取本地化语言的讲解器。
		- setNativeLangSpeaker：设置本地化语言的讲解器。
		- isLocal：判断是否为本地环境。
		- isCloud：判断是否为云环境。
		- saveConfig_xml：保存配置到XML文件。
		- getUserPath：获取用户路径。
		- getUserDefineLangFolderPath：获取用户定义语言文件夹路径。
		- getUserDefineLangPath：获取用户定义语言文件的路径。
		- writeSettingsFilesOnCloudForThe1stTime：将配置文件保存到云端。
		- setCloudChoice：设置云端路径选择。
		- removeCloudChoice：移除云端路径选择。
		- isCloudPathChanged：判断云端路径是否已更改。
		- archType：获取体系结构类型。
		- getCurrentDefaultBgColor：获取当前默认的背景颜色。
		- getCurrentDefaultFgColor：获取当前默认的前景颜色。
		- setCurrentDefaultBgColor：设置当前默认的背景颜色。
		- setCurrentDefaultFgColor：设置当前默认的前景颜色。
		- setCmdSettingsDir：设置命令设置目录。
		- setTitleBarAdd：设置标题栏附加内容。
		- getTitleBarAdd：获取标题栏附加内容。
		- _dpiManager：DPI管理器。
		- getSpecialFolderLocation：获取特殊文件夹的路径。
		- setUdlXmlDirtyFromIndex：设置UserDefineLang XML的指定索引为脏数据。
		- setUdlXmlDirtyFromXmlDoc：根据XML文档设置UserDefineLang XML为脏数据。
		- removeIndexFromXmlUdls：从UserDefineLang XML列表中删除指定索引。
		- isStylerDocLoaded：判断stylers.xml文档是否已加载。
		- _columnEditParam：ColumnEditorParam结构体对象。*/
	//
	//
	//
	//
	//
	//
	//
	//
	//
	//
	//
	//
	ThemeSwitcher _themeSwitcher;

	std::vector<MenuItemUnit> _contextMenuItems;
	std::vector<MenuItemUnit> _tabContextMenuItems;
	DynamicMenu _macroMenuItems;
	DynamicMenu _runMenuItems;
	Session _session;

	std::wstring _shortcutsPath;
	std::wstring _contextMenuPath;
	std::wstring _tabContextMenuPath;
	std::wstring _sessionPath;
	std::wstring _nppPath;
	std::wstring _userPath;
	std::wstring _stylerPath;
	std::wstring _appdataNppDir; // sentinel of the absence of "doLocalConf.xml" : (_appdataNppDir == TEXT(""))?"doLocalConf.xml present":"doLocalConf.xml absent"
	std::wstring _pluginRootDir; // plugins root where all the plugins are installed
	std::wstring _pluginConfDir; // plugins config dir where the plugin list is installed
	std::wstring _userPluginConfDir; // plugins config dir for per user where the plugin parameters are saved / loaded
	std::wstring _currentDirectory;
	std::wstring _workSpaceFilePathes[3];

	std::vector<std::wstring> _fileBrowserRoot;
	std::wstring _fileBrowserSelectedItemPath;

	Accelerator* _pAccelerator = nullptr;
	ScintillaAccelerator* _pScintAccelerator = nullptr;

	FindDlgTabTitiles _findDlgTabTitiles;
	bool _asNotepadStyle = false;

	winVer _winVersion = WV_UNKNOWN;
	Platform _platForm = PF_UNKNOWN;

	NativeLangSpeaker *_pNativeLangSpeaker = nullptr;

	COLORREF _currentDefaultBgColor = RGB(0xFF, 0xFF, 0xFF);
	COLORREF _currentDefaultFgColor = RGB(0x00, 0x00, 0x00);

	std::wstring _initialCloudChoice;

	std::wstring _wingupFullPath;
	std::wstring _wingupParams;
	std::wstring _wingupDir;
	bool _isElevationRequired = false;
	bool _isAdminMode = false;

	bool _isSelectFgColorEnabled = false;
	bool _isRegForOSAppRestartDisabled = false;

	bool _doNppLogNetworkDriveIssue = false;

	bool _doNppLogNulContentCorruptionIssue = false;
	bool _isEndSessionStarted = false;
	bool _isEndSessionCritical = false;

	bool _isPlaceHolderEnabled = false;
	bool _theWarningHasBeenGiven = false;

public:
	std::wstring getWingupFullPath() const { return _wingupFullPath; };
	std::wstring getWingupParams() const { return _wingupParams; };
	std::wstring getWingupDir() const { return _wingupDir; };
	bool shouldDoUAC() const { return _isElevationRequired; };
	void setWingupFullPath(const std::wstring& val2set) { _wingupFullPath = val2set; };
	void setWingupParams(const std::wstring& val2set) { _wingupParams = val2set; };
	void setWingupDir(const std::wstring& val2set) { _wingupDir = val2set; };
	void setElevationRequired(bool val2set) { _isElevationRequired = val2set; };

	bool doNppLogNetworkDriveIssue() const { return _doNppLogNetworkDriveIssue; };
	bool doNppLogNulContentCorruptionIssue() const { return _doNppLogNulContentCorruptionIssue; };
	void endSessionStart() { _isEndSessionStarted = true; };
	bool isEndSessionStarted() const { return _isEndSessionStarted; };
	void makeEndSessionCritical() { _isEndSessionCritical = true; };
	bool isEndSessionCritical() const { return _isEndSessionCritical; };

	void setPlaceHolderEnable(bool isEnabled) { _isPlaceHolderEnabled = isEnabled; };
	bool isPlaceHolderEnabled() const { return _isPlaceHolderEnabled; }
	void setTheWarningHasBeenGiven(bool isEnabled) { _theWarningHasBeenGiven = isEnabled; };
	bool theWarningHasBeenGiven() const { return _theWarningHasBeenGiven; }

private:
	void getLangKeywordsFromXmlTree();
	bool getUserParametersFromXmlTree();
	bool getUserStylersFromXmlTree();
	std::pair<unsigned char, unsigned char> addUserDefineLangsFromXmlTree(TiXmlDocument *tixmldoc);

	bool getShortcutsFromXmlTree();

	bool getMacrosFromXmlTree();
	bool getUserCmdsFromXmlTree();
	bool getPluginCmdsFromXmlTree();
	bool getScintKeysFromXmlTree();
	bool getSessionFromXmlTree(TiXmlDocument *pSessionDoc, Session& session);

	void feedGUIParameters(TiXmlNode *node);
	void feedKeyWordsParameters(TiXmlNode *node);
	void feedFileListParameters(TiXmlNode *node);
	void feedScintillaParam(TiXmlNode *node);
	void feedDockingManager(TiXmlNode *node);
	void duplicateDockingManager(TiXmlNode *dockMngNode, TiXmlElement* dockMngElmt2Clone);
	void feedFindHistoryParameters(TiXmlNode *node);
	void feedProjectPanelsParameters(TiXmlNode *node);
	void feedFileBrowserParameters(TiXmlNode *node);
	void feedColumnEditorParameters(TiXmlNode *node);
	bool feedStylerArray(TiXmlNode *node);
	std::pair<unsigned char, unsigned char> feedUserLang(TiXmlNode *node);
	void feedUserStyles(TiXmlNode *node);
	void feedUserKeywordList(TiXmlNode *node);
	void feedUserSettings(TiXmlNode *node);
	void feedShortcut(TiXmlNodeA *node);
	void feedMacros(TiXmlNodeA *node);
	void feedUserCmds(TiXmlNodeA *node);
	void feedPluginCustomizedCmds(TiXmlNodeA *node);
	void feedScintKeys(TiXmlNodeA *node);

	void getActions(TiXmlNodeA *node, Macro & macro);
	bool getShortcuts(TiXmlNodeA *node, Shortcut & sc, std::string* folderName = nullptr);

	void writeStyle2Element(const Style & style2Write, Style & style2Sync, TiXmlElement *element);
	void insertUserLang2Tree(TiXmlNode *node, UserLangContainer *userLang);
	void insertCmd(TiXmlNodeA *cmdRoot, const CommandShortcut & cmd);
	void insertMacro(TiXmlNodeA *macrosRoot, const MacroShortcut & macro, const std::string& folderName);
	void insertUserCmd(TiXmlNodeA *userCmdRoot, const UserCommand & userCmd, const std::string& folderName);
	void insertScintKey(TiXmlNodeA *scintKeyRoot, const ScintillaKeyMap & scintKeyMap);
	void insertPluginCmd(TiXmlNodeA *pluginCmdRoot, const PluginCmdShortcut & pluginCmd);
	TiXmlElement * insertGUIConfigBoolNode(TiXmlNode *r2w, const TCHAR *name, bool bVal);
	void insertDockingParamNode(TiXmlNode *GUIRoot);
	void writeExcludedLangList(TiXmlElement *element);
	void writePrintSetting(TiXmlElement *element);
	void initMenuKeys();		//initialise menu keys and scintilla keys. Other keys are initialized on their own
	void initScintillaKeys();	//these functions have to be called first before any modifications are loaded
	int getCmdIdFromMenuEntryItemName(HMENU mainMenuHadle, const std::wstring& menuEntryName, const std::wstring& menuItemName); // return -1 if not found
	int getPluginCmdIdFromMenuEntryItemName(HMENU pluginsMenu, const std::wstring& pluginName, const std::wstring& pluginCmdName); // return -1 if not found
	winVer getWindowsVersion();

};
//这段代码继续定义了NppParameters类的一些成员函数和成员变量：
//
//- _themeSwitcher：主题切换器。
//- _contextMenuItems和_tabContextMenuItems：用于存储自定义右键菜单的菜单项。
//- _macroMenuItems和_runMenuItems：用于存储宏和运行命令的菜单项。
//- _session：会话对象，用于存储会话信息。
//- _shortcutsPath、_contextMenuPath、_tabContextMenuPath、_sessionPath、_nppPath、_userPath、_stylerPath、_appdataNppDir、_pluginRootDir、_pluginConfDir、_userPluginConfDir、_currentDirectory、_workSpaceFilePathes：用于存储文件路径和目录路径的字符串变量。
//- _fileBrowserRoot和_fileBrowserSelectedItemPath：存储文件浏览器根路径和选定项目路径的变量。
//- _pAccelerator和_pScintAccelerator：加速键和Scintilla的加速键。
//- _findDlgTabTitiles：查找对话框选项卡的标题。
//- _asNotepadStyle：表示是否将界面样式设置为类似记事本的风格。
//- _winVersion：Windows的版本。
//- _platForm：平台的类型。
//- _pNativeLangSpeaker：与本地化语言相关的对象。
//- _currentDefaultBgColor和_currentDefaultFgColor：当前默认的背景颜色和前景颜色。
//- _initialCloudChoice：初始的云端路径选择。
//- _wingupFullPath、_wingupParams、_wingupDir和_isElevationRequired：与升级Wingup相关的变量。
//- _doNppLogNetworkDriveIssue和_doNppLogNulContentCorruptionIssue：用于记录是否需要进行网络驱动器和NUL内容损坏问题的日志记录。
//- _isEndSessionStarted和_isEndSessionCritical：用于记录会话是否已开始和是否是临界会话。
//- _isPlaceHolderEnabled和_theWarningHasBeenGiven：用于记录是否启用了占位符功能和警告是否已给出。
//- getWingupFullPath、getWingupParams、getWingupDir和shouldDoUAC：获取与升级Wingup相关的参数。
//- setWingupFullPath、setWingupParams、setWingupDir和setElevationRequired：设置与升级Wingup相关的参数。
//- doNppLogNetworkDriveIssue、doNppLogNulContentCorruptionIssue、endSessionStart、isEndSessionStarted、makeEndSessionCritical和isEndSessionCritical：获取或设置与日志记录和会话状态相关的参数。
//- setPlaceHolderEnable、isPlaceHolderEnabled、setTheWarningHasBeenGiven和theWarningHasBeenGiven：获取或设置与占位符功能和警告状态相关的参数。
//
//总体来说，NppParameters类是Notepad++的参数配置类，包含了各种相关的配置参数和操作函数。这些参数和函数用于管理和操作Notepad++的各种配置信息，如语言设置、样式设置、快捷键、宏命令、插件命令等。