(set-language-environment "UTF-8")
(prefer-coding-system 'utf-8-unix)
(set-default-coding-systems 'utf-8-unix)
(set-terminal-coding-system 'utf-8-unix)
(set-keyboard-coding-system 'utf-8-unix)
(set-selection-coding-system 'utf-8-unix)
(set-file-name-coding-system 'utf-8-unix)
(set-clipboard-coding-system 'utf-8-unix)
(set-buffer-file-coding-system 'utf-8-unix)
(if (eq system-type 'windows-nt)
(setq file-name-coding-system 'gbk))
;; Package Initialization
(require 'package)
(add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t)
(package-initialize)
;; Theme Loading
;; Fonts
(defun my/setup-blog-fonts ()
"Setup fonts with precise control over CJK, Punctuation, and Nerd Icons.
Refactored to strictly separate Fixed Pitch (Code) and Variable Pitch (Writing) faces."
(interactive)
(require 'org)
;; =================================================================
;; 1.【核心修复】脚本劫持 (保持不变)
;; =================================================================
(set-char-table-range char-script-table '(#x3000 . #x303F) 'han)
(set-char-table-range char-script-table '(#xFF00 . #xFFEF) 'han)
(set-char-table-range char-script-table '(#x2000 . #x206F) 'han)
;; =================================================================
;; 2. 基础字体 (Default Face) - Emacs 的基底
;; =================================================================
;; 英文/数字: 强制 JetBrains Mono
(set-face-attribute 'default nil :font "JetBrains Mono-13")
;; 中文: 强制 Source Han Sans SC (思源黑体) 用于 UI 和基础对齐
(set-fontset-font t 'han (font-spec :family "Source Han Sans SC"))
(set-fontset-font t 'cjk-misc (font-spec :family "Source Han Sans SC"))
;; =================================================================
;; 3. 【关键修复】固定宽度字体 (Fixed Pitch)
;; =================================================================
;; 专门用于代码块、表格、属性栏。这能解决 "Georgia + Courier" 的问题。
(set-face-attribute 'fixed-pitch nil :family "JetBrains Mono" :height 1.0)
;; 为 fixed-pitch 补充中文部分,保持表格对齐
(let ((fixed-fontset (face-attribute 'fixed-pitch :fontset)))
(when (eq fixed-fontset 'unspecified)
(setq fixed-fontset (create-fontset-from-fontset-spec
(font-xlfd-name (face-attribute 'default :font)))))
(set-fontset-font fixed-fontset 'han (font-spec :family "Source Han Sans SC")))
;; =================================================================
;; 4. 变宽/阅读字体 (Variable Pitch) - 写作模式
;; =================================================================
;; 英文: 优先使用 Source Serif 4,如果没有则回退到 Georgia
(let* ((en-serif-font (if (find-font (font-spec :family "Source Serif 4"))
"Source Serif 4"
"Georgia"))
;; 创建一个专属的 fontset,命名为 fontset-variable
(v-fontset-name "fontset-variable")
;; 注意:create-fontset-from-fontset-spec 需要符合 XLFD 格式或特定的 fontset 描述
;; 这里我们更安全地基于标准 fontset 创建,或者直接定义它
(v-fontset (create-fontset-from-fontset-spec
(font-xlfd-name
(font-spec :family en-serif-font
:registry "fontset-variable")))))
;; 步骤 A: 设定 variable-pitch 面
;; 强制指定 slant 为 normal,防止英文也跟着变斜
(set-face-attribute 'variable-pitch nil
:family en-serif-font
:height 1.1
:weight 'regular
:slant 'normal
:fontset v-fontset-name)
;; 步骤 B: 针对您的系统环境精确配置中文
;; 您的列表显示字体名为 "思源宋体 CN",必须精确匹配这个字符串
(let ((cjk-serif-name "思源宋体 CN"))
(if (member cjk-serif-name (font-family-list))
(progn
;; 针对汉字 (han)
(set-fontset-font v-fontset-name 'han
(font-spec :family cjk-serif-name
:weight 'normal
:slant 'normal)) ;; 关键:显式禁止倾斜
;; 针对中文标点 (#x3000 - #x303F)
(set-fontset-font v-fontset-name '(#x3000 . #x303F)
(font-spec :family cjk-serif-name
:weight 'normal
:slant 'normal)))
(message "Warning: CJK Serif font '%s' not found. Fallback might occur." cjk-serif-name))))
;; =================================================================
;; 5. 标题字体 (Headings)
;; =================================================================
(let ((heading-font-family "Open Sans")
(heading-cjk-family "Noto Sans SC"))
(when (find-font (font-spec :family heading-font-family))
(dolist (face '(org-level-1 org-level-2 org-level-3 org-level-4
org-level-5 org-level-6 org-level-7 org-level-8))
(when (facep face)
(set-face-attribute face nil :family heading-font-family :weight 'bold)
;; 确保标题中文使用黑体
(when (find-font (font-spec :family heading-cjk-family))
(let ((face-fontset (face-attribute face :fontset)))
(when (eq face-fontset 'unspecified)
;; 如果 face 没有独立的 fontset,创建一个
(setq face-fontset (create-fontset-from-fontset-spec
(font-xlfd-name (face-attribute 'default :font)))))
(set-fontset-font face-fontset 'han
(font-spec :family heading-cjk-family :weight 'bold))))))))
;; =================================================================
;; 6. Org 界面元素微调
;; =================================================================
;; 让 Org 的代码块、元数据、表格、引用块强制继承 fixed-pitch
(dolist (face '(org-block org-code org-table org-verbatim org-formula
org-checkbox org-date org-priority org-special-keyword
org-tag line-number))
(when (facep face)
(set-face-attribute face nil :inherit 'fixed-pitch)))
;; 特殊处理:Meta line (如 #+TITLE) 通常需要更淡的颜色,但也需要等宽
(when (facep 'org-meta-line)
(set-face-attribute 'org-meta-line nil :inherit '(font-lock-comment-face fixed-pitch)))
;; =================================================================
;; 7. 【Nerd Icons 修复】强制映射私有使用区 (PUA)
;; =================================================================
(let ((nerd-font (font-spec :family "Symbols Nerd Font Mono")))
(when (find-font nerd-font)
(set-fontset-font t '(#xE000 . #xF8FF) nerd-font nil 'prepend)))
;; =================================================================
;; 8. 【Emoji 修复】
;; =================================================================
(when (eq system-type 'windows-nt)
(let* ((emoji-candidates
'("Segoe UI Emoji" "Symbola" "Noto Emoji" "Apple Color Emoji"))
(primary-emoji-font (cl-find-if (lambda (f) (find-font (font-spec :family f))) emoji-candidates)))
(if primary-emoji-font
(progn
(let ((font-spec (font-spec :family primary-emoji-font)))
(set-fontset-font t 'emoji font-spec nil 'prepend)
(set-fontset-font t '(#x1F000 . #x1FFFF) font-spec nil 'prepend)
(set-fontset-font t '(#x2600 . #x27BF) font-spec nil 'prepend)))
(message "Warning: No suitable Emoji font found."))))
(message "Fonts setup: Default(JB Mono) | Writing(Source Serif 4/Georgia) | Fixed(JB Mono)"))
(defun my/force-restore-fonts (&rest _args)
(message "Theme changed, re-applying fonts...")
(my/setup-blog-fonts))
(advice-add 'load-theme :after #'my/force-restore-fonts)
(add-to-list 'custom-theme-load-path "~/.emacs.d/themes/")
(load-theme 'darcula t)
;; Package Configs
;; Ox-Hugo
(unless (package-installed-p 'ox-hugo)
(package-refresh-contents)
(package-install 'ox-hugo))
(with-eval-after-load 'ox
(require 'ox-hugo)
(setq org-hugo-content-folder "D:/Programs/Blog/Blog-local/source"))
;; YASnippet
(unless (package-installed-p 'yasnippet)
(package-install 'yasnippet))
(with-eval-after-load 'yasnippet
(yas-global-mode 1)
(yas-reload-all))
;; Rainbow Delimiters
(unless (package-installed-p 'rainbow-delimiters)
(package-refresh-contents)
(package-install 'rainbow-delimiters))
(add-hook 'prog-mode-hook #'rainbow-delimiters-mode)
(add-hook 'emacs-lisp-mode-hook #'rainbow-delimiters-mode)
(add-hook 'lisp-interaction-mode-hook #'rainbow-delimiters-mode)
;; Built-in Paren Highlighting
(show-paren-mode 1)
(electric-pair-mode 1)
(setq show-paren-delay 0)
(setq show-paren-style 'parenthesis)
;; GPG Configuration (Fixed for Windows)
(require 'cl-lib) ; 确保cl-some函数可用
(defun my/setup-gpg ()
"配置GPG,优先查找Windows常见安装路径。"
(interactive)
(require 'epa-file)
;; 1. 定义查找列表:优先找用户实际安装位置
(let* ((candidates '("D:/GnuPG/bin/gpg.exe" ; 用户实际安装位置 (最高优先级)
"C:/Program Files (x86)/GnuPG/bin/gpg.exe" ; Gpg4win 默认路径 (64位系统)
"C:/Program Files/GnuPG/bin/gpg.exe" ; Gpg4win 备选路径
"gpg")) ; 系统 PATH
;; 找到第一个存在的路径
(found-gpg (cl-some (lambda (path)
(if (string-match-p "/" path)
(and (file-exists-p path) path)
(executable-find path)))
candidates)))
(if found-gpg
(progn
;; Add GPG path to exec-path for proper discovery
(let ((gpg-dir (file-name-directory found-gpg)))
(when (and gpg-dir (not (member gpg-dir exec-path)))
(add-to-list 'exec-path gpg-dir)))
;; Use custom-set-variables for EPA configuration (StackOverflow solution)
(custom-set-variables
`(epg-gpg-program ,found-gpg)
'(epa-pinentry-mode 'loopback)
'(epg-debug t)
`(epg-gpg-home-directory ,(or (getenv "GNUPGHOME")
(expand-file-name "~/.gnupg")))
'(epa-file-cache-passphrase-for-symmetric-encryption t)
'(epa-file-select-keys 'silent)
'(epa-file-encrypt-to nil)
'(epa-armor t)
'(epg-user-id nil))
;; Enable encrypted file support
(require 'epa-file)
(epa-file-enable)
(message "GPG configured successfully. Path: %s" found-gpg))
;; GPG not found handling
(message "Warning: GPG executable not found. Mastodon will not be able to save credentials securely.")
(message "Please check if Gpg4win is installed and confirm the installation path."))))
;; GPG密钥检测和创建函数
(defun my/check-or-create-gpg-keys ()
"检测GPG密钥,如果没有则提示创建。"
(interactive)
(when epg-gpg-program
(condition-case err
(let* ((context (epg-make-context))
(keys (epg-list-keys context)))
(if keys
(progn
(message "Found %d GPG keys" (length keys))
(dolist (key keys)
(let ((user-ids (epg-key-user-id-list key)))
(when user-ids
(message "Key: %s" (epg-user-id-string (car user-ids)))))))
;; 没有密钥,提供创建选项
(when (yes-or-no-p "未找到GPG密钥,是否创建新密钥对? ")
(my/create-gpg-keypair))))
(error
(message "Error checking GPG keys: %s" (error-message-string err))))))
(defun my/create-gpg-keypair ()
"创建新的GPG密钥对。"
(interactive)
(let* ((name (read-string "输入姓名: "))
(email (read-string "输入邮箱: "))
(passphrase (read-passwd "输入密码(可选,直接回车跳过): "))
(batch-config (format "%%echo Generating GPG key
Key-Type: RSA
Key-Length: 2048
Subkey-Type: RSA
Subkey-Length: 2048
Name-Real: %s
Name-Email: %s
%s
Expire-Date: 0
%%commit
%%echo Done"
name
email
(if (string-empty-p passphrase)
"%no-protection"
(format "Passphrase: %s" passphrase))))
(temp-file (make-temp-file "gpg-batch" nil ".txt")))
(with-temp-file temp-file
(insert batch-config))
(message "Creating GPG keypair, please wait...")
(let ((result (shell-command (format "\"%s\" --batch --generate-key \"%s\""
epg-gpg-program temp-file))))
(delete-file temp-file)
(if (= result 0)
(progn
(message "GPG keypair created successfully!")
(my/check-or-create-gpg-keys))
(message "Failed to create GPG keypair. Please check configuration")))))
;; GPG配置文件检查和修复
(defun my/check-gpg-config ()
"检查和修复GPG配置文件。"
(interactive)
(let* ((gpg-home (or (getenv "GNUPGHOME")
(expand-file-name "~/.gnupg")))
(gpg-conf (expand-file-name "gpg.conf" gpg-home))
(gpg-agent-conf (expand-file-name "gpg-agent.conf" gpg-home)))
;; 确保.gnupg目录存在
(unless (file-directory-p gpg-home)
(make-directory gpg-home t)
(message "Created GPG home directory: %s" gpg-home))
;; 检查和创建gpg.conf
(unless (file-exists-p gpg-conf)
(with-temp-file gpg-conf
(insert "# GPG配置文件\n")
(insert "use-agent\n")
(insert "armor\n")
(insert "keyid-format long\n"))
(message "Created gpg.conf configuration file"))
;; 检查和创建gpg-agent.conf (Windows需要)
(unless (file-exists-p gpg-agent-conf)
(with-temp-file gpg-agent-conf
(insert "# GPG Agent配置文件\n")
(insert "default-cache-ttl 28800\n")
(insert "max-cache-ttl 86400\n")
(when (eq system-type 'windows-nt)
(insert "pinentry-program C:/Program Files (x86)/Gpg4win/bin/pinentry-basic.exe\n")))
(message "Created gpg-agent.conf configuration file"))
(message "GPG configuration check completed")))
;; 一键修复EPA问题的函数
(defun my/fix-epa-issues ()
"一键诊断和修复EPA配置问题。"
(interactive)
(message "Starting EPA diagnostics and repair...")
;; 重新配置GPG
(my/setup-gpg)
;; 检查配置文件
(my/check-gpg-config)
;; 检查密钥
(my/check-or-create-gpg-keys)
;; 重新初始化EPA
(when (fboundp 'epa-file-disable)
(epa-file-disable))
(epa-file-enable)
;; 测试EPA功能
(run-with-timer 3 nil (lambda ()
(condition-case err
(progn
(epg-make-context)
(message "EPA repair completed! Please test Mastodon functionality"))
(error
(message "EPA still has issues: %s" (error-message-string err))
(message "Suggestion: manually check GPG installation and key configuration"))))))
;; Simple EPA test function
(defun my/test-epa-quick ()
"Quick EPA functionality test."
(interactive)
(condition-case err
(progn
(require 'epg)
(epg-make-context)
(message "EPA test passed - ready for Mastodon"))
(error
(message "EPA test failed: %s" (error-message-string err)))))
;; Initialize GPG configuration
(my/setup-gpg)
;; (run-with-timer 1 nil 'my/check-gpg-config)
;; (run-with-timer 2 nil 'my/check-or-create-gpg-keys)
;; (run-with-timer 3 nil 'my/test-epa-quick)
;; Mastodon Client
(unless (package-installed-p 'mastodon)
(package-install 'mastodon))
(with-eval-after-load 'mastodon
;; 基础设置:请修改为您自己的实例和用户名
(setq mastodon-instance-url "https://m.otter.homes"
mastodon-active-user "cytrogen")
;; 界面设置
(setq mastodon-client-width-mode nil)
;; --- UI Modernization (Avatars & Images) ---
;; 1. Enable Avatars
(setq mastodon-tl--show-avatars t)
;; Note: 'mastodon-client-display-avatar-in-status' doesn't seem to be a std var in this version,
;; checking source: mastodon-tl--show-avatars is the custom var for avatars.
;; 2. Optimize Image Preview
(setq mastodon-media-format-type 'preview)
;; 智能EPA绕过和错误隔离
(defvar my/mastodon-encryption-attempted nil
"记录是否已尝试启用加密。")
(defun my/test-mastodon-encryption ()
"测试Mastodon是否能安全使用GPG加密。"
(condition-case err
(progn
(epg-make-context)
(epg-list-keys (epg-make-context))
t) ; 成功返回t
(error nil))) ; 失败返回nil
;; 根据EPA功能自动选择加密方式
(if (and (not my/mastodon-encryption-attempted)
(my/test-mastodon-encryption))
(progn
(setq mastodon-client-file-encryption t)
(setq my/mastodon-encryption-attempted t)
(message "Mastodon enabled GPG encrypted storage"))
(progn
(setq mastodon-client-file-encryption nil)
(setq my/mastodon-encryption-attempted t)
(message "Mastodon using plaintext storage (EPA unavailable or problematic)")))
;; 运行时错误隔离
(condition-case gpg-err
(when mastodon-client-file-encryption
(when (and epg-gpg-program (file-exists-p epg-gpg-program))
(message "Mastodon GPG configuration validation completed")))
(error
(setq mastodon-client-file-encryption nil) ; 自动fallback到明文
(message "Detected EPA issues, automatically switching to plaintext storage: %s" (error-message-string gpg-err)))))
;; Mastodon UI Beautification (Nerd Icons & Modern Look)
(unless (package-installed-p 'nerd-icons)
(package-install 'nerd-icons))
;; --- Nerd Icons Font Setup and Verification ---
;; Emacs needs to be able to find a suitable Nerd Font to display icons.
;; The recommended font is "Symbols Nerd Font Mono".
;; If you see empty squares instead of icons, you might need to install it.
;; Run `M-x nerd-icons-install-fonts` in Emacs, then manually install the font file.
;; If Emacs still doesn't see it, restart Emacs.
(defun my/verify-nerd-font ()
"Check if Symbols Nerd Font is available."
(interactive)
(let* ((font-name "Symbols Nerd Font Mono")
(font (find-font (font-spec :name font-name))))
(if font
(message "✅ 成功! Emacs 已找到字体: %s" font)
(message "❌ 失败! Emacs 找不到 '%s'。请确认已选择'为所有用户安装'并重启了 Emacs。" font-name))))
;; If you already have another Nerd Font (e.g., "JetBrainsMono Nerd Font") and prefer to use it,
;; uncomment the line below and replace "Your Nerd Font Name" with its exact name.
(with-eval-after-load 'nerd-icons
;; (setq nerd-icons-font-family "Your Nerd Font Name")
)
(with-eval-after-load 'mastodon
(require 'nerd-icons)
;; 1. Replace text symbols with Nerd Icons
(setq mastodon-tl--symbols
`((reply . (,(nerd-icons-faicon "nf-fa-reply") . "R"))
(boost . (,(nerd-icons-faicon "nf-fa-retweet") . "B"))
(reblog . (,(nerd-icons-faicon "nf-fa-retweet") . "B"))
(favourite . (,(nerd-icons-faicon "nf-fa-star") . "F"))
(bookmark . (,(nerd-icons-faicon "nf-fa-bookmark") . "K"))
(media . (,(nerd-icons-faicon "nf-fa-file_image_o") . "[media]"))
(verified . (,(nerd-icons-octicon "nf-oct-verified") . "V"))
(locked . (,(nerd-icons-faicon "nf-fa-lock") . "[locked]"))
(private . (,(nerd-icons-faicon "nf-fa-lock") . "[followers]"))
(mention . (,(nerd-icons-faicon "nf-fa-at") . "[mention]"))
(direct . (,(nerd-icons-faicon "nf-fa-envelope") . "[direct]"))
(edited . (,(nerd-icons-faicon "nf-fa-pencil") . "[edited]"))
(update . (,(nerd-icons-faicon "nf-fa-pencil") . "[edited]"))
(status . (,(nerd-icons-faicon "nf-fa-bell") . "[posted]"))
(poll . (,(nerd-icons-faicon "nf-fa-bar_chart") . "[poll]"))
(follow . (,(nerd-icons-faicon "nf-fa-user_plus") . "+"))
(follow_request . (,(nerd-icons-faicon "nf-fa-user_plus") . "+"))
(severed_relationships . (,(nerd-icons-faicon "nf-fa-chain_broken") . "//"))
(moderation_warning . (,(nerd-icons-faicon "nf-fa-exclamation_triangle") . "!!"))
(reply-bar . ("┃" . "|"))))
;; 2. Modernize Faces
;; Use variable width font for main text (if desired)
(add-hook 'mastodon-mode-hook #'variable-pitch-mode)
;; Make headers stand out
(set-face-attribute 'mastodon-display-name-face nil :height 1.2 :weight 'bold)
(set-face-attribute 'mastodon-handle-face nil :height 0.9 :slant 'italic :foreground "gray60")
;; Improve metadata visibility
(set-face-attribute 'mastodon-toot-docs-face nil :height 0.85 :foreground "gray50")
;; Fix alignment for icons if needed
(when (display-graphic-p)
(setq mastodon-tl--enable-proportional-fonts t)))
;; Universal Elisp Tags Filter
(with-eval-after-load 'ox
(defun my/org-export-hexo-universal-block (block backend info)
(when (org-export-derived-backend-p backend 'md)
(let* ((type (downcase (org-element-property :type block)))
(content (org-export-data (org-element-contents block) info)))
(format "{%% %s %%}\n%s{%% end%s %%}" type content type))))
(add-to-list 'org-export-filter-special-block-functions 'my/org-export-hexo-universal-block))
;; Visual Line Mode
(add-hook 'org-mode-hook #'visual-line-mode)
(add-hook 'markdown-mode-hook #'visual-line-mode)
(when (fboundp 'adaptive-wrap-prefix-mode)
(add-hook 'visual-line-mode-hook #'adaptive-wrap-prefix-mode))
;; Fonts
(defun my/org-mode-visual-setup ()
"Activate visual adjustments for Org mode writing."
(variable-pitch-mode 1) ; 开启变宽字体模式(正文使用 Source Serif 4/宋体)
(visual-line-mode 1)) ; 开启视觉折行(按词换行,而非按字符截断)
(add-hook 'org-mode-hook 'my/org-mode-visual-setup)
;; Apply Fonts
(if (daemonp)
(add-hook 'after-make-frame-functions
(lambda (frame) (with-selected-frame
frame (my/setup-blog-fonts))))
(my/setup-blog-fonts))
;; Org Directory (Dynamic Setting)
(defvar my/org-path-config-file (concat user-emacs-directory ".org-path")
"File to store the user's Org directory path.")
(defun my/setup-org-directory ()
"Load Org directory from config file or prompt user to select one."
(let ((path nil))
;; 1. Try to read from file
(when (file-exists-p my/org-path-config-file)
(with-temp-buffer
(insert-file-contents my/org-path-config-file)
(setq path (string-trim (buffer-string)))))
;; 2. Validate path, if invalid/missing, prompt user
(unless (and path (file-directory-p path))
(setq path (read-directory-name "请选择您的 Org 笔记根目录 (Please select Org root): " "D:/"))
(unless (file-directory-p path)
(make-directory path t))
;; Save for next time
(with-temp-file my/org-path-config-file
(insert path)))
;; 3. Apply setting
(setq org-directory (file-name-as-directory path))
(setq org-default-notes-file (concat org-directory "inbox.org"))
(message "Org Directory loaded: %s" org-directory)))
;; Execute setup immediately
(my/setup-org-directory)
;; Set agenda files to include all org files in the directory
(setq org-agenda-files
(append (list org-directory)
(when (file-exists-p org-directory)
(directory-files org-directory t "\\.org$"))))
;; Ensure Org directories exist immediately to prevent crashes during config load
(let ((notes-dir (concat org-directory "notes/")))
(unless (file-exists-p notes-dir)
(make-directory notes-dir t)
(message "Created missing directory: %s" notes-dir)))
;; --- Custom Dashboard / Startup Screen ---
(defun my/show-dashboard ()
"Render a custom GTD dashboard."
(interactive)
(let ((buf (get-buffer-create "*Cytrogen's Home*")))
(with-current-buffer buf
(let ((inhibit-read-only t))
(erase-buffer)
;; Header
(insert "#+TITLE: Cytrogen 的个人领地\n")
(insert "#+STARTUP: showall\n\n")
(insert "\n")
(insert "Welcome back, Cytrogen.\n")
(insert "------------------------------------\n\n")
;; GTD Intro
(insert "* GTD 工作流指南\n\n")
(insert "1. Capture (收集): 大脑用来思考,不是用来记事的。\n")
(insert " 任何想法、任务、灵感,第一时间通过 Capture 放入 Inbox。\n")
(insert " - [C-c c] 唤起 Capture 面板\n")
(insert " - [C-c C-c] 确认保存\n")
(insert " - [C-c C-k] Abort (放弃/取消)\n\n")
(insert "2. Process (整理): 清空 Inbox。\n")
(insert " 每天/每周定期检查 Inbox,将任务移动到具体的项目或归档。\n")
(insert " - [C-c w] Quick Refile (快速移动条目)\n\n")
(insert "3. Do (执行): 专注当下。\n")
(insert " 通过 Agenda 查看今日待办。\n")
(insert " - [C-c a] 打开 Agenda 视图\n\n")
;; Keybindings Cheatsheet
(insert "* 常用命令\n\n")
(insert "| 快捷键 | 描述 | 命令 |\n")
(insert "|---|---|---|\n")
(insert "| ~C-c c~ | 快速记录 | org-capture |\n")
(insert "| ~C-c a~ | 日程/代办 | org-agenda |\n")
(insert "| ~C-c w~ | 快速归档 | my/quick-refile |\n")
(insert "| ~C-c o~ | 打开笔记 | my/open-org-file |\n")
(insert "| ~C-c m~ | 长毛象 | mastodon |\n")
(insert "| ~C-c i~ | 编辑配置 | my/open-init-file |\n")
(insert "| ~C-c r~ | 重载配置 | my/reload-init-file |\n")
;; Footer
(insert "\n\n/\"保持简单,保持流动。\"/\n")
(org-mode)
(my/org-mode-visual-setup)
(org-indent-mode 1)
(visual-line-mode 1)
(when (bound-and-true-p display-line-numbers-mode)
(display-line-numbers-mode -1))
(setq mode-line-format nil)
(setq-local org-hide-emphasis-markers t)
(goto-char (point-min))
(while (re-search-forward "^#\\+.*$" nil t)
(add-text-properties (match-beginning 0) (match-end 0)
'(invisible t)))
(add-to-list 'buffer-invisibility-spec '(t . t))
(setq buffer-read-only t)
(goto-char (point-min))
(while (get-char-property (point) 'invisible)
(forward-line 1))))
(switch-to-buffer buf)))
;; Disable default startup screen and show ours
(setq inhibit-startup-screen t)
(add-hook 'emacs-startup-hook #'my/show-dashboard)
(with-eval-after-load 'org
;; --- Refile Configuration ---
;; 强化 Refile 功能,允许将条目移动到项目或分类的具体标题下
(setq org-refile-use-outline-path 'file)
(setq org-outline-path-complete-in-steps nil)
(setq org-refile-allow-creating-parent-nodes 'confirm)
;; 设定 Refile 的目标文件
(setq org-refile-targets
`((nil :maxlevel . 3) ; 当前 buffer 的标题 (直到 3 级)
(org-agenda-files :maxlevel . 3) ; 所有 Agenda 文件 (直到 3 级)
;; 添加 notes 目录下的所有 org 文件
(,(directory-files-recursively (concat org-directory "notes/") "\\.org$") :maxlevel . 3)))
;; --- Capture Templates ---
;; 强化 Capture 功能,快速捕获任务、笔记和博客想法
(setq org-capture-templates
'(("t" "Todo [任务]" entry (file+headline "inbox.org" "Tasks")
"* TODO %?\n %U\n %a")
("n" "Note [笔记/灵感]" entry (file+headline "inbox.org" "Notes")
"* %? \n %U\n")
("b" "Blog Idea [写作灵感]" entry (file+headline "inbox.org" "Writing Ideas")
"* IDEA %?\n :PROPERTIES:\n :CAPTURED: %U\n :END:\n")
("r" "Reading [阅读/学习]" entry (file+headline "notes/reading.org" "Inbox")
"* %? \n :PROPERTIES:\n :SOURCE: %^{Source}\n :END:\n %U\n")
("j" "Journal [学习日志]" entry (file+olp+datetree "notes/journal.org")
"* %?\n %U\n")
("s" "Snippet [代码片段]" entry (file+headline "notes/snippets.org" "新片段")
"* %^{Title}\n#+BEGIN_SRC %^{Language}\n%?\n#+END_SRC\n %U\n")
("m" "Mastodon [长毛象]" entry (file+headline "inbox.org" "Notes")
"* %^{Title}\n:PROPERTIES:\n:SOURCE: %l\n:CAPTURED: %U\n:END:\n\n#+BEGIN_QUOTE\n%i\n#+END_QUOTE\n\n%?")
("S" "Shopping" entry (file+olp "inbox.org" "Shopping List")
"* Shopping List %U\n - [ ] %?\n"))))
;; Syncthing
(setq backup-directory-alist `(("." . ,(concat user-emacs-directory "saves/"))))
(setq auto-save-file-name-transforms `((".*" ,(concat user-emacs-directory "saves/") t)))
(setq create-lockfiles nil)
(unless (file-exists-p (concat user-emacs-directory "saves/"))
(make-directory (concat user-emacs-directory "saves/")))
;; Custom Variables
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(epa-armor t t)
'(epa-file-cache-passphrase-for-symmetric-encryption t)
'(epa-file-encrypt-to nil t)
'(epa-file-select-keys 'silent)
'(epg-debug t)
'(epg-gpg-home-directory "c:/Users/Cytrogen/AppData/Roaming/.gnupg")
'(epg-gpg-program "D:/GnuPG/bin/gpg.exe")
'(epg-pinentry-mode 'loopback)
'(epg-user-id nil t)
'(package-selected-packages
'(adaptive-wrap mastodon nerd-icons ox-hugo rainbow-delimiters
yasnippet)))
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
)
;; Global Keybindings
(global-set-key (kbd "C-c c") 'org-capture)
(global-set-key (kbd "C-c a") 'org-agenda)
(global-set-key (kbd "C-c m") 'mastodon)
(global-set-key (kbd "C-c C-w") 'org-refile)
(global-set-key (kbd "C-c w") 'my/quick-refile)
(global-set-key (kbd "C-c i") 'my/open-init-file)
(global-set-key (kbd "C-c r") 'my/reload-init-file)
(global-set-key (kbd "C-c o") 'my/open-org-file)
;; Custom Functions
(require 'cl-lib)
;; Quick Access to Configuration
(defun my/open-init-file ()
"快速打开init.el配置文件进行编辑。"
(interactive)
(find-file user-init-file)
(message "Opened configuration file: %s" user-init-file))
(defun my/reload-init-file ()
"重新加载init.el配置文件。"
(interactive)
(load-file user-init-file)
(message "Configuration file reloaded: %s" user-init-file))
(defun my/open-org-file ()
"交互式选择并打开 Org 目录下的文件。"
(interactive)
;; 1. 确保 org-directory 存在
(unless (and org-directory (file-directory-p org-directory))
(user-error "Org directory not found or invalid: %s" org-directory))
(let* ((files (directory-files-recursively org-directory "\\.org$"))
;; 2. 构建候选列表,如果列表为空则提示
(candidates (if files
(mapcar (lambda (f)
(cons (file-relative-name f org-directory) f))
files)
nil)))
(if (not candidates)
(message "No .org files found in %s" org-directory)
;; 3. 正常选择
(let ((selection (completing-read "Open Org File: " (mapcar #'car candidates))))
(when selection
(let ((full-path (cdr (assoc selection candidates))))
(when full-path
(find-file full-path)
(message "Opened: %s" selection))))))))
;; Interactive Refile System
(defvar my/refile-targets
'(("t" "Tech"
(("d" "Development" "tech.org" "Development")
("l" "Tools" "tech.org" "Tools")
("e" "Learning" "tech.org" "Learning")
("p" "Projects" "tech.org" "Projects")))
("s" "Shopping"
(("l" "Shopping Lists" "shopping.org" "Shopping Lists")
("b" "Budgets" "shopping.org" "Budgets")
("p" "Purchases" "shopping.org" "Purchases")))
("p" "Personal"
(("h" "Health" "personal.org" "Health")
("f" "Finance" "personal.org" "Finance")
("m" "Family" "personal.org" "Family")
("g" "Goals" "personal.org" "Goals")))
("n" "Notes"
(("r" "Reading" "notes/reading.org" "Inbox")
("p" "Projects" "notes/projects.org" "Active")
("a" "Archive Projects" "notes/projects.org" "Completed"))))
"Quick refile destinations in format: (key label ((subkey sublabel file heading)))")
(defun my/quick-refile ()
"Interactive refile with menu selection."
(interactive)
(unless (org-region-active-p)
(org-back-to-heading t))
;; Display main categories
(let* ((categories (mapcar (lambda (cat)
(format "[%s] %s" (car cat) (cadr cat)))
my/refile-targets))
(prompt (concat "Quick Refile to: " (mapconcat 'identity categories " ") " "))
(choice (read-char-exclusive prompt)))
;; Find selected category
(let* ((choice-str (char-to-string choice))
(selected-cat (cl-find-if (lambda (cat) (string= (car cat) choice-str))
my/refile-targets)))
(if (not selected-cat)
(message "Invalid choice: %s" choice-str)
;; Display subcategories
(let* ((subcats (caddr selected-cat))
(subcat-display (mapcar (lambda (sub)
(format "[%s] %s" (car sub) (cadr sub)))
subcats))
(sub-prompt (concat "Choose destination: "
(mapconcat 'identity subcat-display " ") " "))
(sub-choice (read-char-exclusive sub-prompt)))
;; Find selected subcategory and refile
(let* ((sub-choice-str (char-to-string sub-choice))
(selected-sub (cl-find-if (lambda (sub) (string= (car sub) sub-choice-str))
subcats)))
(if (not selected-sub)
(message "Invalid subcategory choice: %s" sub-choice-str)
;; Perform the refile
(let* ((file (caddr selected-sub))
(heading (cadddr selected-sub))
(target-path (expand-file-name file org-directory)))
(if (not (file-exists-p target-path))
(message "Target file does not exist: %s" target-path)
(let ((pos (save-excursion
(with-current-buffer (find-file-noselect target-path)
(org-find-exact-headline-in-buffer heading)))))
(if (not pos)
(message "Heading '%s' not found in %s" heading file)
(org-refile nil nil (list heading target-path nil pos))
(message "Refiled to: %s -> %s" file heading))))))))))))
(defun my/ensure-org-infrastructure ()
"Ensure all necessary Org files and base headings exist based on capture templates."
(interactive)
(require 'org)
(message "--- Org Infrastructure Check Start ---")
(message "Org Directory: %s" org-directory)
;; Define complete file structure for capture & refile system
(let ((file-configs '(;; Main files in root directory
("inbox.org" . ("Tasks" "Notes" "Writing Ideas" "Shopping List"))
("tech.org" . ("Development" "Tools" "Learning" "Projects"))
("shopping.org" . ("Shopping Lists" "Budgets" "Purchases"))
("personal.org" . ("Health" "Finance" "Family" "Goals"))
;; Notes subdirectory files
("notes/reading.org" . ("Inbox"))
("notes/journal.org" . nil) ; Uses datetree, no specific headings needed
("notes/snippets.org" . ("新片段"))
("notes/projects.org" . ("Active" "Backlog" "Completed")))))
;; 1. Ensure directories and files exist
(dolist (config file-configs)
(let* ((file (car config))
(headings (cdr config))
(path (expand-file-name file org-directory)))
(message "Checking file: %s" path)
;; Create file if it doesn't exist
(unless (file-exists-p path)
(message " [MISSING] Creating file...")
(condition-case err
(progn
(make-directory (file-name-directory path) t)
(with-temp-file path
(insert "#+TITLE: " (capitalize (file-name-base file)) "\n\n"))
(message " [SUCCESS] File created."))
(error (message " [ERROR] Failed to create file: %s" err))))
;; Check and create required headings
(when (and (file-exists-p path) headings)
(with-current-buffer (find-file-noselect path)
(save-excursion
(dolist (heading headings)
(goto-char (point-min))
(unless (re-search-forward (format "^\\* %s" (regexp-quote heading)) nil t)
(message " [MISSING HEADING] Creating '%s' in %s" heading file)
(goto-char (point-max))
(unless (bolp) (insert "\n"))
(insert "* " heading "\n"))))
(save-buffer)))))
(message "--- Org Infrastructure Check End ---")))
(defun my/check-gpg-status ()
"检查并显示当前GPG配置状态。"
(interactive)
(with-output-to-temp-buffer "*GPG状态检查*"
(princ "=== GPG状态检查 ===\n\n")
;; 使用与my/setup-gpg相同的查找逻辑
(princ "1. GPG程序检查(按优先级顺序):\n")
(let* ((candidates '("D:/GnuPG/bin/gpg.exe" ; 用户实际安装位置
"C:/Program Files (x86)/GnuPG/bin/gpg.exe"
"C:/Program Files/GnuPG/bin/gpg.exe"
"gpg"))
(found-paths '()))
;; 检查每个候选路径
(dolist (path candidates)
(let ((exists (if (string-match-p "/" path)
(file-exists-p path)
(executable-find path))))
(if exists
(progn
(princ (format " Found: %s\n" path))
(push path found-paths))
(princ (format " ✗ %s\n" path)))))
;; 显示当前使用的路径
(princ "\n2. 当前Emacs配置:\n")
(if epg-gpg-program
(progn
(princ (format " Using path: %s\n" epg-gpg-program))
(condition-case err
(let ((version (shell-command-to-string (format "\"%s\" --version" epg-gpg-program))))
(princ (format " Version: %s" (car (split-string version "\n")))))
(error (princ (format " Warning: version check failed: %s\n" (error-message-string err))))))
(princ " ✗ epg-gpg-program 未设置\n"))
(princ (format " epa-pinentry-mode: %s\n" epa-pinentry-mode))
;; Mastodon相关设置
(princ "\n3. Mastodon配置:\n")
(if (boundp 'mastodon-client-file-encryption)
(princ (format " Encryption setting: %s\n"
(if mastodon-client-file-encryption "GPG加密" "明文存储(当前设置)")))
(princ " ✓ 加密设置: 默认(依赖GPG)\n"))
;; 给出建议
(princ "\n=== 状态总结 ===\n")
(cond
((not (boundp 'mastodon-client-file-encryption))
(princ "⚠️ Mastodon包未加载,无法确定加密设置\n"))
((not mastodon-client-file-encryption)
(princ "OK: Mastodon configured for plaintext storage, should work normally\n")
(princ " For GPG encryption, run M-x my/test-gpg-basic to diagnose issues\n"))
((and epg-gpg-program (file-exists-p epg-gpg-program))
(princ "OK: GPG configured, mastodon should work with encryption\n"))
(found-paths
(princ "Warning: Found GPG but not properly configured, please restart Emacs\n"))
(t
(princ "Error: GPG not found, suggest enabling plaintext storage\n"))))
(princ "\nRun M-x my/setup-gpg to reconfigure GPG\n")))
(defun my/test-gpg-basic ()
"Test basic GPG functionality to help troubleshoot issues."
(interactive)
(with-output-to-temp-buffer "*GPG Basic Test*"
(princ "=== GPG Basic Functionality Test ===\n\n")
;; 测试GPG版本
(princ "1. GPG Version Test:\n")
(condition-case err
(let ((version-output (shell-command-to-string (format "\"%s\" --version" epg-gpg-program))))
(princ (format " Version info:\n%s\n" version-output)))
(error (princ (format " Error: Version check failed: %s\n" (error-message-string err)))))
;; 测试密钥列表
(princ "2. Key Check:\n")
(condition-case err
(let ((keys-output (shell-command-to-string (format "\"%s\" --list-keys" epg-gpg-program))))
(if (string-match "gpg: error" keys-output)
(princ " Warning: Key list has warnings, but this is usually normal\n")
(princ " Key list access normal\n")))
(error (princ (format " Error: Key check failed: %s\n" (error-message-string err)))))
;; 测试Emacs EPA
(princ "3. Emacs EPA Test:\n")
(condition-case err
(progn
(require 'epg)
(let ((context (epg-make-context)))
(princ " EPA context created successfully\n")))
(error (princ (format " Error: EPA test failed: %s\n" (error-message-string err)))))
;; 给出建议
(princ "\n=== Suggestions ===\n")
(princ "If GPG basic functionality works but mastodon still has issues:\n")
(princ "1. Plaintext storage is currently enabled, mastodon should work normally\n")
(princ "2. For full GPG support, you may need to generate GPG keypair\n")
(princ "3. Run: gpg --full-generate-key (in command line)\n")
(princ "4. Or continue using plaintext storage (usually secure enough for personal use)\n")))
;; Insert Newsletter TOC
(defun my/slugify-title (title)
"Convert title to anchor-compatible slug, similar to the nodejs script."
(let ((slug title))
;; Remove 《》 brackets
(setq slug (replace-regexp-in-string "《\\|》" "" slug))
;; Remove punctuation, keep Unicode letters, numbers, spaces, hyphens
(setq slug (replace-regexp-in-string "[^[:alnum:]\\s-]" "" slug))
;; Replace spaces with hyphens
(setq slug (replace-regexp-in-string "\\s+" "-" slug))
;; Convert to lowercase
(downcase slug)))
(defun my/generate-newsletter-toc ()
"Generate TOC for newsletter, similar to the nodejs script."
(interactive)
(save-excursion
(goto-char (point-min))
;; Find the end of details block
(if (not (re-search-forward "#+END_details" nil t))
(message "Error: Could not find #+END_details block")
(let ((toc-sections '())
(current-section nil))
;; Parse content after the details block
(while (not (eobp))
(beginning-of-line)
(let ((line (thing-at-point 'line t)))
(cond
;; Match H2 headings (exported as ## in markdown)
((string-match "^\\* \\(.*\\)$" line)
(let ((section-title (match-string 1 line)))
(setq current-section (list :title section-title :articles '()))
(push current-section toc-sections)))
;; Match H4 headings with article links (exported as #### [...](url))
((and current-section
(string-match "^\\*\\*\\*\\* \\[\\[.*?\\]\\[《\\(.*?\\)》\\]\\]" line))
(let ((article-title (match-string 1 line)))
(push article-title (plist-get current-section :articles))))))
(forward-line 1))
;; Reverse to get correct order
(setq toc-sections (reverse toc-sections))
(dolist (section toc-sections)
(setq section (plist-put section :articles (reverse (plist-get section :articles)))))
;; Generate TOC markdown
(let ((toc-content "\n## 输入\n\n"))
(dolist (section toc-sections)
(let ((section-title (plist-get section :title))
(articles (plist-get section :articles)))
(when articles
(setq toc-content
(concat toc-content
(format "### %s\n\n" section-title)))
(dolist (article articles)
(let ((display-title article)
(anchor (my/slugify-title article)))
(setq toc-content
(concat toc-content
(format "- [%s](#%s)\n" display-title anchor))))
(setq toc-content (concat toc-content "\n")))))
;; Find the details block and replace its content
(goto-char (point-min))
(if (re-search-forward "#+BEGIN_details 本期导读" nil t)
(progn
(forward-line 4) ; Skip PROPERTIES block
(let ((start (point)))
(if (re-search-forward "#+END_details" nil t)
(progn
(beginning-of-line)
(delete-region start (point))
(insert toc-content)
(message "Newsletter TOC generated and inserted!"))
(message "Error: Could not find #+END_details"))))
(message "Error: Could not find details block"))))))))
(defun my/insert-newsletter-toc ()
"Deprecated: Use my/generate-newsletter-toc instead."
(interactive)
(message "Please use M-x my/generate-newsletter-toc instead."))
;; Auto-save Refile
(defun my/save-after-refile (&rest _)
(org-save-all-org-buffers))
(advice-add 'org-refile :after #'my/save-after-refile)
;; Run infrastructure check after all functions are defined
(my/ensure-org-infrastructure)