ccls/src/clang_format.cc

55 lines
1.7 KiB
C++
Raw Normal View History

#if USE_CLANG_CXX
#include "clang_format.h"
#include "working_files.h"
2017-12-29 21:44:28 +00:00
#include <loguru.hpp>
2018-01-01 04:17:31 +00:00
using namespace clang;
using clang::format::FormatStyle;
namespace {
2018-01-01 04:17:31 +00:00
// TODO Objective-C 'header/interface' files may use .h, we should get this from
// project information.
FormatStyle::LanguageKind getLanguageKindFromFilename(
llvm::StringRef filename) {
if (filename.endswith(".m") || filename.endswith(".mm")) {
return FormatStyle::LK_ObjC;
}
return FormatStyle::LK_Cpp;
}
} // namespace
2018-01-01 04:17:31 +00:00
std::vector<tooling::Replacement> ClangFormatDocument(
WorkingFile* working_file,
int start,
int end,
lsFormattingOptions options) {
const auto language_kind =
getLanguageKindFromFilename(working_file->filename);
FormatStyle predefined_style;
getPredefinedStyle("chromium", language_kind, &predefined_style);
2017-12-29 21:44:28 +00:00
llvm::Expected<FormatStyle> style =
2018-01-01 04:17:31 +00:00
format::getStyle("file", working_file->filename, "chromium");
2017-12-29 21:44:28 +00:00
if (!style) {
// If, for some reason, we cannot get a format style, use Chromium's with
// tab configuration provided by the client editor.
2017-12-29 21:44:28 +00:00
LOG_S(ERROR) << llvm::toString(style.takeError());
predefined_style.UseTab = options.insertSpaces
? FormatStyle::UseTabStyle::UT_Never
: FormatStyle::UseTabStyle::UT_Always;
predefined_style.IndentWidth = options.tabSize;
}
auto format_result = reformat(
style ? *style : predefined_style, working_file->buffer_content,
2018-01-01 04:17:31 +00:00
llvm::ArrayRef<tooling::Range>(tooling::Range(start, end - start)),
working_file->filename);
2018-01-01 04:17:31 +00:00
return std::vector<tooling::Replacement>(format_result.begin(),
format_result.end());
}
#endif