分享代码——golang自动插入注释

因为flycheck使用了golint, flycheck总是显示代码没有注释的警告 exported method Raw should have comment or be unexported (go-golint), 也没找到什么方法来禁止它, 作为强迫症受不了,总不能一个一个去注释, 所以写了一个函数来自动注释整个文件的所有未注释函数:

   (defun maple/go-auto-comment()
    (interactive)
    (unless (featurep 'imenu)
      (require 'imenu nil t))
    (let* ((imenu-auto-rescan t)
           (imenu-auto-rescan-maxout (if current-prefix-arg
                                         (buffer-size)
                                       imenu-auto-rescan-maxout))
           (items (imenu--make-index-alist t))
           (items (delete (assoc "*Rescan*" items) items)))
      (cl-mapcan
       (lambda(item)
         (cl-mapcan
          (if (string= (car item) "func")
              'maple/go-func-comment
            'maple/go-type-comment)
          (cdr item)))
       items)))

  (defun maple/go-add-comment(func point)
    (save-excursion
      (goto-char point)
      (forward-line -1)
      (when (not (looking-at (concat "// " func)))
        (end-of-line) (newline-and-indent)
        (insert (concat "// " func " ..")))))

  (defun maple/go-func-comment(f)
    (let ((func (car f)))
      (if (and (string-prefix-p "(" func)
               (string-match "[)] \\(.*\\)[(]\\(.*\\)[)]\\(.*\\)$" func))
          (maple/go-add-comment (match-string 1 func) (cdr f))
        (if (string-match "\\(.*\\)[(]\\(.*\\)[)]\\(.*\\)$" func)
            (maple/go-add-comment (match-string 1 func) (cdr f))
          (maple/go-add-comment (car f) (cdr f))))))

  (defun maple/go-type-comment(f)
    (maple/go-add-comment (car f) (cdr f)))
2 个赞

666,有机会试下