Positions
*********

A position is the index of a character in the text of a buffer. More precisely, a position identifies the place between two characters (or before the first character, or after the last character), so we can speak of the character before or after a given position.  However, we often speak of the character ``at'' a position, meaning the character after that position.

Positions are usually represented as integers starting from 1, but can also be represented as markers---special objects that relocate automatically when text is inserted or deleted so they stay with the surrounding characters.  Functions that expect an argument to be a position (an integer), but accept a marker as a substitute, normally ignore the marker buffer.  Of course, markers used this way usually point to a position in the buffer that the function operates on, but that is entirely the programmer's responsibility.  See Markers.

See also the ``field'' feature (see Fields), which provides functions that are used by many cursor-motion commands.

Point
=====

Point is a special buffer position used by many editing commands, including the self-inserting typed characters and text insertion functions.  Other commands move point through the text to allow editing and insertion at different places.

Like other positions, point designates a place between two characters (or before the first character, or after the last character), rather than a particular character.  Usually terminals display the cursor over the character that immediately follows point; point is actually before the character on which the cursor sits.

The value of point is a number no less than 1, and no greater than the buffer size plus 1.  If narrowing is in effect (see Narrowing), then point is constrained to fall within the accessible portion of the buffer (possibly at one end of it).

Each buffer has its own value of point, which is independent of the value of point in other buffers.  Each window also has a value of point, which is independent of the value of point in other windows on the same buffer.  This is why point can have different values in various windows that display the same buffer.  When a buffer appears in only one window, the buffer's point and the window's point normally have the same value, so the distinction is rarely important.  See Window Point, for more details.

 -- Function: point
     This function returns the value of point in the current buffer, as an integer.

          (point)
               => 175

 -- Function: point-min
     This function returns the minimum accessible value of point in the current buffer.  This is normally 1, but if narrowing is in effect, it is the position of the start of the region that you narrowed to. (see Narrowing.)

 -- Function: point-max
     This function returns the maximum accessible value of point in the current buffer.  This is (1+ (buffer-size)), unless narrowing is in effect, in which case it is the position of the end of the region that you narrowed to.  (see Narrowing.)

 -- Function: buffer-end flag
     This function returns (point-max) if FLAG is greater than 0, (point-min) otherwise.  The argument FLAG must be a number.

 -- Function: buffer-size &optional buffer
     This function returns the total number of characters in the current buffer.  In the absence of any narrowing (see Narrowing), point-max returns a value one larger than this.

     If you specify a buffer, BUFFER, then the value is the size of BUFFER.

          (buffer-size)
               => 35

          (point-max)
               => 36

Motion
======

Motion functions change the value of point, either relative to the current value of point, relative to the beginning or end of the buffer, or relative to the edges of the selected window.  See Point.

Motion by Characters
--------------------

These functions move point based on a count of characters. goto-char is the fundamental primitive; the other functions use that.

 -- Command: goto-char position
     This function sets point in the current buffer to the value POSITION.  If POSITION is less than 1, it moves point to the beginning of the buffer.  If POSITION is greater than the length of the buffer, it moves point to the end.

     If narrowing is in effect, POSITION still counts from the beginning of the buffer, but point cannot go outside the accessible portion.  If POSITION is out of range, goto-char moves point to the beginning or the end of the accessible portion.

     When this function is called interactively, POSITION is the numeric prefix argument, if provided; otherwise it is read from the minibuffer.

     goto-char returns POSITION.

 -- Command: forward-char &optional count
     This function moves point COUNT characters forward, towards the end of the buffer (or backward, towards the beginning of the buffer, if COUNT is negative).  If the function attempts to move point past the beginning or end of the buffer (or the limits of the accessible portion, when narrowing is in effect), an error is signaled with error code beginning-of-buffer or end-of-buffer.

     In an interactive call, COUNT is the numeric prefix argument.

 -- Command: backward-char &optional count
     This function moves point COUNT characters backward, towards the beginning of the buffer (or forward, towards the end of the buffer, if COUNT is negative).  If the function attempts to move point past the beginning or end of the buffer (or the limits of the accessible portion, when narrowing is in effect), an error is signaled with error code beginning-of-buffer or end-of-buffer.

     In an interactive call, COUNT is the numeric prefix argument.

Motion by Words
---------------

