1 /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
2 file Copyright.txt or https://cmake.org/licensing for details. */
3 #include "cmExtraSublimeTextGenerator.h"
11 #include "cmsys/RegularExpression.hxx"
13 #include "cmGeneratedFileStream.h"
14 #include "cmGeneratorExpression.h"
15 #include "cmGeneratorTarget.h"
16 #include "cmGlobalGenerator.h"
17 #include "cmLocalGenerator.h"
18 #include "cmMakefile.h"
19 #include "cmMessageType.h"
20 #include "cmSourceFile.h"
21 #include "cmStateTypes.h"
22 #include "cmStringAlgorithms.h"
23 #include "cmSystemTools.h"
28 Sublime Text 2 Generator
29 Author: Morné Chamberlain
30 This generator was initially based off of the CodeBlocks generator.
34 http://www.sublimetext.com/
37 http://www.sublimetext.com/docs/2/projects.html
38 http://sublimetext.info/docs/en/reference/build_systems.html
41 cmExternalMakefileProjectGeneratorFactory*
42 cmExtraSublimeTextGenerator::GetFactory()
44 static cmExternalMakefileProjectGeneratorSimpleFactory<
45 cmExtraSublimeTextGenerator>
46 factory("Sublime Text 2", "Generates Sublime Text 2 project files.");
48 if (factory.GetSupportedGlobalGenerators().empty()) {
50 factory.AddSupportedGlobalGenerator("MinGW Makefiles");
51 factory.AddSupportedGlobalGenerator("NMake Makefiles");
52 // disable until somebody actually tests it:
53 // factory.AddSupportedGlobalGenerator("MSYS Makefiles");
55 factory.AddSupportedGlobalGenerator("Ninja");
56 factory.AddSupportedGlobalGenerator("Unix Makefiles");
62 cmExtraSublimeTextGenerator::cmExtraSublimeTextGenerator()
64 this->ExcludeBuildFolder = false;
67 void cmExtraSublimeTextGenerator::Generate()
69 this->ExcludeBuildFolder = this->GlobalGenerator->GlobalSettingIsOn(
70 "CMAKE_SUBLIME_TEXT_2_EXCLUDE_BUILD_TREE");
71 this->EnvSettings = this->GlobalGenerator->GetSafeGlobalSetting(
72 "CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS");
74 // for each sub project in the project create a sublime text 2 project
75 for (auto const& it : this->GlobalGenerator->GetProjectMap()) {
76 // create a project file
77 this->CreateProjectFile(it.second);
81 void cmExtraSublimeTextGenerator::CreateProjectFile(
82 const std::vector<cmLocalGenerator*>& lgs)
84 std::string outputDir = lgs[0]->GetCurrentBinaryDirectory();
85 std::string projectName = lgs[0]->GetProjectName();
87 const std::string filename =
88 outputDir + "/" + projectName + ".sublime-project";
90 this->CreateNewProjectFile(lgs, filename);
93 void cmExtraSublimeTextGenerator::CreateNewProjectFile(
94 const std::vector<cmLocalGenerator*>& lgs, const std::string& filename)
96 const cmMakefile* mf = lgs[0]->GetMakefile();
98 cmGeneratedFileStream fout(filename);
103 const std::string& sourceRootRelativeToOutput = cmSystemTools::RelativePath(
104 lgs[0]->GetBinaryDirectory(), lgs[0]->GetSourceDirectory());
105 // Write the folder entries to the project file
107 fout << "\t\"folders\":\n\t[\n\t";
108 if (!sourceRootRelativeToOutput.empty()) {
109 fout << "\t{\n\t\t\t\"path\": \"" << sourceRootRelativeToOutput << "\"";
110 const std::string& outputRelativeToSourceRoot =
111 cmSystemTools::RelativePath(lgs[0]->GetSourceDirectory(),
112 lgs[0]->GetBinaryDirectory());
113 if ((!outputRelativeToSourceRoot.empty()) &&
114 ((outputRelativeToSourceRoot.length() < 3) ||
115 (outputRelativeToSourceRoot.substr(0, 3) != "../"))) {
116 if (this->ExcludeBuildFolder) {
117 fout << ",\n\t\t\t\"folder_exclude_patterns\": [\""
118 << outputRelativeToSourceRoot << "\"]";
122 fout << "\t{\n\t\t\t\"path\": \"./\"";
125 // End of the folders section
128 // Write the beginning of the build systems section to the project file
129 fout << ",\n\t\"build_systems\":\n\t[\n\t";
131 // Set of include directories over all targets (sublime text/sublimeclang
132 // doesn't currently support these settings per build system, only project
134 MapSourceFileFlags sourceFileFlags;
135 this->AppendAllTargets(lgs, mf, fout, sourceFileFlags);
137 // End of build_systems
139 std::string systemName = mf->GetSafeDefinition("CMAKE_SYSTEM_NAME");
140 std::vector<std::string> tokens = cmExpandedList(this->EnvSettings);
142 if (!this->EnvSettings.empty()) {
144 fout << "\n\t\"env\":";
146 fout << "\n\t\t" << systemName << ":";
148 for (std::string const& t : tokens) {
149 size_t const pos = t.find_first_of('=');
151 if (pos != std::string::npos) {
152 std::string varName = t.substr(0, pos);
153 std::string varValue = t.substr(pos + 1);
155 fout << "\n\t\t\t\"" << varName << "\":\"" << varValue << "\"";
157 std::ostringstream e;
158 e << "Could not parse Env Vars specified in "
159 "\"CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS\""
160 << ", corrupted string " << t;
161 mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
170 void cmExtraSublimeTextGenerator::AppendAllTargets(
171 const std::vector<cmLocalGenerator*>& lgs, const cmMakefile* mf,
172 cmGeneratedFileStream& fout, MapSourceFileFlags& sourceFileFlags)
174 const std::string& make = mf->GetRequiredDefinition("CMAKE_MAKE_PROGRAM");
175 std::string compiler;
177 this->AppendTarget(fout, "all", lgs[0], nullptr, make.c_str(), mf,
178 compiler.c_str(), sourceFileFlags, true);
179 this->AppendTarget(fout, "clean", lgs[0], nullptr, make.c_str(), mf,
180 compiler.c_str(), sourceFileFlags, false);
183 // add all executable and library targets and some of the GLOBAL
184 // and UTILITY targets
185 for (cmLocalGenerator* lg : lgs) {
186 cmMakefile* makefile = lg->GetMakefile();
187 const auto& targets = lg->GetGeneratorTargets();
188 for (const auto& target : targets) {
189 std::string targetName = target->GetName();
190 switch (target->GetType()) {
191 case cmStateEnums::GLOBAL_TARGET: {
192 // Only add the global targets from CMAKE_BINARY_DIR,
193 // not from the subdirs
194 if (lg->GetCurrentBinaryDirectory() == lg->GetBinaryDirectory()) {
195 this->AppendTarget(fout, targetName, lg, nullptr, make.c_str(),
196 makefile, compiler.c_str(), sourceFileFlags,
200 case cmStateEnums::UTILITY:
201 // Add all utility targets, except the Nightly/Continuous/
202 // Experimental-"sub"targets as e.g. NightlyStart
203 if ((cmHasLiteralPrefix(targetName, "Nightly") &&
204 (targetName != "Nightly")) ||
205 (cmHasLiteralPrefix(targetName, "Continuous") &&
206 (targetName != "Continuous")) ||
207 (cmHasLiteralPrefix(targetName, "Experimental") &&
208 (targetName != "Experimental"))) {
212 this->AppendTarget(fout, targetName, lg, nullptr, make.c_str(),
213 makefile, compiler.c_str(), sourceFileFlags,
216 case cmStateEnums::EXECUTABLE:
217 case cmStateEnums::STATIC_LIBRARY:
218 case cmStateEnums::SHARED_LIBRARY:
219 case cmStateEnums::MODULE_LIBRARY:
220 case cmStateEnums::OBJECT_LIBRARY: {
221 this->AppendTarget(fout, targetName, lg, target.get(), make.c_str(),
222 makefile, compiler.c_str(), sourceFileFlags,
224 std::string fastTarget = cmStrCat(targetName, "/fast");
225 this->AppendTarget(fout, fastTarget, lg, target.get(), make.c_str(),
226 makefile, compiler.c_str(), sourceFileFlags,
236 void cmExtraSublimeTextGenerator::AppendTarget(
237 cmGeneratedFileStream& fout, const std::string& targetName,
238 cmLocalGenerator* lg, cmGeneratorTarget* target, const char* make,
239 const cmMakefile* makefile, const char* /*compiler*/,
240 MapSourceFileFlags& sourceFileFlags, bool firstTarget)
243 if (target != nullptr) {
244 std::vector<cmSourceFile*> sourceFiles;
245 target->GetSourceFiles(sourceFiles,
246 makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
247 for (cmSourceFile* sourceFile : sourceFiles) {
248 auto sourceFileFlagsIter =
249 sourceFileFlags.find(sourceFile->ResolveFullPath());
250 if (sourceFileFlagsIter == sourceFileFlags.end()) {
251 sourceFileFlagsIter =
253 .insert(MapSourceFileFlags::value_type(
254 sourceFile->ResolveFullPath(), std::vector<std::string>()))
257 std::vector<std::string>& flags = sourceFileFlagsIter->second;
258 std::string flagsString =
259 this->ComputeFlagsForObject(sourceFile, lg, target);
260 std::string definesString = this->ComputeDefines(sourceFile, lg, target);
261 std::string includesString =
262 this->ComputeIncludes(sourceFile, lg, target);
264 cmsys::RegularExpression flagRegex;
265 // Regular expression to extract compiler flags from a string
266 // https://gist.github.com/3944250
267 const char* regexString =
268 R"((^|[ ])-[DIOUWfgs][^= ]+(=\"[^"]+\"|=[^"][^ ]+)?)";
269 flagRegex.compile(regexString);
270 std::string workString =
271 cmStrCat(flagsString, " ", definesString, " ", includesString);
272 while (flagRegex.find(workString)) {
273 std::string::size_type start = flagRegex.start();
274 if (workString[start] == ' ') {
277 flags.push_back(workString.substr(start, flagRegex.end() - start));
278 if (flagRegex.end() < workString.size()) {
279 workString = workString.substr(flagRegex.end());
287 // Ninja uses ninja.build files (look for a way to get the output file name
288 // from cmMakefile or something)
289 std::string makefileName;
290 if (this->GlobalGenerator->GetName() == "Ninja") {
291 makefileName = "build.ninja";
293 makefileName = "Makefile";
298 fout << "\t{\n\t\t\t\"name\": \"" << lg->GetProjectName() << " - "
299 << targetName << "\",\n";
300 fout << "\t\t\t\"cmd\": ["
301 << this->BuildMakeCommand(make, makefileName, targetName) << "],\n";
302 fout << "\t\t\t\"working_dir\": \"${project_path}\",\n";
303 fout << "\t\t\t\"file_regex\": \""
304 "^(..[^:]*)(?::|\\\\()([0-9]+)(?::|\\\\))(?:([0-9]+):)?\\\\s*(.*)"
309 // Create the command line for building the given target using the selected
311 std::string cmExtraSublimeTextGenerator::BuildMakeCommand(
312 const std::string& make, const std::string& makefile,
313 const std::string& target)
315 std::string command = cmStrCat('"', make, '"');
316 std::string generator = this->GlobalGenerator->GetName();
317 if (generator == "NMake Makefiles") {
318 std::string makefileName = cmSystemTools::ConvertToOutputPath(makefile);
319 command += R"(, "/NOLOGO", "/f", ")";
320 command += makefileName + "\"";
321 command += ", \"" + target + "\"";
322 } else if (generator == "Ninja") {
323 std::string makefileName = cmSystemTools::ConvertToOutputPath(makefile);
324 command += R"(, "-f", ")";
325 command += makefileName + "\"";
326 command += ", \"" + target + "\"";
328 std::string makefileName;
329 if (generator == "MinGW Makefiles") {
330 // no escaping of spaces in this case, see
331 // https://gitlab.kitware.com/cmake/cmake/-/issues/10014
332 makefileName = makefile;
334 makefileName = cmSystemTools::ConvertToOutputPath(makefile);
336 command += R"(, "-f", ")";
337 command += makefileName + "\"";
338 command += ", \"" + target + "\"";
343 // TODO: Most of the code is picked up from the Ninja generator, refactor it.
344 std::string cmExtraSublimeTextGenerator::ComputeFlagsForObject(
345 cmSourceFile* source, cmLocalGenerator* lg, cmGeneratorTarget* gtgt)
348 std::string language = source->GetOrDetermineLanguage();
349 if (language.empty()) {
353 // Explicitly add the explicit language flag before any other flag
354 // so user flags can override it.
355 gtgt->AddExplicitLanguageFlags(flags, *source);
357 std::string const& config =
358 lg->GetMakefile()->GetSafeDefinition("CMAKE_BUILD_TYPE");
360 lg->GetTargetCompileFlags(gtgt, config, language, flags);
362 // Add source file specific flags.
363 cmGeneratorExpressionInterpreter genexInterpreter(lg, config, gtgt,
366 const std::string COMPILE_FLAGS("COMPILE_FLAGS");
367 if (cmValue cflags = source->GetProperty(COMPILE_FLAGS)) {
368 lg->AppendFlags(flags, genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS));
371 const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
372 if (cmValue coptions = source->GetProperty(COMPILE_OPTIONS)) {
373 lg->AppendCompileOptions(
374 flags, genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS));
380 // TODO: Refactor with
381 // void cmMakefileTargetGenerator::WriteTargetLanguageFlags().
382 std::string cmExtraSublimeTextGenerator::ComputeDefines(
383 cmSourceFile* source, cmLocalGenerator* lg, cmGeneratorTarget* target)
386 std::set<std::string> defines;
387 cmMakefile* makefile = lg->GetMakefile();
388 const std::string& language = source->GetOrDetermineLanguage();
389 const std::string& config = makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
390 cmGeneratorExpressionInterpreter genexInterpreter(lg, config, target,
393 // Add preprocessor definitions for this target and configuration.
394 lg->GetTargetDefines(target, config, language, defines);
395 const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
396 if (cmValue compile_defs = source->GetProperty(COMPILE_DEFINITIONS)) {
398 defines, genexInterpreter.Evaluate(*compile_defs, COMPILE_DEFINITIONS));
401 std::string defPropName =
402 cmStrCat("COMPILE_DEFINITIONS_", cmSystemTools::UpperCase(config));
403 if (cmValue config_compile_defs = source->GetProperty(defPropName)) {
406 genexInterpreter.Evaluate(*config_compile_defs, COMPILE_DEFINITIONS));
409 std::string definesString;
410 lg->JoinDefines(defines, definesString, language);
412 return definesString;
415 std::string cmExtraSublimeTextGenerator::ComputeIncludes(
416 cmSourceFile* source, cmLocalGenerator* lg, cmGeneratorTarget* target)
419 std::vector<std::string> includes;
420 cmMakefile* makefile = lg->GetMakefile();
421 const std::string& language = source->GetOrDetermineLanguage();
422 const std::string& config = makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
423 cmGeneratorExpressionInterpreter genexInterpreter(lg, config, target,
426 // Add include directories for this source file
427 const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
428 if (cmValue cincludes = source->GetProperty(INCLUDE_DIRECTORIES)) {
429 lg->AppendIncludeDirectories(
430 includes, genexInterpreter.Evaluate(*cincludes, INCLUDE_DIRECTORIES),
434 // Add include directory flags.
435 lg->GetIncludeDirectories(includes, target, language, config);
437 std::string includesString =
438 lg->GetIncludeFlags(includes, target, language, config, false);
440 return includesString;
443 bool cmExtraSublimeTextGenerator::Open(const std::string& bindir,
444 const std::string& projectName,
447 cmValue sublExecutable =
448 this->GlobalGenerator->GetCMakeInstance()->GetCacheDefinition(
449 "CMAKE_SUBLIMETEXT_EXECUTABLE");
450 if (!sublExecutable) {
453 if (cmIsNOTFOUND(*sublExecutable)) {
457 std::string filename = bindir + "/" + projectName + ".sublime-project";
459 return cmSystemTools::FileExists(filename, true);
462 return cmSystemTools::RunSingleCommand(
463 { *sublExecutable, "--project", filename });