Pages

Saturday, March 7, 2009

Opening a file as root

I found this stuff very handy:

The procedure is to open any file belonging to root, for example, and then hit C-x C-r to reopen it as root using tramp.

1) Keybinding

  1. (global-set-key (kbd "C-x C-r") 'find-alternative-file-with-sudo)


2) Code

  1. (defun find-alternative-file-with-sudo ()
  2. "Open current buffer as root!"
  3. (interactive)
  4. (when buffer-file-name
  5. (find-alternate-file
  6. (concat "/sudo:root@localhost:"
  7. buffer-file-name))))
  8. (defface find-file-root-header-face
  9. '((t (:foreground "white" :background "red3")))
  10. "*Face use to display header-lines for files opened as root.")
  11. (defun find-file-root-header-warning ()
  12. "*Display a warning in header line of the current buffer.
  13. This function is suitable to add to `find-file-root-hook'."
  14. (let* ((warning "WARNING: EDITING FILE AS ROOT!")
  15. (space (+ 6 (- (window-width) (length warning))))
  16. (bracket (make-string (/ space 2) ?-))
  17. (warning (concat bracket warning bracket)))
  18. (setq header-line-format
  19. (propertize warning 'face 'find-file-root-header-face))))
  20. (defun find-file-hook-root-header-warning ()
  21. (when (and buffer-file-name (string-match "root@localhost" buffer-file-name))
  22. (find-file-root-header-warning)))
  23. (add-hook 'find-file-hook 'find-file-hook-root-header-warning)


No comments:

Post a Comment