These functions for parsing words use the syntax table to decide whether a given character is part of a word.  See Syntax Tables.

 -- Command: forward-word &optional count
     This function moves point forward COUNT words (or backward if COUNT is negative).  ``Moving one word'' means moving until point crosses a word-constituent character and then encounters a word-separator character.  However, this function cannot move point past the boundary of the accessible portion of the buffer, or across a field boundary (see Fields).  The most common case of a field boundary is the end of the prompt in the minibuffer.

     If it is possible to move COUNT words, without being stopped prematurely by the buffer boundary or a field boundary, the value is t.  Otherwise, the return value is nil and point stops at the buffer boundary or field boundary.

     If inhibit-field-text-motion is non-nil, this function ignores field boundaries.

     In an interactive call, COUNT is specified by the numeric prefix argument.  If COUNT is omitted or nil, it defaults to 1.

 -- Command: backward-word &optional count
     This function is just like forward-word, except that it moves backward until encountering the front of a word, rather than forward.

 -- Variable: words-include-escapes
     This variable affects the behavior of forward-word and everything that uses it.  If it is non-nil, then characters in the ``escape'' and ``character quote'' syntax classes count as part of words.  Otherwise, they do not.

 -- Variable: inhibit-field-text-motion
     If this variable is non-nil, certain motion functions including forward-word, forward-sentence, and forward-paragraph ignore field boundaries.

Motion to an End of the Buffer
------------------------------

To move point to the beginning of the buffer, write:

     (goto-char (point-min))

Likewise, to move to the end of the buffer, use:

     (goto-char (point-max))

Here are two commands that users use to do these things.  They are documented here to warn you not to use them in Lisp programs, because they set the mark and display messages in the echo area.

 -- Command: beginning-of-buffer &optional n
     This function moves point to the beginning of the buffer (or the limits of the accessible portion, when narrowing is in effect), setting the mark at the previous position.  If N is non-nil, then it puts point N tenths of the way from the beginning of the accessible portion of the buffer.

     In an interactive call, N is the numeric prefix argument, if provided; otherwise N defaults to nil.

     Warning: Don't use this function in Lisp programs!

 -- Command: end-of-buffer &optional n
     This function moves point to the end of the buffer (or the limits of the accessible portion, when narrowing is in effect), setting the mark at the previous position.  If N is non-nil, then it puts point N tenths of the way from the end of the accessible portion of the buffer.

     In an interactive call, N is the numeric prefix argument, if provided; otherwise N defaults to nil.

     Warning: Don't use this function in Lisp programs!

Motion by Text Lines
--------------------

