Syntax checking python...

Alex Coventry throwaway at mit.edu
Sat Feb 1 00:27:56 EST 2003


hi.  i use emacs with the following script, which i've arranged to
execute whenever i execute or save a python buffer:

http://web.mit.edu/alex_c/Public/find_syntax_error.py

the elisp function i use in conjunction with this is below.  it warps
the cursor to the script's best guess as to the line on which the syntax
error occurred.

hope this helps.

alex.

(defun check-syntax () (interactive)

  "Check whether there are any errors in the current buffer."
  
  (let (

	;; Name of the file the buffer will be saved to.
	(file (expand-file-name (make-temp-name "python-")
				py-temp-directory))

	;; Store the results of calling out to find_syntax_error.py
	compile-result row column msg)

    ;; Add some whitespace at the end, to make sure the entire file
    ;; gets compiled.
    (save-excursion
      (goto-char (point-max))
      (if (not (looking-at "^\\s-*$")) (insert "\n")))

    ;; Save to the temp file
    (write-region (point-min) (point-max) file nil 'nomsg)

    ;; Get the result from find_syntax_error.py
    (setq compile-result
	  (shell-command-to-string
	   (concat py-python-command " "
		   MY_CVS_PATH "tools/admin/find_syntax_error.py "
		   file)))

    ;; Get rid of the temp file.
    (delete-file file)

    
    (if (string-match "No error found\\.\n" compile-result)
	(message "No syntax errors")
      (goto-char (point-min))
      (if (not (string-match "^\\([0-9]+\\) \\([0-9]+\\) \\(.*\\)"
			     compile-result))
	  (progn
	    (message compile-result)
	    (error (concat
		    "Could not find error coordinates. "
		    "Error message was: " compile-result
		    ))))
      (setq row    (string-to-int (match-string 1 compile-result))
	    column (string-to-int (match-string 2 compile-result))
	    msg                   (match-string 3 compile-result)
	    )
      (goto-char (point-min))
      (next-line row)

      (forward-char column)
      (error (concat "Syntax Error found: " msg))
    )))





More information about the Python-list mailing list