- (interactive "sCategory: ")
- (save-window-excursion
- (setq todo-categories (cons cat todo-categories))
- (find-file todo-file-do)
- (widen)
- (goto-char (point-min))
- (let ((posn (search-forward "-*- mode: todo; " 17 t)))
- (if posn
- (progn
- (goto-char posn)
- (kill-line))
- (insert "-*- mode: todo; \n")
- (forward-char -1)))
- (insert (format "todo-categories: %S; -*-" todo-categories))
- (forward-char 1)
- (insert (format "%s%s%s\n%s\n%s %s\n"
- todo-prefix todo-category-beg cat
- todo-category-end
- todo-prefix todo-category-sep)))
- 0)
+ (interactive)
+ (let ((buf (find-file-noselect todo-file-do t))
+ (prompt "Category: "))
+ (unless (zerop (buffer-size buf))
+ (and (null todo-categories)
+ (null todo-cats)
+ (error "Error in %s: File is non-empty but contains no category"
+ todo-file-do)))
+ (unless cat (setq cat (read-from-minibuffer prompt)))
+ (with-current-buffer buf
+ ;; reject names that could induce bugs and confusion
+ (while (and (cond ((string= "" cat)
+ (setq prompt "Enter a non-empty category name: "))
+ ((string-match "\\`\\s-+\\'" cat)
+ (setq prompt "Enter a category name that is not only white space: "))
+ ((member cat todo-categories)
+ (setq prompt "Enter a non-existing category name: ")))
+ (setq cat (read-from-minibuffer prompt))))
+ ;; initialize a newly created Todo buffer for Todo mode
+ (unless (file-exists-p todo-file-do) (todo-mode))
+ (setq todo-categories (cons cat todo-categories))
+ (widen)
+ (goto-char (point-min))
+ (if (search-forward "-*- mode: todo; " (+ (point-min) 16) t)
+ (kill-line)
+ (insert "-*- mode: todo; \n")
+ (forward-char -1))
+ (insert (format "todo-categories: %S; -*-" todo-categories))
+ (forward-char 1)
+ (insert (format "%s%s%s\n%s\n%s %s\n"
+ todo-prefix todo-category-beg cat
+ todo-category-end
+ todo-prefix todo-category-sep))
+ (if (called-interactively-p 'interactive)
+ ;; properly display the newly added category
+ (progn (setq todo-category-number 0) (todo-show))
+ 0))))