Text lines are portions of the buffer delimited by newline characters, which are regarded as part of the previous line.  The first text line begins at the beginning of the buffer, and the last text line ends at the end of the buffer whether or not the last character is a newline. The division of the buffer into text lines is not affected by the width of the window, by line continuation in display, or by how tabs and control characters are displayed.

 -- Command: goto-line line
     This function moves point to the front of the LINEth line, counting from line 1 at beginning of the buffer.  If LINE is less than 1, it moves point to the beginning of the buffer.  If LINE is greater than the number of lines in the buffer, it moves point to the end of the buffer---that is, the end of the last line of the buffer.  This is the only case in which goto-line does not necessarily move to the beginning of a line.

     If narrowing is in effect, then LINE still counts from the beginning of the buffer, but point cannot go outside the accessible portion.  So goto-line moves point to the beginning or end of the accessible portion, if the line number specifies an inaccessible position.

     The return value of goto-line is the difference between LINE and the line number of the line to which point actually was able to move (in the full buffer, before taking account of narrowing). Thus, the value is positive if the scan encounters the real end of the buffer before finding the specified line.  The value is zero if scan encounters the end of the accessible portion but not the real end of the buffer.

     In an interactive call, LINE is the numeric prefix argument if one has been provided.  Otherwise LINE is read in the minibuffer.

 -- Command: beginning-of-line &optional count
     This function moves point to the beginning of the current line.  With an argument COUNT not nil or 1, it moves forward COUNT-1 lines and then to the beginning of the line.

     This function does not move point across a field boundary (see Fields) unless doing so would move beyond there to a different line; therefore, if COUNT is nil or 1, and point starts at a field boundary, point does not move.  To ignore field boundaries, either bind inhibit-field-text-motion to t, or use the forward-line function instead.  For instance, (forward-line 0) does the same thing as (beginning-of-line), except that it ignores field boundaries.

     If this function reaches the end of the buffer (or of the accessible portion, if narrowing is in effect), it positions point there.  No error is signaled.

 -- Function: line-beginning-position &optional count
     Return the position that (beginning-of-line COUNT) would move to.

 -- Command: end-of-line &optional count
     This function moves point to the end of the current line.  With an argument COUNT not nil or 1, it moves forward COUNT-1 lines and then to the end of the line.

     This function does not move point across a field boundary (see Fields) unless doing so would move beyond there to a different line; therefore, if COUNT is nil or 1, and point starts at a field boundary, point does not move.  To ignore field boundaries, bind inhibit-field-text-motion to t.

     If this function reaches the end of the buffer (or of the accessible portion, if narrowing is in effect), it positions point there.  No error is signaled.

 -- Function: line-end-position &optional count
     Return the position that (end-of-line COUNT) would move to.

 -- Command: forward-line &optional count
     This function moves point forward COUNT lines, to the beginning of the line.  If COUNT is negative, it moves point -COUNT lines backward, to the beginning of a line.  If COUNT is zero, it moves point to the beginning of the current line.

     If forward-line encounters the beginning or end of the buffer (or of the accessible portion) before finding that many lines, it sets point there.  No error is signaled.

     forward-line returns the difference between COUNT and the number of lines actually moved.  If you attempt to move down five lines from the beginning of a buffer that has only three lines, point stops at the end of the last line, and the value will be 2.

     In an interactive call, COUNT is the numeric prefix argument.

 -- Function: count-lines start end
     This function returns the number of lines between the positions START and END in the current buffer.  If START and END are equal, then it returns 0.  Otherwise it returns at least 1, even if START and END are on the same line.  This is because the text between them, considered in isolation, must contain at least one line unless it is empty.

     Here is an example of using count-lines:

          (defun current-line ()
            "Return the vertical position of point..."
            (+ (count-lines (window-start) (point))
               (if (= (current-column) 0) 1 0)))

 -- Function: line-number-at-pos &optional pos
     This function returns the line number in the current buffer corresponding the buffer position POS.  If POS is nil or omitted, the current buffer position is used.

Also see the functions bolp and eolp in Near Point. These functions do not move point, but test whether it is already at the beginning or end of a line.

Motion by Screen Lines
----------------------

The line functions in the previous section count text lines, delimited only by newline characters.  By contrast, these functions count screen lines, which are defined by the way the text appears on the screen.  A text line is a single screen line if it is short enough to fit the width of the selected window, but otherwise it may occupy several screen lines.

In some cases, text lines are truncated on the screen rather than continued onto additional screen lines.  In these cases, vertical-motion moves point much like forward-line. See Truncation.

Because the width of a given string depends on the flags that control the appearance of certain characters, vertical-motion behaves differently, for a given piece of text, depending on the buffer it is in, and even on the selected window (because the width, the truncation flag, and display table may vary between windows).  See Usual Display.

