Emacs is designed with programming in mind, it supports languages like C, Python, and Lisp natively, offering advanced features such as syntax highlighting, customizable coding styles, and real-time error detection. Its built-in Lisp interpreter makes Emacs highly adaptable, allowing users to shape the editor to fit specific workflows or create entirely new functionalities.
Its rich ecosystem of extensions ensures it remains relevant across diverse fields, from academic writing to system programming, while its customizable interface enables users to optimize their environment for maximum productivity.
It continues to be a reliable choice for those who value control and versatility, proving that a tool designed decades ago can still meet the demands of today’s fast-evolving tech landscape.
Why Choose Emacs?
Emacs is more than just a text editor—it's a powerful, extensible platform for programming, writing, and customization. Unlike modern editors like VS Code or IntelliJ IDEA, Emacs thrives on flexibility and programmability. It allows users to deeply tailor their workflow, turning it into an environment suited for their exact needs. Whether you are coding in C, managing large projects, or even writing novels, Emacs can adapt to your requirements.
For new users, this might seem overwhelming, but once you understand its principles, Emacs becomes a tool that grows with you. This guide aims to help you set up a streamlined Emacs environment, from basic configurations to advanced integrations, ensuring you're productive every step of the way.
Table of Contents
- Creating init.el
- Ensuring the init.el Directory is Correct
- Basic Configuration for Emacs
- Adding the Linux Kernel Coding Style Patterns
- Installing and Configuring the MELPA Package Manager
- Installing the Clang LSP Server
- Enhancing C Development with Company, Projectile, Treemacs, and Magit
- Adding GNU Global, GTags, and Helm-Gtags
- Using YASnippet for Code Templates
- Configuring Semantic for Context-Aware Navigation
- Practical Workflow Example for Development
- Cheat Sheets
- References for Plugins
- Additional Learning Resources
Steps:
Creating init.el
- Open Emacs on your system.
- Use the command C-x C-f (press Ctrl and x, then Ctrl and f), which opens a file for editing.
- Type the file path ~/.emacs.d/init.el to create or edit your Emacs configuration file and press Enter.
- Add your desired configurations to the buffer. Once done, save the changes with C-x C-s (press Ctrl and x, then Ctrl and s).
Ensuring the init.el Directory is Correct
To ensure that the Emacs configuration always references the correct directory for the init.el file, add the following snippet to the top of your init.el file:
(setq user-emacs-directory "~/.emacs.d/")
This explicitly sets the user-emacs-directory variable to ~/.emacs.d/, ensuring that Emacs uses the specified path for its initialization file and related configurations. This approach avoids potential issues where Emacs might reference a different directory due to environment-specific settings.
Basic Configuration for Emacs
Here’s a simple and practical Emacs setup, explained clearly to help you understand its purpose. This configuration enhances usability, simplifies the interface, and ensures an efficient coding experience.
This line consolidates all backup files into a single directory (~/.saves). It keeps your projects clean and avoids cluttering your workspace.
(setq backup-directory-alist `(("." . "~/.saves")))
To reduce distractions, this removes unnecessary interface elements like the toolbar, scroll bar, tooltips, and menu bar. A cleaner interface helps you focus on coding without visual noise.
(tool-bar-mode -1) (scroll-bar-mode -1) (tooltip-mode -1) (menu-bar-mode -1)
This setup disables the Emacs startup screen, removes the default message in the *scratch* buffer, and silences the system bell. It creates a distraction-free environment right from the start.
(setq inhibit-startup-screen t initial-scratch-message nil ring-bell-function 'ignore)
The cursor is set to a box style for better visibility, and the blinking effect is disabled. Automatic pairing of parentheses and indentation are enabled, making coding smoother and faster.
(setq user-emacs-directory "~/.emacs.d/")
Line numbers are displayed globally for easier navigation, and the column number is shown in the status bar to keep track of cursor position in each line.
(setq backup-directory-alist `(("." . "~/.saves")))
This configuration adds a clean and concise time display in the mode line, showing the day, date, and time in 24-hour format. The load average is excluded to keep the interface minimal.
(tool-bar-mode -1) (scroll-bar-mode -1) (tooltip-mode -1) (menu-bar-mode -1)
Selections automatically replace highlighted text when typing, and clipboard integration ensures seamless copying and pasting between Emacs and other applications.
(setq inhibit-startup-screen t initial-scratch-message nil ring-bell-function 'ignore)
All encoding is set to UTF-8, ensuring compatibility with modern text formats and avoiding encoding issues, particularly when working with international text or source code.
(setq cursor-type 'box blink-cursor-mode nil electric-pair-mode 1 electric-indent-mode 1)
Syntax highlighting is enabled globally with global-font-lock-mode. Long lines are wrapped naturally with visual-line-mode. Parentheses are highlighted when the cursor is near them, and recently opened files are tracked for quick access.
(global-display-line-numbers-mode t) (column-number-mode t)
The tangotango theme provides a visually appealing color scheme. The font is set to "Consolas" with bold weight and size 15.2pt for better readability during long coding sessions.
(setq display-time-format "%a %b %d %R" display-time-interval 60 display-time-default-load-average nil) (display-time-mode 1)
Note: Remember, we are using Emacs Lisp (Elisp), a functional programming language, to configure Emacs. This is a huge advantage, as it allows for highly flexible, programmable customization. The ability to write logic in a powerful Lisp dialect makes Emacs not just an editor, but a platform for personalized workflows.
Adding the Linux Kernel Coding Style Patterns
The configuration provided below sets up Emacs to strictly adhere to the Linux kernel coding style, emphasizing 8-character tabs, K&R brace placement, and clear readability. It includes a custom alignment function for argument lists, automatic detection of kernel-related files (e.g., files with Kbuild, Kconfig, or kernel headers), and applies the appropriate style automatically. This ensures consistency and simplifies kernel code editing in Emacs.
The linux-kernel-coding-style/setup function configures Emacs for kernel-specific settings like indent-tabs-mode, tab-width and c-basic-offset to 8, while the linux-kernel-coding-style/c-lineup-arglist-tabs-only function aligns argument lists using tabs, maintaining compliance with kernel guidelines. These hooks automatically apply the style to c-mode when editing Linux kernel files, improving productivity and adherence to coding standards.
(setq select-enable-primary nil select-enable-clipboard t) (delete-selection-mode 1)
Add this configuration to your Emacs initialization file (init.el). Emacs will now automatically detect Linux kernel files and apply the proper coding style, saving you time and ensuring compliance with the kernel's coding standards.
Installing and Configuring the MELPA Package Manager
MELPA makes it easy to install additional packages in Emacs.
Steps:
- Add MELPA to Emacs:
(setq user-emacs-directory "~/.emacs.d/")
- Automatically install packages if they're not present:
(setq backup-directory-alist `(("." . "~/.saves")))
After making changes to your init.el file or adding new configurations, you can refresh Emacs without closing and reopening:
-
Reload the init.el File:
- Press M-x (Alt x), type eval-buffer, and press Enter while in your init.el buffer.
- Alternatively, use the shortcut C-x C-e at the end of the code block to evaluate it.
-
Manually Evaluate Code:
- Select the code snippet you want to reload, press M-x, type eval-region, and press Enter.
This allows you to immediately apply changes to your Emacs configuration without restart
Installing the Clang LSP Server
The Language Server Protocol (LSP) provides advanced features like auto-completion and real-time error checking.
Necessary Requirements
Windows
-
LLVM/Clang:
- Download the LLVM installer from the official website: LLVM Releases
- During installation, make sure to add LLVM to the system PATH.
Linux
- Debian/Ubuntu:
(tool-bar-mode -1) (scroll-bar-mode -1) (tooltip-mode -1) (menu-bar-mode -1)
- Fedora:
(setq inhibit-startup-screen t initial-scratch-message nil ring-bell-function 'ignore)
FreeBSD
- Install clangd:
(setq cursor-type 'box blink-cursor-mode nil electric-pair-mode 1 electric-indent-mode 1)
Steps:
- Install lsp-mode and company-mode:
(global-display-line-numbers-mode t) (column-number-mode t)
- Configure the path to clangd if necessary:
(setq display-time-format "%a %b %d %R" display-time-interval 60 display-time-default-load-average nil) (display-time-mode 1)
- Optional: Set up advanced syntax highlighting with lsp-ui:
(setq select-enable-primary nil select-enable-clipboard t) (delete-selection-mode 1)
What is LSP and Why Use It?
The Language Server Protocol (LSP) bridges the gap between editors and programming languages, providing features like auto-completion, error checking, and code navigation. This is particularly useful for C/C development, where managing headers, debugging, and navigating large codebases can be challenging.
By setting up LSP in Emacs, you gain the ability to:
- View real-time syntax errors as you type.
- Jump to function or variable definitions instantly.
- Access intelligent suggestions for completing code.
This makes Emacs competitive with modern IDEs while retaining its lightweight and customizable nature.
Company, Projectile, Treemacs, and Magit
Enhancing your Emacs setup for C development involves integrating Company, Projectile, Treemacs, and Magit. Company provides auto-completion for C programming, enabling real-time suggestions for functions, variables, and keywords, making coding faster and more efficient. By configuring it to use company-clang, you ensure robust support tailored to C development.
Projectile streamlines project management by allowing quick navigation, file discovery, and project compilation. It pairs seamlessly with Treemacs, which provides a visual, tree-based representation of your project structure, helping you locate and manage files intuitively. Finally, Magit is an advanced interface for Git, providing powerful tools for version control directly within Emacs.
With shortcuts like C-x g, you can perform operations such as commits, branching, and merging interactively, enhancing your workflow and productivity. Here’s the complete configuration to set up these tools in your Emacs environment:
(setq user-emacs-directory "~/.emacs.d/")
Practical Workflow Example
Let’s see how you can combine these tools in a real-world scenario:
-
Open a Project:
- Use C-c p f to quickly find a file within your project directory using Projectile.
-
Navigate Files Visually:
- Open Treemacs with M-0, and use the arrow keys to browse your project structure. Double-click a file to open it.
-
Git Workflow with Magit:
- Stage changes: Open Magit with C-x g, press s to stage files.
- Commit: Press c c to commit changes with a message.
- Push: Use P to push changes to your remote repository.
-
Code Completion:
- While editing a .c file, type a function name partially and use company-mode suggestions by pressing TAB.
Enhancements to Add to the Article
-
GNU Global and GTags Configuration:
- Add instructions for setting up GNU Global and GTags for code navigation:
(setq user-emacs-directory "~/.emacs.d/")
-
Helm-Gtags Integration:
- Include configuration for helm-gtags to enhance project navigation:
(setq backup-directory-alist `(("." . "~/.saves")))
-
Yasnippet Templates:
- Include YASnippet for code templates:
(tool-bar-mode -1) (scroll-bar-mode -1) (tooltip-mode -1) (menu-bar-mode -1)
-
Semantic Configuration:
- Add Semantic for context-aware code completion and parsing:
(setq inhibit-startup-screen t initial-scratch-message nil ring-bell-function 'ignore)
-
Additional Code Navigation Features:
- Mention semantic-symref for reference gathering:
(setq cursor-type 'box blink-cursor-mode nil electric-pair-mode 1 electric-indent-mode 1)
These additions enhance the existing content by providing support for advanced navigation, project management, and automation tools in Emacs, aligning the article with best practices for modern C/C development.
Cheat Sheets
References for Plugins
- lsp-mode: Language Server Protocol support for auto-completion and error checking. GitHub
- company-mode: Context-aware autocompletion. GitHub
- lsp-ui: UI enhancements for lsp-mode. GitHub
- projectile: Project navigation and management. GitHub
- treemacs: Tree-based file explorer. GitHub
- magit: Git interface for Emacs. GitHub
- ggtags: GNU Global integration for code navigation. GitHub
- helm-gtags: Navigation with GNU Global and Helm. GitHub
- yasnippet: Snippet management for reusable code. GitHub
- semantic: Advanced code parsing and navigation. GNU CEDET
Additional Learning Resources
- Emacs for Beginners: A beginner-friendly guide to setting up and using Emacs. Link
- Introduction to Emacs Lisp: Learn how to customize Emacs using Lisp. Link
- Linux Kernel Coding Style: Official documentation on kernel coding standards. Link
- Setting Up Emacs for C Development: A practical guide to configure Emacs for C/C programming. Link
The above is the detailed content of C Development with GNU Emacs. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

People who study Python transfer to C The most direct confusion is: Why can't you write like Python? Because C, although the syntax is more complex, provides underlying control capabilities and performance advantages. 1. In terms of syntax structure, C uses curly braces {} instead of indentation to organize code blocks, and variable types must be explicitly declared; 2. In terms of type system and memory management, C does not have an automatic garbage collection mechanism, and needs to manually manage memory and pay attention to releasing resources. RAII technology can assist resource management; 3. In functions and class definitions, C needs to explicitly access modifiers, constructors and destructors, and supports advanced functions such as operator overloading; 4. In terms of standard libraries, STL provides powerful containers and algorithms, but needs to adapt to generic programming ideas; 5

C destructorsarespecialmemberfunctionsthatautomaticallyreleaseresourceswhenanobjectgoesoutofscopeorisdeleted.1)Theyarecrucialformanagingmemory,filehandles,andnetworkconnections.2)Beginnersoftenneglectdefiningdestructorsfordynamicmemory,leadingtomemo

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

C STL is a set of general template classes and functions, including core components such as containers, algorithms, and iterators. Containers such as vector, list, map, and set are used to store data. Vector supports random access, which is suitable for frequent reading; list insertion and deletion are efficient but accessed slowly; map and set are based on red and black trees, and automatic sorting is suitable for fast searches. Algorithms such as sort, find, copy, transform, and accumulate are commonly used to encapsulate them, and they act on the iterator range of the container. The iterator acts as a bridge connecting containers to algorithms, supporting traversal and accessing elements. Other components include function objects, adapters, allocators, which are used to customize logic, change behavior, and memory management. STL simplifies C

As a beginner graphical programming for C programmers, OpenGL is a good choice. First, you need to build a development environment, use GLFW or SDL to create a window, load the function pointer with GLEW or glad, and correctly set the context version such as 3.3. Secondly, understand OpenGL's state machine model and master the core drawing process: create and compile shaders, link programs, upload vertex data (VBO), configure attribute pointers (VAO) and call drawing functions. In addition, you must be familiar with debugging techniques, check the shader compilation and program link status, enable the vertex attribute array, set the screen clear color, etc. Recommended learning resources include LearnOpenGL, OpenGLRedBook and YouTube tutorial series. Master the above

In C, cin and cout are used for console input and output. 1. Use cout to read the input, pay attention to type matching problems, and stop encountering spaces; 3. Use getline(cin, str) when reading strings containing spaces; 4. When using cin and getline, you need to clean the remaining characters in the buffer; 5. When entering incorrectly, you need to call cin.clear() and cin.ignore() to deal with exception status. Master these key points and write stable console programs.

STL (Standard Template Library) is an important part of the C standard library, including three core components: container, iterator and algorithm. 1. Containers such as vector, map, and set are used to store data; 2. Iterators are used to access container elements; 3. Algorithms such as sort and find are used to operate data. When selecting a container, vector is suitable for dynamic arrays, list is suitable for frequent insertion and deletion, deque supports double-ended quick operation, map/unordered_map is used for key-value pair search, and set/unordered_set is used for deduplication. When using the algorithm, the header file should be included, and iterators and lambda expressions should be combined. Be careful to avoid failure iterators, update iterators when deleting, and not modify m

Learn C You should start from the following points when playing games: 1. Proficient in basic grammar but do not need to go deep into it, master the basic contents of variable definition, looping, condition judgment, functions, etc.; 2. Focus on mastering the use of STL containers such as vector, map, set, queue, and stack; 3. Learn fast input and output techniques, such as closing synchronous streams or using scanf and printf; 4. Use templates and macros to simplify code writing and improve efficiency; 5. Familiar with common details such as boundary conditions and initialization errors.
