Selective staging in Magit

As I mentioned in my Git For Writers book, there may be situations in which you want to only stage part of a file instead of committing the whole thing. I didn’t cover the process in detail because it is more of an advanced technique. However, if you use Magit, it’s much easier to do, and being more selective in your staging helps you write better commit messages.

Here’s a little map of what we’re going to cover in this article:

Basic file staging in Magit

This is the most basic way to stage changes in Magit.

In Emacs, run M-x magit-status or press C-x g (if you have the default keybinding). This opens the status buffer showing all your changes. You will see a single file or list of files depending on what you edited.

Navigate to an unstaged file and press s to stage it. Press u to unstage it.

This will stage all changes in that file. However, maybe you want to be more selective?

Staging parts of files (hunks)

When you have multiple changes in a single file, Magit breaks them into “hunks”—logical chunks of changes.

  1. Open the magit-status buffer
  2. Navigate to the file you want to partially stage
  3. Press TAB to expand and see the individual hunks
  4. Navigate to a specific hunk
  5. Press s to stage just that hunk (or u to unstage)

Staging individual lines

This is where Magit really shines. You can stage a hunk or even specific lines within a hunk:

  1. Navigate to the hunk containing the lines you want
  2. Press TAB to expand the hunk and see the individual lines
  3. Move your point to the specific line
  4. Press s to stage it

You can also use visual selection: select multiple lines with C-SPC  and  press s to stage the selection.

Selected lines as region of what I want to stage.

Commit changes as usual

Once you’ve staged exactly what you want:

  1. Press c to open the commit menu
  2. Press c again to create a commit
  3. Write your commit message
  4. Press C-c C-c to finalize the commit

Why this matters for writers

When working on a long document you might be editing multiple sections. For example, you might be cleaning the wording in a dialogue scene, then remember to jump over and fix some issues in another scene. So, toward the end of your session, you will have edits in different places, which can make it more difficult to write a terse commit message.

By selectively staging changes you can more easily go back through your work and analyze what you did.

1 Comment

Leave a Reply

Your email address will not be published.


*