Используя Emacs, можно ли закрепить команду компиляции в определенном буфере / каталоге? - PullRequest
4 голосов
/ 06 октября 2011

Прямо сейчас я использую следующее для компиляции, когда я, например, в main.cpp

C-x b Makefile RET M-x compile RET RET

У меня фактически Mx compile в качестве сочетания клавиш, нопроблема в том, что мне бы очень не хотелось проходить через все эти проблемы, чтобы просто запустить мой Makefile.

Мне нужно посетить Makefile, чтобы убедиться, что команда compile выполняется с использованием того же каталога.Есть ли способ прикрепить каталог, чтобы я мог просто пойти M-x compile RET RET?

С уважением

Ответы [ 3 ]

4 голосов
/ 06 октября 2011

Используйте recompile вместо. C-u M-x recompile позволит вам сначала отредактировать команду компиляции. В любом случае компиляция будет работать из каталога, в котором была выполнена последняя компиляция.

2 голосов
/ 07 октября 2011

Смотрите мой ответ здесь

Локальные переменные каталога предоставляют простой способ запуска компиляции из родительского каталога любого исходного файла в подкаталоге.

1 голос
/ 06 октября 2011

Я запускаю emacs в основном в Windows.
Когда у меня есть make-файл, который находится в родительском каталоге модуля C, я использую его как команду компиляции:

cd .. &&NMAKE

например:

cd .. && nmake CONFIG = Debug PLATFORM = x64 target

Помимо этого, я считаю, что указаниеСоздать командную строку, которую я хочу запустить для различных модулей, это своего рода боль.Мне нужен был способ присоединить команду компиляции по умолчанию к редактируемому буферу.Поэтому я написал небольшое письмо, чтобы справиться с этой работой.Я решил вставить в комментарии заголовка каждого буфера строку, в которой будет указана моя предпочтительная команда компиляции, например:

compile: cd .. && nmake CONFIG = Debug PLATFORM = x64 target

А затем запустите фрагмент elisp, прежде чем я вызову M-x compile, который захватывает строку и предлагает ее в качестве команды компиляции, которую я хотел бы запустить.

Этот defun вытягивает строку из комментариев заголовка:

(defun cheeso-c-get-value-from-comments (marker-string line-limit)
    "gets a string from the header comments in the current buffer.

This is used to extract the compile command from the comments. It
could be used for other purposes too.

It looks for \"marker-string:\" and returns the string that
follows it, or returns nil if that string is not found.

eg, when marker-string is \"compile\", and the following
string is found at the top of the buffer:

     compile: cl.exe /I uthash

...then this command will return the string

     \"cl.exe /I uthash\"

It's ok to have whitespace between the marker and the following
colon.

"
  (let (start search-limit found)
    ;; determine what lines to look in
    (save-excursion
      (save-restriction
        (widen)
        (cond ((> line-limit 0)
               (goto-char (setq start (point-min)))
               (forward-line line-limit)
               (setq search-limit (point)))
              ((< line-limit 0)
               (goto-char (setq search-limit (point-max)))
               (forward-line line-limit)
               (setq start (point)))
              (t                        ;0 => no limit (use with care!)
               (setq start (point-min))
               (setq search-limit (point-max))))))

    ;; look in those lines
    (save-excursion
      (save-restriction
        (widen)
        (let ((re-string
               (concat "\\b" marker-string "[ \t]*:[ \t]*\\(.+\\)$")))
          (if (and start
                   (< (goto-char start) search-limit)
                   (re-search-forward re-string search-limit 'move))

              (buffer-substring-no-properties
               (match-beginning 1)
               (match-end 1))))))))

Хорошо, теперь мне нужно что-то вызвать, прежде чем я вызову compile.

(defun cheeso-invoke-compile-interactively ()
  "fn to wrap the `compile' function.  This simply
checks to see if `compile-command' has been previously set, and
if not, invokes `cheeso-guess-compile-command' to set the value.
Then it invokes the `compile' function, interactively."
  (interactive)
  (cond
   ((not (boundp 'cheeso-local-compile-command-has-been-set))
    (cheeso-guess-compile-command)
    (set (make-local-variable 'cheeso-local-compile-command-has-been-set) t)))
  ;; local compile command has now been set
  (call-interactively 'compile))

Затем, конечно, defun, который угадывает команду компиляции:

(defun cheeso-guess-compile-command ()
  "set `compile-command' intelligently depending on the
current buffer, or the contents of the current directory."
  (interactive)
  (set (make-local-variable 'compile-command)
       (cond
        (buffer-file-name
         (let ((filename (file-name-nondirectory buffer-file-name)))
           (cond
            ;; editing a C-language source file - check for an
            ;; explicitly-specified command
            ((string-equal (substring buffer-file-name -2) ".c")
             (let ((explicit-compile-command
                    (cheeso-c-get-value-from-comments "compile" 34)))
               (or explicit-compile-command
                   (concat "nmake " ;; assume a makefile exists
                           (file-name-sans-extension filename)
                           ".exe"))))

            ;; editing a makefile - just run nmake
            ((string-equal (substring buffer-file-name -8) "makefile")
             "nmake ")

            ;; something else - do a typical .exe build
            (t
             (concat "nmake "
                     (file-name-sans-extension filename)
                     ".exe")))))
        (t
         ;; punt
         "nmake "))))

Последний бит - это привязка C-x C-e, обычно привязанная к compile, к оболочкеdefun:

(global-set-key "\C-x\C-e"  'cheeso-invoke-compile-interactively)

Теперь, когда я делаю C-x C-e в буфере, он ищет команду компиляции и предлагает мне команду, которую он находит.Я могу отредактировать предложенную команду компиляции, затем нажать клавишу ВВОД и запустить ее.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...