[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: M-x compile for different file extensions

From: Ehud Karni
Subject: Re: M-x compile for different file extensions
Date: Sun, 20 Oct 2002 02:00:11 +0200

On Sat, 19 Oct 2002 17:41:34 GMT, wgh <wgh@askme.ok> wrote:
> Is there a way to have M-x compile to automatically detect
> what command to use depending on the file extension of the
> current buffer being edited?
> Because I don't really see the advantage of using M-x compile
> if I can get away with fewer keystrokes in Bash doing the
> exact same thing (i.e. typing the compile command, pressing
> the up arrow if I need to recompile, etc.)

I had the same need and I have written some functions to accomplish
this. It was posted to emacs sources on 2002-07-22 but I never got
any responses. Here is the updated version.

I have enhanced the Emacs `compile' package with some commands.

1. Automatic selection of compile commands according to the file
   extension and DEBUG state. (defuns: `compile-main', `compile-sub',
2. A command to change the list of extensions and associate compile
   commands dynamicly. (see help for `compile-ek')
3. A way to give 2 specific compilation commands (normal/debug) for
   the current edited file (`compile-ext-edit').
4. An easy way to interact (send input to) with the compilation process
5. Run some commands with interactive input to them (when needed) in a
   compilation window, with an option to kill the compilation buffer.
   (`compile-commands', read the help carefully).
6. Please note that you can embed the compile command within the file
   (see help for `compile-ek') e.g. for a shell script you can add
   ##  Compile by: /bin/sh -e $* arg1 arg2
   ##  Compile debug: /bin/sh -ex $* dbg1 dbg2

The ekcompl.el is listed below. Every one is encouraged to change it
(especially the `compile-main-ext' and `compile-sub-ext' vars).
Any comments and improvements are welcomed.

To get it send an email to:
   Subject: "files" (one word, no quotes).
   1st line of the content: "ekcompl.el.gz" (one word, no quotes).
   The file will be then automaticly sent to the reply address.


;; -*- mode: emacs-lisp; unibyte: t; -*-
;; ekcompl.el --- Automatic compilation commands
;; Copyright (C) 1992-2000  Ehud karni <>

;; This file is NOT part of GNU Emacs, distribution conditions below.
;;              EHUD   KARNI            ינרק   דוהא
;;              Ben Gurion st'   14   ןוירוג ןב 'חר
;;              Kfar - Sava    44 257     אבס - רפכ
;;              ===================================
;;              <>  972-(0)9-7659599
;;              ===================================

;;     RCS: $Id: ekcompl.el,v 1.106 2000/05/08 16:10:24 ehud Exp $
;;  $Log: ekcompl.el,v $
;;  Revision 1.106  2000/05/08  16:10:24  ehud
;;  Added remote compilation option when called with prefix arg. The
;;  `compile-remote-call' variable is the script name for executing remotly.
;;  Revision 1.105  2000/03/05  14:16:49  ehud
;;  Comment headers changes (NOT GNU)  +  Other comments   == ONLY ==
;;  Revision 1.104  1998/03/15  17:12:33  ehud
;;  Last revision for 19.34
;;  Revision 1.103  1996/02/19  10:25:45  ehud
;;  Emacs 19.30 version
;;  Revision 1.102  1995/09/20  17:10:46  ehud
;;  rearrange of compile-ek (add compile-rplc-nm-ext),
;;  make special I-A commands available (see commented compile-cob-fnx)
;;  Revision 1.101  1995/08/28  15:34:30  ehud
;;  change of compile-ek: allow user to specify compilation in 1st 20 lines.
;;  Revision 1.100  1995/01/19  17:17:35  ehud
;;  SW initial version control for all el's

;;  This program is free software; you can redistribute it and/or modify
;;  it under the terms of the GNU General Public License as published by
;;  the Free Software Foundation; either version 2 of the License, or
;;  (at your option) any later version.
;;  This program is distributed in the hope that it will be useful,
;;  but WITHOUT ANY WARRANTY; without even the implied warranty of
;;  GNU General Public License for more details.
;;  You should have received a copy of the GNU General Public License
;;  along with this program; if not, write to the Free Software
;;  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

;; The updated package can be got by email:
;;   Send email to:
;;   Subject: "files" (one word, no quotes).
;;   1st line of the content: "ekcompl.el.gz" (one word, no quotes).
;;   The file will be then automaticly sent to the reply address.

(require 'compile)

(defvar compile-debug nil
"*Debug indicator for compilations (nil=normal other=debug on)")

(defvar compile-main-ext '((".c" "ccn" "ccdb")                 ; SW c
                           (".ec" "ccnsql" "ccdbsql")          ; SW c/informix
                   ;;      (".pc8" "+MFcf" "+MFcf-dbg")        ;====  Micro  
Focus  Cobol  ====
                   ;;      (".pco" "+MFcf" "+MFcf-dbg")        ;====  with 
Oracle preprocessing

                           (".cbl" "cobn" "cobdb")             ; SW Cobol
                           (".eco" "esqlcobol" "cobsqldb")     ; SW 
                           (".f"   "ftn" "ftndb")              ; SW Fortran
                           (".ef"  "ftnsql" "ftndbsql")        ; SW 
                           (".el"  "+bcEL")                    ; emacs lisp
                           (".lts" "letcmp -lu" "letcmp -u")   ; SW letus
                           (".pns" "smfcmp -lo" "smfcmp -o")   ; SW screen 
formater (SMF)
                          ) "Extension list and commands for compilations of 
main programs")

(defvar compile-sub-ext '((".c"   "ccsb" "ccsbd")              ; SW c
                          (".ec"  "ccsbsql" "ccsbdsql")        ; SW c/informix
                          (".cbl" "cobsub" "cobsubd")          ; SW Cobol
                          (".eco" "cobsqlsub" "cobsqlsubd")    ; SW 
                          (".f"   "ftsb" "ftsbd"))             ; SW Fortran
"Extension list and commands for compilations of sub-programs")

(defvar compile-remote-call "" "*command (usually a script) to run 
remote compilations")
(defvar compile-hosts-list '("linux" "aviion" "sw-dbs")
           "*Initial hosts list for remote compilations.
This is a history list so it gets updated whenever the user choose a host.")
(defvar compile-host "linux" "*host name for remote compilations")

(defun compile-debug-toggle () "Toggle the compile-debug variable (t / nil)"
        (if compile-debug
                (setq compile-debug nil)
                (message "Normal compilation"))
                (setq compile-debug 'DEBUG)
                (message "Compilation with DEBUG"))))

(defun compile-main (&optional remote)
  "Save buffer and than Compile main program using the compile-main-ext
which is (if not changed):
                                      shell  script
    language               ext       normal    debug
    MF Cobol               .cbl      cobn      cobdb
    System C               .c        ccn       ccdb
    GH Fortran 77          .f        ftn       ftndb
    Emacs Lisp             .el       byte-compile (no debug option)

You can change the extension list by using M-x compile-ext-edit (or Alt-S-F5).

To compile remotely use prefix argument.
See help for `compile-ek' for ways to override the default compilation script.
  (interactive "P")
       (if remote
           (setq remote (compile-get-host)))
       (compile-ek compile-main-ext remote))

(defun compile-sub (&optional remote)
  "Save buffer and than Compile sub-program using the compile-sub-ext
which is (if not changed):
                                      shell  script
    language               ext       normal    debug
    MF Cobol               .cbl      cobsub    cobsubd
    System C               .c        ccsb      ccsbd
    GH Fortran 77          .f        ftsb      ftsdb

You can change the extension list by using M-x compile-ext-edit (or Alt-S-F5).

See help for `compile-ek' for ways to override the default compilation script.
  (interactive "P")
       (if remote
           (setq remote (compile-get-host)))
       (compile-ek compile-sub-ext remote))

(defun compile-get-host ()
  "Get host for remote compilation (default is `compile-host') and re-save.
Empty string means compile locally and `compile-host' is preserved."
       (let ((host (read-string "Enter host for remote compilation 
(empty-locally): "
                                compile-host 'compile-hosts-list)))
           (if (string-equal host "")
               (setq host nil))
           (and host
               (setq compile-host host))

(defun compile-ek (EXT-LIST remote)
  "Save buffer and Compile it using the script name that match the file 
(.xxxx) from EXT-LIST (1st name for normal, 2nd for debug).

2nd arg REMOTE is name of host for remote compilation or nil (local).

If the extension is not found, display error message.
The standard script may be changed by changing the standard extension list
using `compile-ext-edit' (usually bound to [S-f25] - Shift-Alt-F5.

A file can override the script assigned to it by its extension by having in its
first  20  lines the string \"Compile by: \" followed by the command (up to end
of line) to perform Normal compilation, use the string \"Compile debug: \" for
Debug compilation. The command can include $* (replaced by the file name) and
$@ (the file name without its extension).
e.g. to use make to compile a program:
       Compile by: gmake -f $ap_sys/Nmake $@.exe
       Compile debug: gmake -f $ap_sys/makeDB $*
       (let* (call-buf                         ;file name (absolute)
             (srch (if compile-debug "debug" "by"))
             p1  p2                            ;temp vars
             (pos (point))                     ;saved pos
             mxp                               ;max pos to search
           (if (eq major-mode 'dired-mode)             ;in dired ?
               (setq call-buf (dired-get-filename))    ;yes, skip search in file
               (progn                                  ;not dired (normal 
                   (save-buffer 3)                     ;save this buffer
                   (setq call-buf (buffer-file-name))  ;absolute file name
                   (goto-char (point-min))             ;1st char/line
                   (search-forward "\n" nil 1 20)      ;search line 20/end of 
                   (setq mxp (point))                  ;set as limit of search
                   (goto-char (point-min))
                   (if (not (search-forward (concat "Compile " srch ": ")
                                            mxp 'NOERROR)) ;search for "Compile 
                       (goto-char pos)                 ; "Compile by: " not 
                       (progn                          ; extra insurance
                           (setq mxp (point))          ; 1st char of compile 
                           (end-of-line)               ; last char of compile 
                           (setq srch (buffer-substring mxp (point)))  ;raw 
compile command
                           (goto-char pos)             ; Return to original 
                           (setq EXT-LIST nil)         ; no search for file 
                           (compile-ek-sub             ; do compile with 
                               (compile-rplc-nm-ext srch)      ; compile command
                               remote 'NO-FILE)                ; host/nil (no 
file name)
                       )                               ;end of "Compile by:" 
                   )))                                 ;
           (while EXT-LIST                             ;EXT-LIST is nil if 
"Compile by:"
               (setq p2 (car EXT-LIST))                ;p2=("ext" "normal 
compile" "debug")
               (setq EXT-LIST (cdr EXT-LIST))          ;rest of EXT-LIST
               (setq p1 (car p2))                      ;p1="ext"
               (setq p2 (cdr p2))                      ;p2=("normal compile" 
               (if (string= p1                         ;p1="ext"
                       (substring call-buf (- (length p1)))) ;is it "ext" ?
                   (progn                              ;yes, extension found
                       (setq EXT-LIST nil)             ;end loop !
                       (if compile-debug               ;debug mode ?
                           (setq p2 (cdr p2)))         ;yes, p2=("debug compile 
                       (setq p1 (car p2))              ;p1="compile command"

                       (if (and p1 (not (string= p1 "")))  ; not nil or empty 
                               (compile-ek-sub p1 remote)  ; compile command 
and remote-host/nil
                               (setq p1 nil))
                           (setq p1 t)))))
           (if p1 (message "File (%s) - no command found for this extension.  
Error !"

(defun compile-rplc-nm-ext (cmd-in)
       (let ((flnm (file-name-nondirectory             ; leave only file name 
                       (if (eq major-mode 'dired-mode)
                               (dired-get-filename 'LOCAL 'NO-ERROR) ; the file 
on this line (dired)
                               (buffer-file-name))))   ; this buffer file name
             cmd                                       ; command is empty
             p1 p2                                     ;local vars 
           (setq cmd-in (concat cmd-in " "))           ;add 2 spaces for safety
           (while (setq p1 (string-match "\\$" cmd-in))   ; do for all $* & $@ 
in user command
               (setq p2 (aref cmd-in (1+ p1)))         ; char after $
                   ((= p2 ?*)                          ; replace $* by full 
file name
                           (setq p2 flnm))
                   ((= p2 ?@)                          ; $@ replaced by file 
                           (setq p2 (string-match "\\.[^\\.]*$" flnm)) ;without 
                           (if p2
                               (setq p2 (substring flnm 0 p2))     ; omit 
                               (setq p2 flnm)))                    ; NO 
extension found
                           (setq p2 (concat "$" (char-to-string p2))))
               )                                           ;end of cond
               (setq cmd (concat cmd (substring cmd-in 0 p1) p2))
               (setq cmd-in (substring cmd-in (+ p1 2)))
           )                                               ;end of while
           (concat cmd cmd-in)))                           ;return command for 
shell execution

(defun compile-ek-sub (cmd remote &optional no_file)
  "Compile using CMD on host REMOTE (nil->locally).
If optional NO_FILE do not add name of file"
       (require 'compile)
           ((string= cmd "+bcEL")                   ;special case - byte compile
                       (byte-compile-file call-buf));           of Emacs Lisp
;;     ;;    ((string= cmd "+MFcf")                   ;special case - Micro 
;;     ;;                (compile-cob-fnx compile-ek-arg))   ;    Cobol for 
               (and remote
                   (setq cmd (concat compile-remote-call " " remote " " cmd)))
               (or no_file
                   (setq cmd (concat cmd " " (file-name-nondirectory 
               (compile-internal cmd " === No more compilation errors ==="     
;compile with cmd
                           (concat " Compilation (by " cmd ")")))))

(defun compile-ext-edit () "Edit compile-main-ext or compile-sub-ext"
       (let ((ext-list) (ext) (p1) (p2))
            (if (y-or-n-p "Do you wand to change main (else sub) extension 
list? ")
                (setq ext-list "main")
                (setq ext-list "sub"))
            (setq ext (read-string (concat "Compile " ext-list " Extension: ") 
            (if (string= "sub" ext-list)
                (setq p1 (included-car ext compile-sub-ext))
                (setq p1 (included-car ext compile-main-ext)))
            (setq p2 (cdr p1))
            (setq p1 (list
                      (read-string (concat ext-list " Compile (normal) name: ")
                                   (car p2))
                      (read-string (concat ext-list " Compile (debug) name: ")
                                   (car (cdr p2)))
                     ))                                            ; end of 
setq p1
            (if (equal '("" "") (cdr p1))
                (setq p1 (list ext)))                              ; no 
commands (delete)
            (compile-ext-rep ext-list p1)))

(defun compile-ext-rep (TYPE EXTL)
  "Replace (add) names of compilation scripts in extension list.
The compilation TYPE is string - \"sub\" or \"main\".
EXTL is list of 3 strings - (ext, nrml-proc, dbg-proc).

e.g. To change the names for Cobol (extension .cbl) compiler scripts to cob_n
     (normal) and cob_dbg (debug) the EXTL should be: (\".cbl\" \"cob_n\" 
       (if (string= "sub" TYPE)
           (setq compile-sub-ext (included-car-rep EXTL compile-sub-ext))
           (setq compile-main-ext (included-car-rep EXTL compile-main-ext))))

(defun included-car (ELT LIST)
"Returns non-nil if ELT is an (car element) of LIST. Comparison done with equal.
The value is the element whose car is ELT."
        (if LIST
            (if (equal (car (car LIST)) ELT)
                (setq LIST (car LIST))
                (included-car ELT (cdr LIST)))))

(defun included-car-rep (NEW LIST)
"Replace (add/delete) element which its car equals the car of NEW in LIST.
If not found add NEW, if the cdr of NEW is nil delete the found element.
Comparison done with equal. The value is the new list."
       (let ((p1 LIST)
             (p2 (car NEW))
           (setq LIST nil)
           (while p1
                   (setq p3 (car p1))
                   (if (equal (car p3) p2)
                           (if (cdr NEW)
                               (setq LIST (append LIST (list NEW))))
                           (setq NEW nil))
                       (setq LIST (append LIST (list p3))))
                   (setq p1 (cdr p1))))
           (setq LIST (append LIST (if (cdr NEW) (list NEW))))))

;;     example of special interactive compilation command
;;(defvar compile-fnx-number 1 "Default TARGET for Phoenix MF cobol (see help 
for `compile-cob-fnx')")
;;(defun compile-cob-fnx (&optional arg)
;;  "Compile MF Cobol with Oracle preprocessor (by gmake).
;;You can have the following targets:
;; 0 - .int (interpreter code run by rts or anim)
;; 1 - .gnt (native code run by rts or anim)
;; 2 - .o   (object code for ld loader)
;; 3 - .exe (staticly linked executable program)
;; 9 - `tst' - pre compiler only (omit `at DB')"
;;    (interactive "P")
;;       (or arg
;;           (save-window-excursion
;;               (describe-function 'compile-cob-fnx)
;;               (setq arg (string-to-int (read-string
;;                   "Enter new TARGET for this compilation " (format "%s" 
;;               (kill-buffer "*Help*")))
;;       (cond
;;           ((= arg 0)
;;               (setq arg "int"))
;;           ((= arg 1)
;;               (setq arg "gnt"))
;;           ((= arg 2)
;;               (setq arg "o"))
;;           ((= arg 3)
;;               (setq arg "exe"))
;;           ((= arg 9)
;;               (setq arg "tst"))
;;           (t
;;               (error "arg to compile-cob-fnx is not 0-3 or 9.")))
;;       (compile-ek-sub (compile-rplc-nm-ext (concat "oracob $@ " arg)) t))

(defun compile-commands (cmds &optional name rptkl)
  "Perform several shell commands using the `compile-internal' function.
Parameters: CMDS and optional NAME REPEAT and NOKILL.
The CMDS parameter is a list of conses. Each is made of a string & a number.
The string is the command to execute (sent to the compile process), the number
is the time in seconds to wait before sending the next command.
The commands are sent as is (no \\n added !), add \\n if you need it.
No echo of the commands is seen! You can use it to send passwords too.
The subshell run is always \"/bin/sh -i\".
The optional parameter NAME is the process buffer name, (def: \"*sub-shell*\").
The optional parameter RPTKL has 3 possible values: nil (omitted) means no
further actions, t causes the last command in CMDS to be sent repeatedly (once
per second) until the subshell exits and then kills the subshell buffer, other
value of RPTKL waits for the end of the subshell and than kills its buffer.
e.g. CMDS value to login as another user & execute cmnd-1.
       '((\"su ouser\\n\" 3) (\"passwd\\n\" 2) (\"cmd1\\n\" 1) (\"exit\\n\" 0))"
       (require 'compile)
       (let (pbuf                          ;; compilation buffer
             str                           ;; current command
             tm                            ;; time to wait
           (or (and name
                    (stringp name))
               (setq name "*sub-shell*"))  ;; user name for this sub shell
           (setq pbuf (compile-internal "exec /bin/sh -i" "End of sub shell" 
name ))
           (set-buffer pbuf)                   ;; working buffer
           (pop-to-buffer pbuf 'OTHER)         ;; make it visible (preferably 
           (while cmds                         ;; commands list of conses
               (setq str  (car cmds))          ;; 1st command cons
               (setq cmds (cdr cmds))          ;; rest of commands
               (setq tm  (nth 1 str))          ;; seconds to wait
               (setq str (car str))            ;; command to send
               (process-send-string pbuf str)  ;; send this command
               (accept-process-output)         ;; accept output
               (if (> tm 0)                    ;; time to wait > 0 ?
                   (sit-for tm))               ;; wait tm seconds
               (goto-char (point-max))         ;; put cursor at the end
           (if rptkl                                   ;; wait only if rptkl 
non nil
               (while (get-buffer-process pbuf)        ;; while process is alive
                   (if (eq rptkl t)                    ;; send only for t
                       (process-send-string pbuf str)) ;; send command to 
                   (accept-process-output)             ;; accept output
                   (sit-for 1)))                       ;; wait 1 sec & 
redispaly buffer
           (if rptkl
               (kill-buffer pbuf))))

(let ((lmap '(compilation-minor-mode-map compilation-mode-map))
       (require 'compile)      ;; you can change the keys ONLY after 'compile 
is loaded
       (while lmap             ;; do for all compile.el maps
           (setq map  (car lmap))      ;; current map
           (setq lmap (cdr lmap))      ;; rest of maps
           (define-key (symbol-value map) [mouse-3] 'compile-mouse-goto-error)
           (define-key (symbol-value map) "\C-a"    'compile-send-to-process)
           (define-key (symbol-value map) "\C-n"    

(defun compile-send-to-process-nl (&optional str)
  "Send STR (string) with \\n appended to process associated with this buffer."
       (compile-send-to-process str 'NEW-LINE))    ;; send with new line

(defun compile-send-to-process (&optional str nl)
  "Send STR (string) to process associated with this buffer.
If 2nd optional parameter NL is non nil, append \\n to the string."
       (let* ((cbuf (current-buffer))              ;; current buffer
              (cprc (get-buffer-process cbuf)))    ;; current process or nil
           (if (null cprc)                         ;; error if no process
               (error "No process associated to this buffer"))
           (or (and str                            ;; check for existence of
                    (stringp str))                 ;; command (must be string)
               (setq str                           ;; NOT SO, read from user
                     (read-from-minibuffer "String to send: "))
           )                                       ;; end of string check
           (if nl                                  ;; new line requested ?
               (setq str (concat str "\n")))       ;; yes, add it
           (goto-char (point-max))                 ;; put string in process
           (insert-string str)                     ;; buffer at the end
           (set-marker (process-mark cprc) (point));; for 'accept-process-output
           (process-send-string cprc str)          ;; NOW, send command
       ))                                          ;; end of defun

;; reg-exp for /bin/sh errors
(add-to-list 'compilation-error-regexp-alist '("\\([^+][^:\n]+\\): line 
\\([0-9]+\\): " 1 2))

(provide 'ekcompl)

;;============================== ekcompl.el ends here 

 Ehud Karni           Tel: +972-3-7966-561  /"\
 Mivtach - Simon      Fax: +972-3-7966-667  \ /  ASCII Ribbon Campaign
 Insurance agencies   (USA) voice mail and   X   Against   HTML   Mail  FAX:  1-815-5509341  / \                  Better  Safe  Than  Sorry

reply via email to

[Prev in Thread] Current Thread [Next in Thread]