Using Emacs, how could I indent/format a code segment in a TXT file?

editor, emacs

Solution

orgmode manages to do it by copying the code out to a temporary buffer where you edit & format it, and updating the changed text when you're done.

If switching to orgmode is an option, then you do it like this:

 #+BEGIN_SRC emacs-lisp
 (defun org-xor (a b)
    "Exclusive or."
    (if a (not b) b))
 #+END_SRC

and start and finish editing with `C-c '`.

Edit: Emacswiki has a list of multiple modes.

Problem

I am writing a document with Emacs. As you know, there are some code segments in the text file I am working with. Typically, when I open this file, emacs will get into text-mode automatically. And it works fine for me to edit the ordinary paragraphs. But for those code segments, how could I indent them into gnu or linux style just like what I could do in c-mode (by c-set-style && do Ctrl-Alt-\ in certain region)? BTW, actually, I could turn the buffer into c-mode by invoking M-x c-mode to do this, however, I think there should be much a graceful way to do this in text-mode.

Original source