These functions scan text to determine where screen lines break, and thus take time proportional to the distance scanned.  If you intend to use them heavily, Emacs provides caches which may improve the performance of your code.  See cache-long-line-scans.

 -- Function: vertical-motion count &optional window
     This function moves point to the start of the screen line COUNT screen lines down from the screen line containing point.  If COUNT is negative, it moves up instead.

     vertical-motion returns the number of screen lines over which it moved point.  The value may be less in absolute value than COUNT if the beginning or end of the buffer was reached.

     The window WINDOW is used for obtaining parameters such as the width, the horizontal scrolling, and the display table.  But vertical-motion always operates on the current buffer, even if WINDOW currently displays some other buffer.

 -- Function: count-screen-lines &optional beg end count-final-newline window
     This function returns the number of screen lines in the text from BEG to END.  The number of screen lines may be different from the number of actual lines, due to line continuation, the display table, etc.  If BEG and END are nil or omitted, they default to the beginning and end of the accessible portion of the buffer.

     If the region ends with a newline, that is ignored unless the optional third argument COUNT-FINAL-NEWLINE is non-nil.

     The optional fourth argument WINDOW specifies the window for obtaining parameters such as width, horizontal scrolling, and so on. The default is to use the selected window's parameters.

     Like vertical-motion, count-screen-lines always uses the current buffer, regardless of which buffer is displayed in WINDOW.  This makes possible to use count-screen-lines in any buffer, whether or not it is currently displayed in some window.

 -- Command: move-to-window-line count
     This function moves point with respect to the text currently displayed in the selected window.  It moves point to the beginning of the screen line COUNT screen lines from the top of the window.  If COUNT is negative, that specifies a position -COUNT lines from the bottom (or the last line of the buffer, if the buffer ends above the specified screen position).

     If COUNT is nil, then point moves to the beginning of the line in the middle of the window.  If the absolute value of COUNT is greater than the size of the window, then point moves to the place that would appear on that screen line if the window were tall enough. This will probably cause the next redisplay to scroll to bring that location onto the screen.

     In an interactive call, COUNT is the numeric prefix argument.

     The value returned is the window line number point has moved to, with the top line in the window numbered 0.

 -- Function: compute-motion from frompos to topos width offsets window
     This function scans the current buffer, calculating screen positions. It scans the buffer forward from position FROM, assuming that is at screen coordinates FROMPOS, to position TO or coordinates TOPOS, whichever comes first.  It returns the ending buffer position and screen coordinates.

     The coordinate arguments FROMPOS and TOPOS are cons cells of the form (HPOS . VPOS).

     The argument WIDTH is the number of columns available to display text; this affects handling of continuation lines.  Use the value returned by window-width for the window of your choice; normally, use (window-width WINDOW).

     The argument OFFSETS is either nil or a cons cell of the form (HSCROLL . TAB-OFFSET).  Here HSCROLL is the number of columns not being displayed at the left margin; most callers get this by calling window-hscroll.  Meanwhile, TAB-OFFSET is the offset between column numbers on the screen and column numbers in the buffer.  This can be nonzero in a continuation line, when the previous screen lines' widths do not add up to a multiple of tab-width.  It is always zero in a non-continuation line.

     The window WINDOW serves only to specify which display table to use.  compute-motion always operates on the current buffer, regardless of what buffer is displayed in WINDOW.

     The return value is a list of five elements:

          (POS HPOS VPOS PREVHPOS CONTIN)

     Here POS is the buffer position where the scan stopped, VPOS is the vertical screen position, and HPOS is the horizontal screen position.

     The result PREVHPOS is the horizontal position one character back from POS.  The result CONTIN is t if the last line was continued after (or within) the previous character.

     For example, to find the buffer position of column COL of screen line LINE of a certain window, pass the window's display start location as FROM and the window's upper-left coordinates as FROMPOS. Pass the buffer's (point-max) as TO, to limit the scan to the end of the accessible portion of the buffer, and pass LINE and COL as TOPOS.  Here's a function that does this:

          (defun coordinates-of-position (col line)
            (car (compute-motion (window-start)
                                 '(0 . 0)
                                 (point-max)
                                 (cons col line)
                                 (window-width)
                                 (cons (window-hscroll) 0)
                                 (selected-window))))

     When you use compute-motion for the minibuffer, you need to use minibuffer-prompt-width to get the horizontal position of the beginning of the first screen line.  See Minibuffer Misc.

Moving over Balanced Expressions
--------------------------------

