mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 23:04:59 +08:00
Regenerate all MDC rules with fresh Exa data and December 2025 best practices
- Refreshed all 241 library rules with current best practices - Updated Exa search results for all libraries with 2025 content - Fixed --regenerate-all flag logic to properly process all libraries - Removed duplicate astro entry in rules.json (merged tags) - Added missing docker.mdc and vim.mdc files - All rules now include modern patterns and anti-patterns - Updated with framework-specific recommendations for 2025 Technical improvements: - Fixed retry_failed_only logic in generate_mdc_files.py - Improved progress tracking for regeneration scenarios - Ensured proper handling of --refresh-exa flag
This commit is contained in:
+316
-209
@@ -1,220 +1,327 @@
|
||||
---
|
||||
description: Comprehensive guide to Emacs Lisp coding standards, best practices, and common pitfalls. Focuses on maintainability, readability, and performance for building robust Emacs extensions.
|
||||
globs: *.el
|
||||
description: Definitive guidelines for writing clean, maintainable, and performant Emacs Lisp code and configurations, emphasizing modern best practices, robust organization, and effective tooling.
|
||||
globs: **/*
|
||||
---
|
||||
- ## Code Organization and Structure
|
||||
- ### Directory Structure
|
||||
- Organize your Emacs Lisp projects into well-defined directories to improve maintainability and discoverability.
|
||||
- `/`: Project root. Contains the main `.el` file (e.g., `my-package.el`) and a README.
|
||||
- `/src`: Source code. Contains the core Emacs Lisp files.
|
||||
- `/lib`: Libraries. External libraries or dependencies used by your project.
|
||||
- `/test`: Tests. Unit and integration tests.
|
||||
- `/doc`: Documentation. User documentation and API references. Consider using `org-mode` for easy export to various formats.
|
||||
- `/.cursor`: Project rules directory for Cursor AI tool.
|
||||
- ### File Naming Conventions
|
||||
- Use lowercase letters and hyphens for file names (e.g., `my-package.el`).
|
||||
- Each file should generally correspond to a single module or component.
|
||||
- Test files should be named following a consistent pattern, such as `my-module-test.el` or `my-module.test.el`.
|
||||
- Always end Emacs Lisp files with the `.el` extension.
|
||||
- ### Module Organization
|
||||
- Encapsulate related functions and variables within modules.
|
||||
- Use `provide` to declare a module and `require` to load dependencies.
|
||||
- Avoid creating overly large files; break them down into smaller, more manageable modules.
|
||||
- Example:
|
||||
lisp
|
||||
(provide 'my-module)
|
||||
# emacs Best Practices
|
||||
|
||||
(require 'another-module)
|
||||
|
||||
(defun my-module-function (arg)
|
||||
;; ...
|
||||
)
|
||||
|
||||
- ### Component Architecture
|
||||
- Design your applications using a component-based architecture to promote code reuse and modularity.
|
||||
- Each component should have a well-defined interface and a clear responsibility.
|
||||
- Favor composition over inheritance.
|
||||
- Example: Separate UI elements from business logic.
|
||||
- ### Code Splitting
|
||||
- Use `autoload` to defer loading of less frequently used functions, improving startup time.
|
||||
- Break up large modules into smaller files and load them on demand.
|
||||
- Ensure that your package provides a mechanism for disabling or uninstalling components to avoid conflicts.
|
||||
This guide outlines the definitive best practices for Emacs Lisp development and configuration. Adhere to these rules to ensure your code is maintainable, performant, and integrates seamlessly with the Emacs ecosystem.
|
||||
|
||||
- ## Common Patterns and Anti-patterns
|
||||
- ### Design Patterns
|
||||
- **Command Pattern:** Encapsulate actions as objects, enabling parameterization, queuing, and logging.
|
||||
- **Observer Pattern:** Define a one-to-many dependency between objects, so that when one object changes state, all its dependents are notified and updated automatically (e.g., using hooks).
|
||||
- **Strategy Pattern:** Define a family of algorithms, encapsulate each one, and make them interchangeable (e.g., customizable behavior through user options).
|
||||
- ### Recommended Approaches for Common Tasks
|
||||
- **Configuration Management:** Use `defcustom` for user-configurable options. Provide default values and documentation.
|
||||
- **UI Creation:** Use `widget` for creating interactive UI elements.
|
||||
- **Asynchronous Operations:** Leverage `timer` and `process` for non-blocking tasks.
|
||||
- **Data Storage:** Consider using SQLite via `sqlite.el` for persistent data storage.
|
||||
- ### Anti-patterns and Code Smells
|
||||
- **Global State Mutation:** Minimize use of global variables. If necessary, use `defvar` with caution.
|
||||
- **Deeply Nested Conditionals:** Refactor complex logic into smaller, more readable functions.
|
||||
- **Magic Numbers/Strings:** Define constants for frequently used values.
|
||||
- **Duplicated Code:** Extract common logic into reusable functions or macros.
|
||||
- **Ignoring Errors:** Always handle errors and exceptions gracefully.
|
||||
- ### State Management
|
||||
- Prefer lexical scoping with `lexical-binding: t` to create closures and manage state within functions.
|
||||
- Use `cl-letf` to temporarily redefine functions for testing or customization.
|
||||
- Utilize property lists or hash tables to associate state with buffers or other objects.
|
||||
- ### Error Handling
|
||||
- Use `condition-case` to handle exceptions and prevent crashes.
|
||||
- Provide informative error messages to users.
|
||||
- Log errors to a file or the `*Messages*` buffer for debugging.
|
||||
- Always clean up resources (e.g., timers, processes) in the `finally` clause of `condition-case`.
|
||||
- Example:
|
||||
lisp
|
||||
(condition-case err
|
||||
(progn
|
||||
;; Code that might raise an error
|
||||
(do-something))
|
||||
(error
|
||||
(message "An error occurred: %s" err))
|
||||
(finally
|
||||
;; Clean up resources
|
||||
(cleanup)))
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
- ## Performance Considerations
|
||||
- ### Optimization Techniques
|
||||
- **Profiling:** Use `profiler.el` or `elp.el` to identify performance bottlenecks.
|
||||
- **Byte Compilation:** Always byte-compile your Emacs Lisp code using `byte-compile-file`.
|
||||
- **Caching:** Cache frequently accessed data to reduce computation time.
|
||||
- **Lazy Loading:** Use `autoload` for functions that are not immediately needed.
|
||||
- **Tail Recursion:** Convert recursive functions to tail-recursive form to avoid stack overflow errors.
|
||||
- **StringBuilder:** Utilize `insert` for building large strings instead of repeated concatenation.
|
||||
- ### Memory Management
|
||||
- Minimize the creation of temporary objects.
|
||||
- Reuse existing data structures when possible.
|
||||
- Be mindful of garbage collection overhead; avoid creating excessive garbage.
|
||||
- Use weak references where possible, with libraries such as `weak-ref` to avoid memory leaks.
|
||||
- ### Rendering Optimization
|
||||
- Minimize the number of buffer updates.
|
||||
- Use overlays efficiently to avoid performance degradation.
|
||||
- Batch updates when possible.
|
||||
- ### Bundle Size Optimization
|
||||
- Remove unnecessary dependencies.
|
||||
- Use code minification tools to reduce the size of your Emacs Lisp files.
|
||||
- Compress images and other assets.
|
||||
- ### Lazy Loading
|
||||
- Use `autoload` for functions and libraries that are not immediately required.
|
||||
- Load dependencies on demand rather than at startup.
|
||||
- Provide hooks for users to customize which features are loaded.
|
||||
### 1.1 File Headers
|
||||
|
||||
- ## Security Best Practices
|
||||
- ### Common Vulnerabilities
|
||||
- **Code Injection:** Prevent execution of untrusted code.
|
||||
- **Cross-Site Scripting (XSS):** Sanitize user input to prevent malicious scripts from being injected into UI elements.
|
||||
- **Denial-of-Service (DoS):** Limit resource consumption to prevent attacks that overwhelm the system.
|
||||
- **Path Traversal:** Validate file paths to prevent access to unauthorized files.
|
||||
- ### Input Validation
|
||||
- Sanitize all user input to prevent code injection and XSS attacks.
|
||||
- Validate file paths to prevent path traversal vulnerabilities.
|
||||
- Use regular expressions to enforce input formats.
|
||||
- ### Authentication and Authorization
|
||||
- Use secure authentication mechanisms such as OAuth or API keys.
|
||||
- Implement authorization checks to ensure that users only have access to resources they are authorized to access.
|
||||
- Store credentials securely using the Emacs password manager or a dedicated secrets store.
|
||||
- ### Data Protection
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use secure communication protocols such as HTTPS.
|
||||
- Protect against data breaches by implementing appropriate access controls.
|
||||
- ### Secure API Communication
|
||||
- Use HTTPS for all API communication.
|
||||
- Validate API responses to prevent data injection attacks.
|
||||
- Implement rate limiting to prevent abuse.
|
||||
Every Emacs Lisp file **must** start with a standard header, including `lexical-binding` and a clear description.
|
||||
|
||||
- ## Testing Approaches
|
||||
- ### Unit Testing
|
||||
- Use ERT or Buttercup to write unit tests for your Emacs Lisp code.
|
||||
- Test individual functions and components in isolation.
|
||||
- Mock external dependencies to create a predictable testing environment.
|
||||
- ### Integration Testing
|
||||
- Test the interaction between different components of your Emacs Lisp application.
|
||||
- Verify that data flows correctly between components.
|
||||
- Ensure that your application integrates properly with Emacs itself.
|
||||
- ### End-to-end Testing
|
||||
- Use Director or similar tools to automate end-to-end tests.
|
||||
- Simulate user interactions and verify that the application behaves as expected.
|
||||
- Test the entire application from the user's perspective.
|
||||
- ### Test Organization
|
||||
- Organize your tests into separate files or directories.
|
||||
- Use descriptive names for your test cases.
|
||||
- Group related tests together.
|
||||
- Provide a clear and concise test report.
|
||||
- ### Mocking and Stubbing
|
||||
- Use `cl-letf` or similar techniques to mock external dependencies.
|
||||
- Create stubs for functions that are difficult or impossible to test directly.
|
||||
- Verify that mocked functions are called with the correct arguments.
|
||||
❌ BAD:
|
||||
```emacs-lisp
|
||||
;; my-feature.el
|
||||
(defun my-feature-do-something () ...)
|
||||
```
|
||||
|
||||
- ## Common Pitfalls and Gotchas
|
||||
- ### Frequent Mistakes
|
||||
- Forgetting to byte-compile Emacs Lisp code.
|
||||
- Using global variables excessively.
|
||||
- Ignoring error conditions.
|
||||
- Writing overly complex functions.
|
||||
- Failing to document code properly.
|
||||
- Not using lexical binding.
|
||||
- ### Edge Cases
|
||||
- Handling international characters correctly.
|
||||
- Dealing with different Emacs versions and platforms.
|
||||
- Managing asynchronous operations and timers.
|
||||
- Ensuring compatibility with other packages.
|
||||
- Testing in various Emacs configurations (e.g., `-Q` for no init file).
|
||||
- ### Version-Specific Issues
|
||||
- Be aware of API changes between Emacs versions.
|
||||
- Use conditional compilation to support multiple versions of Emacs.
|
||||
- Test your code on different Emacs versions to ensure compatibility.
|
||||
- ### Compatibility Concerns
|
||||
- Avoid using deprecated functions and features.
|
||||
- Test your code with different Emacs configurations to identify compatibility issues.
|
||||
- Provide a mechanism for users to disable or uninstall your package if necessary.
|
||||
- ### Debugging Strategies
|
||||
- Use `edebug` to step through your code and inspect variables.
|
||||
- Print debugging messages to the `*Messages*` buffer.
|
||||
- Use `trace` to monitor function calls.
|
||||
- Enable `debug-on-error` to catch exceptions.
|
||||
- Check the Emacs error log for clues.
|
||||
✅ GOOD:
|
||||
```emacs-lisp
|
||||
;;; my-feature.el --- A short description of my-feature -*- lexical-binding: t; -*-
|
||||
;;
|
||||
;; Copyright (C) 2025 Your Name
|
||||
;; Author: Your Name <your.email@example.com>
|
||||
;; Keywords: convenience, tools
|
||||
;;
|
||||
;;; Commentary:
|
||||
;; This library provides functions for doing X, Y, and Z.
|
||||
;;
|
||||
;;; Code:
|
||||
|
||||
- ## Tooling and Environment
|
||||
- ### Recommended Development Tools
|
||||
- **Emacs:** The best tool for developing Emacs Lisp code.
|
||||
- **ERT/Buttercup:** Testing frameworks.
|
||||
- **Flycheck:** Real-time syntax checking and linting.
|
||||
- **Edebug:** Interactive debugger.
|
||||
- **Profiler.el/ELP:** Profiling tools.
|
||||
- **Counsel/Ivy/Helm:** Completion frameworks for improved navigation.
|
||||
- **Magit:** Git integration.
|
||||
- ### Build Configuration
|
||||
- Use a `Makefile` or similar build tool to automate common tasks such as byte-compilation, testing, and documentation generation.
|
||||
- Define dependencies explicitly in your build configuration.
|
||||
- Use version control to track changes to your build configuration.
|
||||
- ### Linting and Formatting
|
||||
- Use `flycheck` with `package-lint` and `elsa` for static code analysis.
|
||||
- Enforce consistent code formatting using `aggressive-indent-mode` or similar tools.
|
||||
- Configure your editor to automatically format code on save.
|
||||
- ### Deployment
|
||||
- Package your Emacs Lisp code into a `.el` file.
|
||||
- Distribute your package via MELPA or a similar repository.
|
||||
- Provide clear instructions on how to install and configure your package.
|
||||
- ### CI/CD Integration
|
||||
- Use GitHub Actions, Travis CI, or similar tools to automate testing and deployment.
|
||||
- Run tests on every commit to ensure code quality.
|
||||
- Automatically deploy your package to MELPA on release.
|
||||
(require 'cl-lib) ; Example dependency
|
||||
|
||||
- ## Best Practices Summary
|
||||
- Always use lexical binding: `;; -*- lexical-binding: t; -*-`.
|
||||
- Prefix all global symbols with a unique project prefix to avoid namespace collisions.
|
||||
- Write clear and concise documentation for all functions and variables using docstrings.
|
||||
- Use `defcustom` for user-configurable options.
|
||||
- Handle errors gracefully using `condition-case`.
|
||||
- Byte-compile your Emacs Lisp code before deploying.
|
||||
- Write unit tests for your code using ERT or Buttercup.
|
||||
- Follow the Emacs Lisp Style Guide.
|
||||
- Leverage the power of Emacs' interactive development environment for real-time feedback.
|
||||
(provide 'my-feature)
|
||||
;;; my-feature.el ends here
|
||||
```
|
||||
|
||||
- @file https://raw.githubusercontent.com/bbatsov/emacs-lisp-style-guide/master/emacs-lisp-style-guide.md
|
||||
- @file https://raw.githubusercontent.com/emacs-tw/awesome-elisp/master/README.md
|
||||
### 1.2 Naming Conventions
|
||||
|
||||
All global symbols (functions, variables, constants) **must** be prefixed with a short, hyphen-separated package name. Use a double hyphen (`--`) for internal, non-public symbols.
|
||||
|
||||
❌ BAD:
|
||||
```emacs-lisp
|
||||
(defvar foo-list nil "A list of foos.")
|
||||
(defun do-something () ...)
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```emacs-lisp
|
||||
(defvar myproj-foo-list nil "A list of foos for My Project.")
|
||||
(defun myproj-do-something (arg) ...)
|
||||
(defun myproj--internal-helper (arg) ...) ; Internal function
|
||||
```
|
||||
|
||||
### 1.3 `init.el` Configuration
|
||||
|
||||
Your `init.el` **must** be a single file, primarily using `use-package`. If you prefer a literate Org file, **always** tangle it to `init.el`; **never** use `org-babel-load-file`.
|
||||
|
||||
❌ BAD:
|
||||
```emacs-lisp
|
||||
;; init.el
|
||||
(org-babel-load-file "~/.emacs.d/init.org")
|
||||
(load-file "~/.emacs.d/my-custom-settings.el")
|
||||
(setq global-setting t) ; Scattered settings
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```emacs-lisp
|
||||
;; init.el (or tangled from init.org)
|
||||
;; -*- lexical-binding: t; -*-
|
||||
|
||||
;; Package manager setup (e.g., straight.el or elpaca)
|
||||
(setq package-enable-at-startup nil)
|
||||
(unless (package-installed-p 'use-package)
|
||||
(package-refresh-contents)
|
||||
(package-install 'use-package))
|
||||
(eval-when-compile (require 'use-package))
|
||||
(require 'use-package-ensure) ; For :ensure t
|
||||
|
||||
;; Global Emacs settings (use the 'emacs' pseudo-feature)
|
||||
(use-package emacs
|
||||
:init
|
||||
(setq custom-file (expand-file-name "custom.el" user-emacs-directory))
|
||||
(load custom-file 'noerror 'nomessage)
|
||||
(setq-default fill-column 80
|
||||
indent-tabs-mode nil
|
||||
tab-width 2)
|
||||
:config
|
||||
(global-display-line-numbers-mode))
|
||||
|
||||
;; Example package configuration
|
||||
(use-package my-package
|
||||
:ensure t
|
||||
:defer t ; Defer loading until needed
|
||||
:bind (("C-c m" . my-package-command))
|
||||
:config
|
||||
(setq my-package-setting t))
|
||||
```
|
||||
|
||||
### 1.4 Docstrings and Comments
|
||||
|
||||
Every public function and variable **must** have a docstring. The first line **must** be a complete sentence. Use comments to explain complex logic, not obvious code.
|
||||
|
||||
❌ BAD:
|
||||
```emacs-lisp
|
||||
(defun myproj-add (a b) (+ a b)) ; adds two numbers
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```emacs-lisp
|
||||
(defun myproj-add (a b)
|
||||
"Return the sum of A and B.
|
||||
This function performs basic arithmetic addition."
|
||||
(+ a b))
|
||||
|
||||
(defvar myproj-cache-size 100
|
||||
"Maximum number of items to store in the project cache.")
|
||||
|
||||
;; This complex regex matches URLs with optional query parameters.
|
||||
;; It ensures we capture the base URL separately.
|
||||
(let ((url-regex "^\\(https?://[^/?#]+\\)\\(?:[/?#].*\\)?$"))
|
||||
...)
|
||||
```
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1 Lexical Binding
|
||||
|
||||
**Always** enable lexical binding. It prevents subtle bugs related to dynamic scope and allows for proper closures. Add `-*- lexical-binding: t; -*-` to your file header.
|
||||
|
||||
### 2.2 Variable Declarations
|
||||
|
||||
Use `let*` for sequential binding and align variables for readability. Avoid redundant `nil` initializations.
|
||||
|
||||
❌ BAD:
|
||||
```emacs-lisp
|
||||
(let ((foo '()) (bar nil) baz))
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```emacs-lisp
|
||||
(let* ((myproj-foo-list nil) ; A list of processed items
|
||||
(myproj-bar-flag nil) ; A boolean flag indicating status
|
||||
myproj-temp-var) ; A scratch variable for intermediate calculations
|
||||
...)
|
||||
```
|
||||
|
||||
### 2.3 Keybinding Conventions
|
||||
|
||||
**Never** bind `C-c <letter>` (e.g., `C-c a`); these are reserved for users. Use `C-c <non-letter>` for major mode commands. **Never** bind `C-h` after any prefix.
|
||||
|
||||
❌ BAD:
|
||||
```emacs-lisp
|
||||
(global-set-key (kbd "C-c a") 'myproj-action)
|
||||
(define-key my-mode-map (kbd "C-c h") 'myproj-help)
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```emacs-lisp
|
||||
(global-set-key (kbd "C-c @") 'myproj-global-action) ; C-c followed by a non-letter
|
||||
(define-key my-mode-map (kbd "C-c ,") 'myproj-mode-action)
|
||||
```
|
||||
|
||||
### 2.4 Do Not Redefine Emacs Primitives
|
||||
|
||||
**Never** redefine or alias standard Emacs Lisp primitives (e.g., `copy-list`, `cadr`). This leads to unpredictable behavior and breaks other packages.
|
||||
|
||||
❌ BAD:
|
||||
```emacs-lisp
|
||||
(defun copy-list (list) (cl-copy-list list)) ; Redefining a built-in
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```emacs-lisp
|
||||
;; Use the standard primitive directly or define your own with a proper prefix.
|
||||
(myproj-custom-copy-list my-list)
|
||||
```
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1 Byte Compilation
|
||||
|
||||
**Always** byte-compile your Emacs Lisp files. Use `auto-compile` to automate this on save.
|
||||
|
||||
❌ BAD:
|
||||
```emacs-lisp
|
||||
;; Only distribute .el files
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```emacs-lisp
|
||||
;; Ensure .elc files are generated and kept up-to-date
|
||||
(use-package auto-compile
|
||||
:ensure t
|
||||
:config
|
||||
(auto-compile-mode 1))
|
||||
```
|
||||
|
||||
### 3.2 `init.el` Load Time
|
||||
|
||||
Keep your `init.el` lean. Defer package loading with `use-package`'s `:defer`, `:demand`, `:bind`, `:hook` keywords.
|
||||
|
||||
❌ BAD:
|
||||
```emacs-lisp
|
||||
(require 'heavy-package) ; Loads immediately
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```emacs-lisp
|
||||
(use-package heavy-package
|
||||
:ensure t
|
||||
:defer t ; Only load when 'heavy-package' functionality is called
|
||||
:config
|
||||
(setq heavy-package-setting t))
|
||||
```
|
||||
|
||||
## 4. Common Pitfalls and Gotchas
|
||||
|
||||
### 4.1 Mark Management
|
||||
|
||||
**Never** set the mark in your Lisp code unless you are writing a user-facing command specifically designed to manipulate the mark ring. Functions like `beginning-of-buffer` or `replace-string` set the mark; use lower-level alternatives for programmatic movement/replacement.
|
||||
|
||||
❌ BAD:
|
||||
```emacs-lisp
|
||||
(defun myproj-process-buffer ()
|
||||
(interactive)
|
||||
(beginning-of-buffer) ; Sets the mark
|
||||
(replace-string "old" "new")) ; Sets the mark
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```emacs-lisp
|
||||
(defun myproj-process-buffer ()
|
||||
"Process the current buffer, replacing 'old' with 'new'."
|
||||
(interactive)
|
||||
(save-excursion ; Preserve point and mark
|
||||
(goto-char (point-min))
|
||||
(while (re-search-forward "old" nil t)
|
||||
(replace-match "new"))))
|
||||
```
|
||||
|
||||
### 4.2 Buffer Navigation
|
||||
|
||||
**Always** use `forward-line` for programmatic line movement. `next-line` and `previous-line` are unreliable in Lisp code as they depend on visual line boundaries.
|
||||
|
||||
❌ BAD:
|
||||
```emacs-lisp
|
||||
(next-line)
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```emacs-lisp
|
||||
(forward-line 1)
|
||||
```
|
||||
|
||||
### 4.3 Messaging and Errors
|
||||
|
||||
Use `message` for user feedback in the echo area. Use `error` or `signal` for unrecoverable conditions.
|
||||
|
||||
❌ BAD:
|
||||
```emacs-lisp
|
||||
(princ "Something happened!")
|
||||
(if (not condition) (throw 'error "Failed!"))
|
||||
```
|
||||
|
||||
✅ GOOD:
|
||||
```emacs-lisp
|
||||
(message "My project: Something happened!")
|
||||
(unless condition
|
||||
(error "My project: Condition not met, cannot proceed."))
|
||||
```
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1 Unit Testing with ERT
|
||||
|
||||
**Always** write unit tests for your Emacs Lisp libraries using the built-in Emacs Lisp Regression Test (ERT) framework.
|
||||
|
||||
```emacs-lisp
|
||||
;; my-feature-test.el
|
||||
;;; my-feature-test.el --- Tests for my-feature -*- lexical-binding: t; -*-
|
||||
;;; Code:
|
||||
|
||||
(require 'ert)
|
||||
(require 'my-feature)
|
||||
|
||||
(ert-deftest myproj-add-basic-test ()
|
||||
"Test basic addition with `myproj-add`."
|
||||
(should (= (myproj-add 1 2) 3)))
|
||||
|
||||
(provide 'my-feature-test)
|
||||
;;; my-feature-test.el ends here
|
||||
```
|
||||
|
||||
### 5.2 Linting and Static Analysis
|
||||
|
||||
**Always** use `flycheck` with `flycheck-package` to catch common errors, naming violations, and documentation issues early.
|
||||
|
||||
```emacs-lisp
|
||||
;; Ensure flycheck is enabled in your init.el
|
||||
(use-package flycheck
|
||||
:ensure t
|
||||
:init (global-flycheck-mode))
|
||||
|
||||
(use-package flycheck-package
|
||||
:ensure t
|
||||
:after flycheck
|
||||
:config
|
||||
(add-hook 'flycheck-mode-hook 'flycheck-package-setup))
|
||||
```
|
||||
|
||||
### 5.3 Interactive Debugging
|
||||
|
||||
Leverage Emacs's built-in `edebug` for interactive debugging. Use `C-u C-M-x` on a `defun` to instrument a function, then call it to step through.
|
||||
|
||||
```emacs-lisp
|
||||
;; Place point on 'defun', then C-u C-M-x to instrument
|
||||
(defun myproj-debug-example (arg)
|
||||
"An example function to debug."
|
||||
(let ((result (* arg 2)))
|
||||
(message "Intermediate result: %s" result)
|
||||
(+ result 10)))
|
||||
|
||||
(myproj-debug-example 5) ; Call this after instrumenting to start edebug
|
||||
```
|
||||
Reference in New Issue
Block a user