aboutsummaryrefslogtreecommitdiff
path: root/tools/clang-format
diff options
context:
space:
mode:
Diffstat (limited to 'tools/clang-format')
-rw-r--r--tools/clang-format/ClangFormat.cpp87
-rw-r--r--tools/clang-format/clang-format-bbedit.applescript27
-rwxr-xr-xtools/clang-format/clang-format-diff.py11
-rw-r--r--tools/clang-format/clang-format.el31
-rw-r--r--tools/clang-format/clang-format.py7
5 files changed, 134 insertions, 29 deletions
diff --git a/tools/clang-format/ClangFormat.cpp b/tools/clang-format/ClangFormat.cpp
index c4969b2c0865..57833edf0f31 100644
--- a/tools/clang-format/ClangFormat.cpp
+++ b/tools/clang-format/ClangFormat.cpp
@@ -27,22 +27,25 @@ using namespace llvm;
static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
-static cl::list<int> Offsets(
- "offset", cl::desc("Format a range starting at this file offset."));
-static cl::list<int> Lengths(
- "length", cl::desc("Format a range of this length, -1 for end of file."));
+static cl::list<unsigned>
+Offsets("offset", cl::desc("Format a range starting at this file offset. Can "
+ "only be used with one input file."));
+static cl::list<unsigned>
+Lengths("length", cl::desc("Format a range of this length. "
+ "When it's not specified, end of file is used. "
+ "Can only be used with one input file."));
static cl::opt<std::string> Style(
"style",
- cl::desc("Coding style, currently supports: LLVM, Google, Chromium."),
+ cl::desc("Coding style, currently supports: LLVM, Google, Chromium, Mozilla."),
cl::init("LLVM"));
static cl::opt<bool> Inplace("i",
- cl::desc("Inplace edit <file>, if specified."));
+ cl::desc("Inplace edit <file>s, if specified."));
static cl::opt<bool> OutputXML(
"output-replacements-xml", cl::desc("Output replacements as XML."));
-static cl::opt<std::string> FileName(cl::Positional, cl::desc("[<file>]"),
- cl::init("-"));
+static cl::list<std::string> FileNames(cl::Positional,
+ cl::desc("[<file> ...]"));
namespace clang {
namespace format {
@@ -60,12 +63,18 @@ static FormatStyle getStyle() {
FormatStyle TheStyle = getGoogleStyle();
if (Style == "LLVM")
TheStyle = getLLVMStyle();
- if (Style == "Chromium")
+ else if (Style == "Chromium")
TheStyle = getChromiumStyle();
+ else if (Style == "Mozilla")
+ TheStyle = getMozillaStyle();
+ else if (Style != "Google")
+ llvm::errs() << "Unknown style " << Style << ", using Google style.\n";
+
return TheStyle;
}
-static void format() {
+// Returns true on error.
+static bool format(std::string FileName) {
FileManager Files((FileSystemOptions()));
DiagnosticsEngine Diagnostics(
IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
@@ -74,7 +83,7 @@ static void format() {
OwningPtr<MemoryBuffer> Code;
if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
llvm::errs() << ec.message() << "\n";
- return;
+ return true;
}
FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
Lexer Lex(ID, Sources.getBuffer(ID), Sources, getFormattingLangOpts());
@@ -82,15 +91,27 @@ static void format() {
Offsets.push_back(0);
if (Offsets.size() != Lengths.size() &&
!(Offsets.size() == 1 && Lengths.empty())) {
- llvm::errs() << "Number of -offset and -length arguments must match.\n";
- return;
+ llvm::errs()
+ << "error: number of -offset and -length arguments must match.\n";
+ return true;
}
std::vector<CharSourceRange> Ranges;
- for (cl::list<int>::size_type i = 0, e = Offsets.size(); i != e; ++i) {
+ for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
+ if (Offsets[i] >= Code->getBufferSize()) {
+ llvm::errs() << "error: offset " << Offsets[i]
+ << " is outside the file\n";
+ return true;
+ }
SourceLocation Start =
Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
SourceLocation End;
if (i < Lengths.size()) {
+ if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
+ llvm::errs() << "error: invalid length " << Lengths[i]
+ << ", offset + length (" << Offsets[i] + Lengths[i]
+ << ") is outside the file.\n";
+ return true;
+ }
End = Start.getLocWithOffset(Lengths[i]);
} else {
End = Sources.getLocForEndOfFile(ID);
@@ -99,7 +120,8 @@ static void format() {
}
tooling::Replacements Replaces = reformat(getStyle(), Lex, Sources, Ranges);
if (OutputXML) {
- llvm::outs() << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
+ llvm::outs()
+ << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
for (tooling::Replacements::const_iterator I = Replaces.begin(),
E = Replaces.end();
I != E; ++I) {
@@ -114,14 +136,14 @@ static void format() {
tooling::applyAllReplacements(Replaces, Rewrite);
if (Inplace) {
if (Replaces.size() == 0)
- return; // Nothing changed, don't touch the file.
+ return false; // Nothing changed, don't touch the file.
std::string ErrorInfo;
llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo,
llvm::raw_fd_ostream::F_Binary);
if (!ErrorInfo.empty()) {
llvm::errs() << "Error while writing file: " << ErrorInfo << "\n";
- return;
+ return true;
}
Rewrite.getEditBuffer(ID).write(FileStream);
FileStream.flush();
@@ -129,6 +151,7 @@ static void format() {
Rewrite.getEditBuffer(ID).write(outs());
}
}
+ return false;
}
} // namespace format
@@ -139,14 +162,32 @@ int main(int argc, const char **argv) {
cl::ParseCommandLineOptions(
argc, argv,
"A tool to format C/C++/Obj-C code.\n\n"
- "Currently supports LLVM and Google style guides.\n"
"If no arguments are specified, it formats the code from standard input\n"
"and writes the result to the standard output.\n"
- "If <file> is given, it reformats the file. If -i is specified together\n"
- "with <file>, the file is edited in-place. Otherwise, the result is\n"
- "written to the standard output.\n");
+ "If <file>s are given, it reformats the files. If -i is specified \n"
+ "together with <file>s, the files are edited in-place. Otherwise, the \n"
+ "result is written to the standard output.\n");
+
if (Help)
cl::PrintHelpMessage();
- clang::format::format();
- return 0;
+
+ bool Error = false;
+ switch (FileNames.size()) {
+ case 0:
+ Error = clang::format::format("-");
+ break;
+ case 1:
+ Error = clang::format::format(FileNames[0]);
+ break;
+ default:
+ if (!Offsets.empty() || !Lengths.empty()) {
+ llvm::errs() << "error: \"-offset\" and \"-length\" can only be used for "
+ "single file.\n";
+ return 1;
+ }
+ for (unsigned i = 0; i < FileNames.size(); ++i)
+ Error |= clang::format::format(FileNames[i]);
+ break;
+ }
+ return Error ? 1 : 0;
}
diff --git a/tools/clang-format/clang-format-bbedit.applescript b/tools/clang-format/clang-format-bbedit.applescript
new file mode 100644
index 000000000000..fa88fe900480
--- /dev/null
+++ b/tools/clang-format/clang-format-bbedit.applescript
@@ -0,0 +1,27 @@
+-- In this file, change "/path/to/" to the path where you installed clang-format
+-- and save it to ~/Library/Application Support/BBEdit/Scripts. You can then
+-- select the script from the Script menu and clang-format will format the
+-- selection. Note that you can rename the menu item by renaming the script, and
+-- can assign the menu item a keyboard shortcut in the BBEdit preferences, under
+-- Menus & Shortcuts.
+on urlToPOSIXPath(theURL)
+ return do shell script "python -c \"import urllib, urlparse, sys; print urllib.unquote(urlparse.urlparse(sys.argv[1])[2])\" " & quoted form of theURL
+end urlToPOSIXPath
+
+tell application "BBEdit"
+ set selectionOffset to characterOffset of selection
+ set selectionLength to length of selection
+ set fileURL to URL of text document 1
+end tell
+
+set filePath to urlToPOSIXPath(fileURL)
+set newContents to do shell script "/path/to/clang-format -offset=" & selectionOffset & " -length=" & selectionLength & " " & quoted form of filePath
+
+tell application "BBEdit"
+ -- "set contents of text document 1 to newContents" scrolls to the bottom while
+ -- replacing a selection flashes a bit but doesn't affect the scroll position.
+ set currentLength to length of contents of text document 1
+ select characters 1 thru currentLength of text document 1
+ set text of selection to newContents
+ select characters selectionOffset thru (selectionOffset + selectionLength - 1) of text document 1
+end tell
diff --git a/tools/clang-format/clang-format-diff.py b/tools/clang-format/clang-format-diff.py
index ab5f1b1bc630..68b5113d92f6 100755
--- a/tools/clang-format/clang-format-diff.py
+++ b/tools/clang-format/clang-format-diff.py
@@ -63,9 +63,10 @@ def formatRange(r, style):
offset, length = getOffsetLength(filename, line_number, line_count)
with open(filename, 'r') as f:
text = f.read()
- p = subprocess.Popen([binary, '-offset', str(offset), '-length', str(length),
- '-style', style],
- stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ command = [binary, '-offset', str(offset), '-length', str(length)]
+ if style:
+ command.extend(['-style', style])
+ p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
stdout, stderr = p.communicate(input=text)
if stderr:
@@ -84,8 +85,8 @@ def main():
'Reformat changed lines in diff')
parser.add_argument('-p', default=1,
help='strip the smallest prefix containing P slashes')
- parser.add_argument('-style', default='LLVM',
- help='formatting style to apply (LLVM, Google)')
+ parser.add_argument('-style',
+ help='formatting style to apply (LLVM, Google, Chromium)')
args = parser.parse_args()
filename = None
diff --git a/tools/clang-format/clang-format.el b/tools/clang-format/clang-format.el
new file mode 100644
index 000000000000..2c5546b241cc
--- /dev/null
+++ b/tools/clang-format/clang-format.el
@@ -0,0 +1,31 @@
+;;; Clang-format emacs integration for use with C/Objective-C/C++.
+
+;; This defines a function clang-format-region that you can bind to a key.
+;; A minimal .emacs would contain:
+;;
+;; (load "<path-to-clang>/tools/clang-format/clang-format.el")
+;; (global-set-key [C-M-tab] 'clang-format-region)
+;;
+;; Depending on your configuration and coding style, you might need to modify
+;; 'style' and 'binary' below.
+(defun clang-format-region ()
+ (interactive)
+
+ (let* ((orig-windows (get-buffer-window-list (current-buffer)))
+ (orig-window-starts (mapcar #'window-start orig-windows))
+ (orig-point (point))
+ (binary "clang-format")
+ (style "LLVM"))
+ (if mark-active
+ (setq beg (region-beginning)
+ end (region-end))
+ (setq beg (min (line-beginning-position) (1- (point-max)))
+ end (min (line-end-position) (1- (point-max)))))
+ (call-process-region (point-min) (point-max) binary t t nil
+ "-offset" (number-to-string (1- beg))
+ "-length" (number-to-string (- end beg))
+ "-style" style)
+ (goto-char orig-point)
+ (dotimes (index (length orig-windows))
+ (set-window-start (nth index orig-windows)
+ (nth index orig-window-starts)))))
diff --git a/tools/clang-format/clang-format.py b/tools/clang-format/clang-format.py
index de9225740703..d90c62a5bf68 100644
--- a/tools/clang-format/clang-format.py
+++ b/tools/clang-format/clang-format.py
@@ -23,6 +23,10 @@ import subprocess
# Change this to the full path if clang-format is not on the path.
binary = 'clang-format'
+# Change this to format according to other formatting styles (see
+# clang-format -help)
+style = 'LLVM'
+
# Get the current text.
buf = vim.current.buffer
text = "\n".join(buf)
@@ -34,7 +38,8 @@ length = int(vim.eval('line2byte(' +
str(vim.current.range.end + 2) + ')')) - offset - 2
# Call formatter.
-p = subprocess.Popen([binary, '-offset', str(offset), '-length', str(length)],
+p = subprocess.Popen([binary, '-offset', str(offset), '-length', str(length),
+ '-style', style],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
stdout, stderr = p.communicate(input=text)