Here are several functions concerned with balanced-parenthesis expressions (also called sexps in connection with moving across them in Emacs).  The syntax table controls how these functions interpret various characters; see Syntax Tables.  See Parsing Expressions, for lower-level primitives for scanning sexps or parts of sexps.  For user-level commands, see Commands for Editing with Parentheses (The GNU Emacs Manual).

 -- Command: forward-list &optional arg
     This function moves forward across ARG (default 1) balanced groups of parentheses.  (Other syntactic entities such as words or paired string quotes are ignored.)

 -- Command: backward-list &optional arg
     This function moves backward across ARG (default 1) balanced groups of parentheses.  (Other syntactic entities such as words or paired string quotes are ignored.)

 -- Command: up-list &optional arg
     This function moves forward out of ARG (default 1) levels of parentheses. A negative argument means move backward but still to a less deep spot.

 -- Command: down-list &optional arg
     This function moves forward into ARG (default 1) levels of parentheses.  A negative argument means move backward but still go deeper in parentheses (-ARG levels).

 -- Command: forward-sexp &optional arg
     This function moves forward across ARG (default 1) balanced expressions. Balanced expressions include both those delimited by parentheses and other kinds, such as words and string constants see Parsing Expressions.  For example,

          ---------- Buffer: foo ----------
          (concat-!- "foo " (car x) y z)
          ---------- Buffer: foo ----------

          (forward-sexp 3)
               => nil

          ---------- Buffer: foo ----------
          (concat "foo " (car x) y-!- z)
          ---------- Buffer: foo ----------

 -- Command: backward-sexp &optional arg
     This function moves backward across ARG (default 1) balanced expressions.

 -- Command: beginning-of-defun &optional arg
     This function moves back to the ARGth beginning of a defun.  If ARG is negative, this actually moves forward, but it still moves to the beginning of a defun, not to the end of one.

 -- Command: end-of-defun &optional arg
     This function moves forward to the ARGth end of a defun.  If ARG is negative, this actually moves backward, but it still moves to the end of a defun, not to the beginning of one.

 -- User Option: defun-prompt-regexp
     If non-nil, this variable holds a regular expression that specifies what text can appear before the open-parenthesis that starts a defun.  That is to say, a defun begins on a line that starts with a match for this regular expression, followed by a character with open-parenthesis syntax.

 -- User Option: open-paren-in-column-0-is-defun-start
     If this variable's value is non-nil, an open parenthesis in column 0 is considered to be the start of a defun.  If it is nil, an open parenthesis in column 0 has no special meaning. The default is t.

 -- Variable: beginning-of-defun-function
     If non-nil, this variable holds a function for finding the beginning of a defun.  The function beginning-of-defun calls this function instead of using its normal method.

 -- Variable: end-of-defun-function
     If non-nil, this variable holds a function for finding the end of a defun.  The function end-of-defun calls this function instead of using its normal method.

Skipping Characters
-------------------

The following two functions move point over a specified set of characters.  For example, they are often used to skip whitespace.  For related functions, see Motion and Syntax.

These functions convert the set string to multibyte if the buffer is multibyte, and they convert it to unibyte if the buffer is unibyte, as the search functions do (see Searching and Matching).

 -- Function: skip-chars-forward character-set &optional limit
     This function moves point in the current buffer forward, skipping over a given set of characters.  It examines the character following point, then advances point if the character matches CHARACTER-SET.  This continues until it reaches a character that does not match.  The function returns the number of characters moved over.

     The argument CHARACTER-SET is like the inside of a [...] in a regular expression except that ] is never special and \ quotes ^, - or \.  Thus, "a-zA-Z" skips over all letters, stopping before the first nonletter, and "^a-zA-Z" skips nonletters stopping before the first letter.  See Regular Expressions.

     If LIMIT is supplied (it must be a number or a marker), it specifies the maximum position in the buffer that point can be skipped to.  Point will stop at or before LIMIT.

     In the following example, point is initially located directly before the T.  After the form is evaluated, point is located at the end of that line (between the t of hat and the newline).  The function skips all letters and spaces, but not newlines.

          ---------- Buffer: foo ----------
          I read "-!-The cat in the hat
          comes back" twice.
          ---------- Buffer: foo ----------

          (skip-chars-forward "a-zA-Z ")
               => nil

          ---------- Buffer: foo ----------
          I read "The cat in the hat-!-
          comes back" twice.
          ---------- Buffer: foo ----------

     Note that char classes are not currently supported in CHARACTER-SET; they will be treated as literals.  Thus you cannot use "[:alpha:]" instead of "a-zA-Z" to include non-ASCII letters.  A way to skip forward over all letters is:

          (re-search-forward "\\=[[:alpha:]]*" nil t)

 -- Function: skip-chars-backward character-set &optional limit
     This function moves point backward, skipping characters that match CHARACTER-SET, until LIMIT.  It is just like skip-chars-forward except for the direction of motion.

     The return value indicates the distance traveled.  It is an integer that is zero or less.

Excursions
==========

It is often useful to move point ``temporarily'' within a localized portion of the program, or to switch buffers temporarily.  This is called an excursion, and it is done with the save-excursion special form.  This construct initially remembers the identity of the current buffer, and its values of point and the mark, and restores them after the completion of the excursion.

