Make it easy to run `gn format' on an emacs buffer.

BUG=none

Review URL: https://codereview.chromium.org/1887233004

Cr-Original-Commit-Position: refs/heads/master@{#387727}
Cr-Mirrored-From: https://chromium.googlesource.com/chromium/src
Cr-Mirrored-Commit: a67a258a487ec1948d6a6cfc4744cefbab868b5d
diff --git a/tools/gn/misc/emacs/gn-mode.el b/tools/gn/misc/emacs/gn-mode.el
index 6682290..435e872 100644
--- a/tools/gn/misc/emacs/gn-mode.el
+++ b/tools/gn/misc/emacs/gn-mode.el
@@ -36,6 +36,11 @@
   :group 'gn
   :type 'integer)
 
+(defcustom gn-format-command "gn format --stdin"
+  "The command to run to format gn files in place."
+  :group 'gn
+  :type 'string)
+
 (defgroup gn-faces nil
   "Faces used in Generate Ninja mode."
   :group 'gn
@@ -123,6 +128,20 @@
       ;; if we do.
       t))
 
+(defun gn-run-format ()
+  "Run 'gn format' on the buffer in place."
+  (interactive)
+  ;; We can't `save-excursion' here; that will put us at the beginning of the
+  ;; shell output, aka the beginning of the document.
+  (let ((my-start-line (line-number-at-pos)))
+    (shell-command-on-region (point-min) (point-max) gn-format-command nil t)
+    (goto-line my-start-line)))
+
+(defvar gn-mode-map
+  (let ((map (make-sparse-keymap)))
+    (define-key map "\C-c\C-f" 'gn-run-format)
+    map))
+
 ;;;###autoload
 (define-derived-mode gn-mode prog-mode "GN"
   "Major mode for editing gn (Generate Ninja)."