Search code examples
pythondebuggingemacselispcustomization

Emacs: Set/Reset python debug breakpoint


I use python debugger pdb. I use emacs for python programming. I use python-mode.el. My idea is to make emacs intuitive. So I need the following help for python programs (.py)

  1. Whenever I press 'F9' key, the emacs should put "import pdb; pdb.set_trace();" statements in the current line and move the current line to one line below. Sentence to be in same line. smart indentation may help very much.

  2. Wherever "import pdb; pdb.set_trace();" statement presents in the python code, emacs should display left indicator and highlight that line.

  3. When I press 'Alt-F9' keys at the current line and emacs found the "import pdb; pdb.set_trace();" statement then, emacs should remove the "import pdb; pdb.set_trace();" line and move the current line to one up.

  4. Whenever I press "F8" key, emacs to jump to "import pdb; pdb.set_trace();" in the same buffer.

I am trying to learn elisp and catch up lisp soon to customize emacs myself. I will appreciate your answers.

The answer shall be great enough for me and others who find this solution is very useful.


Solution

  • to do 1)

    (defun add-py-debug ()  
          "add debug code and move line down"  
        (interactive)  
        (move-beginning-of-line 1)  
        (insert "import pdb; pdb.set_trace();\n"))  
    
    (local-set-key (kbd "<f9>") 'add-py-debug)
    

    to do 2) you probably have to change the syntax highlighting of the python mode, or write you own minor mode. You'd have to look into font-lock to get more. Sorry.

    to do 3) though I've set this to be C-c F9 instead of Alt-F9

    (defun remove-py-debug ()  
      "remove py debug code, if found"  
      (interactive)  
      (let ((x (line-number-at-pos))  
        (cur (point)))  
        (search-forward-regexp "^[ ]*import pdb; pdb.set_trace();")  
        (if (= x (line-number-at-pos))  
        (let ()  
          (move-beginning-of-line 1)  
          (kill-line 1)  
          (move-beginning-of-line 1))  
          (goto-char cur))))  
    
    (local-set-key (kbd "C c <f9>") 'remove-py-debug)
    

    and to do 4)

    (local-set-key (kbd "<f3>") '(lambda ()  
                                     (interactive)   
                                     (search-forward-regexp "^[ ]*import pdb; pdb.set_trace();")   
                                     (move-beginning-of-line 1)))
    

    Note, this is not the best elisp code in the world, but I've tried to make it clear to you what's going on rather than make it totally idiomatic. The GNU Elsip book is a great place to start if you want to do more with elisp.

    HTH