The forms for saving and restoring the configuration of windows are described elsewhere (see Window Configurations, and see Frame Configurations).

 -- Special Form: save-excursion forms...
     The save-excursion special form saves the identity of the current buffer and the values of point and the mark in it, evaluates FORMS, and finally restores the buffer and its saved values of point and the mark.  All three saved values are restored even in case of an abnormal exit via throw or error (see Nonlocal Exits).

     The save-excursion special form is the standard way to switch buffers or move point within one part of a program and avoid affecting the rest of the program.  It is used more than 4000 times in the Lisp sources of Emacs.

     save-excursion does not save the values of point and the mark for other buffers, so changes in other buffers remain in effect after save-excursion exits.

     Likewise, save-excursion does not restore window-buffer correspondences altered by functions such as switch-to-buffer. One way to restore these correspondences, and the selected window, is to use save-window-excursion inside save-excursion (see Window Configurations).

     The value returned by save-excursion is the result of the last of FORMS, or nil if no FORMS are given.

          (save-excursion FORMS)
          ==
          (let ((old-buf (current-buffer))
                (old-pnt (point-marker))

                (old-mark (copy-marker (mark-marker))))
            (unwind-protect
                (progn FORMS)
              (set-buffer old-buf)

              (goto-char old-pnt)
              (set-marker (mark-marker) old-mark)))

Warning: Ordinary insertion of text adjacent to the saved point value relocates the saved value, just as it relocates all markers. More precisely, the saved value is a marker with insertion type nil.  See Marker Insertion Types.  Therefore, when the saved point value is restored, it normally comes before the inserted text.

Although save-excursion saves the location of the mark, it does not prevent functions which modify the buffer from setting deactivate-mark, and thus causing the deactivation of the mark after the command finishes.  See The Mark.

Narrowing
=========

Narrowing means limiting the text addressable by Emacs editing commands to a limited range of characters in a buffer.  The text that remains addressable is called the accessible portion of the buffer.

Narrowing is specified with two buffer positions which become the beginning and end of the accessible portion.  For most editing commands and most Emacs primitives, these positions replace the values of the beginning and end of the buffer.  While narrowing is in effect, no text outside the accessible portion is displayed, and point cannot move outside the accessible portion.

Values such as positions or line numbers, which usually count from the beginning of the buffer, do so despite narrowing, but the functions which use them refuse to operate on text that is inaccessible.

The commands for saving buffers are unaffected by narrowing; they save the entire buffer regardless of any narrowing.

 -- Command: narrow-to-region start end
     This function sets the accessible portion of the current buffer to start at START and end at END.  Both arguments should be character positions.

     In an interactive call, START and END are set to the bounds of the current region (point and the mark, with the smallest first).

 -- Command: narrow-to-page &optional move-count
     This function sets the accessible portion of the current buffer to include just the current page.  An optional first argument MOVE-COUNT non-nil means to move forward or backward by MOVE-COUNT pages and then narrow to one page.  The variable page-delimiter specifies where pages start and end (see Standard Regexps).

     In an interactive call, MOVE-COUNT is set to the numeric prefix argument.

 -- Command: widen
     This function cancels any narrowing in the current buffer, so that the entire contents are accessible.  This is called widening. It is equivalent to the following expression:

          (narrow-to-region 1 (1+ (buffer-size)))

 -- Special Form: save-restriction body...
     This special form saves the current bounds of the accessible portion, evaluates the BODY forms, and finally restores the saved bounds, thus restoring the same state of narrowing (or absence thereof) formerly in effect.  The state of narrowing is restored even in the event of an abnormal exit via throw or error (see Nonlocal Exits). Therefore, this construct is a clean way to narrow a buffer temporarily.

     The value returned by save-restriction is that returned by the last form in BODY, or nil if no body forms were given.

     Caution: it is easy to make a mistake when using the save-restriction construct.  Read the entire description here before you try it.

     If BODY changes the current buffer, save-restriction still restores the restrictions on the original buffer (the buffer whose restrictions it saved from), but it does not restore the identity of the current buffer.

     save-restriction does not restore point and the mark; use save-excursion for that.  If you use both save-restriction and save-excursion together, save-excursion should come first (on the outside).  Otherwise, the old point value would be restored with temporary narrowing still in effect.  If the old point value were outside the limits of the temporary narrowing, this would fail to restore it accurately.

     Here is a simple example of correct use of save-restriction:

          ---------- Buffer: foo ----------
          This is the contents of foo
          This is the contents of foo
          This is the contents of foo-!-
          ---------- Buffer: foo ----------

          (save-excursion
            (save-restriction
              (goto-char 1)
              (forward-line 2)
              (narrow-to-region 1 (point))
              (goto-char (point-min))
              (replace-string "foo" "bar")))

          ---------- Buffer: foo ----------
          This is the contents of bar
          This is the contents of bar
          This is the contents of foo-!-
          ---------- Buffer: foo ----------