]> git.lyx.org Git - lyx.git/blobdiff - src/BufferView.C
get rid of MSVC warning (signed/unsigned comparison)
[lyx.git] / src / BufferView.C
index 1ba092af0dcb3272003d2e7a1e9c045463e1e953..008f03e4aa11e10347289ed7911525d6fbb5aa85 100644 (file)
@@ -20,6 +20,7 @@
 #include "buffer_funcs.h"
 #include "bufferlist.h"
 #include "bufferparams.h"
+#include "bufferview_funcs.h"
 #include "coordcache.h"
 #include "CutAndPaste.h"
 #include "debug.h"
@@ -62,6 +63,7 @@
 #include "frontends/Alert.h"
 #include "frontends/FileDialog.h"
 #include "frontends/FontMetrics.h"
+#include "frontends/Selection.h"
 
 #include "graphics/Previews.h"
 
@@ -83,10 +85,11 @@ namespace lyx {
 using support::addPath;
 using support::bformat;
 using support::FileFilterList;
+using support::FileName;
 using support::fileSearch;
 using support::isDirWriteable;
+using support::isFileReadable;
 using support::makeDisplayPath;
-using support::makeAbsPath;
 using support::package;
 
 using std::distance;
@@ -123,7 +126,7 @@ BufferView::BufferView()
        : width_(0), height_(0), buffer_(0), wh_(0),
          cursor_(*this),
          multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
-         intl_(new Intl)
+         intl_(new Intl), last_inset_(0)
 {
        xsel_cache_.set = false;
        intl_->initKeyMapper(lyxrc.use_kbmap);
@@ -153,7 +156,7 @@ void BufferView::setBuffer(Buffer * b)
                buffer_->saveCursor(cursor_.selectionBegin(),
                                    cursor_.selectionEnd());
                // current buffer is going to be switched-off, save cursor pos
-               LyX::ref().session().lastFilePos().save(buffer_->fileName(),
+               LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
                        boost::tie(cursor_.pit(), cursor_.pos()) );
        }
 
@@ -185,7 +188,6 @@ void BufferView::setBuffer(Buffer * b)
                                    << "Buffer addr: " << buffer_ << endl;
                cursor_.push(buffer_->inset());
                cursor_.resetAnchor();
-               buffer_->text().init(this);
                buffer_->text().setCurrentFont(cursor_);
                if (buffer_->getCursor().size() > 0 &&
                    buffer_->getAnchor().size() > 0)
@@ -194,30 +196,23 @@ void BufferView::setBuffer(Buffer * b)
                        cursor_.resetAnchor();
                        cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
                        cursor_.setSelection();
+                       theSelection().haveSelection(cursor_.selection());
                }
        }
 
-       update();
+       if (buffer_)
+               updateMetrics(false);    
 
        if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
                graphics::Previews::get().generateBufferPreviews(*buffer_);
 }
 
 
-bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
+bool BufferView::loadLyXFile(FileName const & filename, bool tolastfiles)
 {
-       // Get absolute path of file and add ".lyx"
-       // to the filename if necessary
-       string s = fileSearch(string(), filename, "lyx");
-
-       bool const found = !s.empty();
-
-       if (!found)
-               s = filename;
-
        // File already open?
-       if (theBufferList().exists(s)) {
-               docstring const file = makeDisplayPath(s, 20);
+       if (theBufferList().exists(filename.absFilename())) {
+               docstring const file = makeDisplayPath(filename.absFilename(), 20);
                docstring text = bformat(_("The document %1$s is already "
                                                     "loaded.\n\nDo you want to revert "
                                                     "to the saved version?"), file);
@@ -225,11 +220,11 @@ bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
                        text, 0, 1,  _("&Revert"), _("&Switch to document"));
 
                if (ret != 0) {
-                       setBuffer(theBufferList().getBuffer(s));
+                       setBuffer(theBufferList().getBuffer(filename.absFilename()));
                        return true;
                }
                // FIXME: should be LFUN_REVERT
-               if (!theBufferList().close(theBufferList().getBuffer(s), false))
+               if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
                        return false;
                // Fall through to new load. (Asger)
                buffer_ = 0;
@@ -237,21 +232,21 @@ bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
 
        Buffer * b = 0;
 
-       if (found) {
-               b = theBufferList().newBuffer(s);
-               if (!lyx::loadLyXFile(b, s)) {
+       if (isFileReadable(filename)) {
+               b = theBufferList().newBuffer(filename.absFilename());
+               if (!lyx::loadLyXFile(b, filename)) {
                        theBufferList().release(b);
                        return false;
                }
        } else {
                docstring text = bformat(_("The document %1$s does not yet "
                                                     "exist.\n\nDo you want to create "
-                                                    "a new document?"), from_utf8(s));
+                                                    "a new document?"), from_utf8(filename.absFilename()));
                int const ret = Alert::prompt(_("Create new document?"),
                         text, 0, 1, _("&Create"), _("Cancel"));
 
                if (ret == 0) {
-                       b = newFile(s, string(), true);
+                       b = newFile(filename.absFilename(), string(), true);
                        if (!b)
                                return false;
                } else
@@ -262,43 +257,27 @@ bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
        // Send the "errors" signal in case of parsing errors
        b->errors("Parse");
 
+       // Update the labels and section numbering.
+       updateLabels(*buffer_);
        // scroll to the position when the file was last closed
        if (lyxrc.use_lastfilepos) {
                pit_type pit;
                pos_type pos;
-               boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(s);
-               // I am not sure how to separate the following part to a function
-               // so I will leave this to Lars.
-               //
-               // check pit since the document may be externally changed.
-               if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
-                       ParIterator it = b->par_iterator_begin();
-                       ParIterator const end = b->par_iterator_end();
-                       for (; it != end; ++it)
-                               if (it.pit() == pit) {
-                                       // restored pos may be bigger than it->size
-                                       setCursor(makeDocIterator(it, min(pos, it->size())));
-                                       update(Update::FitCursor);
-                                       break;
-                               }
+               boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(filename);
+               // if successfully move to pit (returned par_id is not zero), update metrics
+               if (moveToPosition(pit, 0, pos).get<1>()) {
+                       if (fitCursor())
+                               updateMetrics(false);
                }
        }
 
        if (tolastfiles)
-               LyX::ref().session().lastFiles().add(b->fileName());
+               LyX::ref().session().lastFiles().add(FileName(b->fileName()));
 
        return true;
 }
 
 
-void BufferView::reload()
-{
-       string const fn = buffer_->fileName();
-       if (theBufferList().close(buffer_, false))
-               loadLyXFile(fn);
-}
-
-
 void BufferView::resize()
 {
        if (!buffer_)
@@ -306,8 +285,7 @@ void BufferView::resize()
 
        lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
 
-       buffer_->text().init(this);
-       update();
+       updateMetrics(false);
        switchKeyMap();
 }
 
@@ -341,6 +319,10 @@ bool BufferView::multiParSel()
 
 bool BufferView::update(Update::flags flags)
 {
+       // last_inset_ points to the last visited inset. This pointer may become
+       // invalid because of keyboard editing. Since all such operations
+       // causes screen update(), I reset last_inset_ to avoid such a problem.
+       last_inset_ = 0;
        // This is close to a hot-path.
        if (lyxerr.debugging(Debug::DEBUG)) {
                lyxerr[Debug::DEBUG]
@@ -362,15 +344,51 @@ bool BufferView::update(Update::flags flags)
        // Update macro store
        buffer_->buildMacros();
 
-       // First drawing step
-       updateMetrics(flags & Update::SinglePar);
-
+       // Now do the first drawing step if needed. This consists on updating
+       // the CoordCache in updateMetrics().
        // The second drawing step is done in WorkArea::redraw() if needed.
-       bool const need_second_step =
-               (flags & (Update::SinglePar | Update::Force | Update::FitCursor | Update::MultiParSel))
-               && (fitCursor() || multiParSel());
 
-       return need_second_step;
+       // Case when no explicit update is requested.
+       if (!flags) {
+               // no need to redraw anything.
+               metrics_info_.update_strategy = NoScreenUpdate;
+               return false;
+       }
+
+       if (flags == Update::Decoration) {
+               metrics_info_.update_strategy = DecorationUpdate;
+               return true;
+       }
+
+       if (flags == Update::FitCursor 
+               || flags == (Update::Decoration | Update::FitCursor)) {
+               bool const fit_cursor = fitCursor();
+               // tell the frontend to update the screen if needed.
+               if (fit_cursor) {
+                       updateMetrics(false);
+                       return true;
+               }
+               if (flags & Update::Decoration) {
+                       metrics_info_.update_strategy = DecorationUpdate;
+                       return true;
+               }
+               // no screen update is needed.
+               metrics_info_.update_strategy = NoScreenUpdate;
+               return false;
+       }
+
+       bool full_metrics = flags & Update::Force;
+       if (flags & Update::MultiParSel)
+               full_metrics |= multiParSel();
+
+       bool const single_par = !full_metrics;
+       updateMetrics(single_par);
+
+       if (flags & Update::FitCursor && fitCursor())
+               updateMetrics(false);
+
+       // tell the frontend to update the screen.
+       return true;
 }
 
 
@@ -384,6 +402,8 @@ void BufferView::updateScrollbar()
        }
 
        LyXText & t = buffer_->text();
+       TextMetrics & tm = text_metrics_[&t];
+
        int const parsize = int(t.paragraphs().size() - 1);
        if (anchor_ref_ >  parsize)  {
                anchor_ref_ = parsize;
@@ -404,13 +424,14 @@ void BufferView::updateScrollbar()
        // estimated average paragraph height:
        if (wh_ == 0)
                wh_ = height_ / 4;
-       int h = t.getPar(anchor_ref_).height();
+
+       int h = tm.parMetrics(anchor_ref_).height();
 
        // Normalize anchor/offset (MV):
        while (offset_ref_ > h && anchor_ref_ < parsize) {
                anchor_ref_++;
                offset_ref_ -= h;
-               h = t.getPar(anchor_ref_).height();
+               h = tm.parMetrics(anchor_ref_).height();
        }
        // Look at paragraph heights on-screen
        int sumh = 0;
@@ -418,7 +439,7 @@ void BufferView::updateScrollbar()
        for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
                if (sumh > height_)
                        break;
-               int const h2 = t.getPar(pit).height();
+               int const h2 = tm.parMetrics(pit).height();
                sumh += h2;
                nh++;
        }
@@ -451,15 +472,18 @@ void BufferView::scrollDocView(int value)
                return;
 
        LyXText & t = buffer_->text();
+       TextMetrics & tm = text_metrics_[&t];
 
        float const bar = value / float(wh_ * t.paragraphs().size());
 
        anchor_ref_ = int(bar * t.paragraphs().size());
        if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
                anchor_ref_ = int(t.paragraphs().size()) - 1;
-       t.redoParagraph(*this, anchor_ref_);
-       int const h = t.getPar(anchor_ref_).height();
+
+       tm.redoParagraph(anchor_ref_);
+       int const h = tm.parMetrics(anchor_ref_).height();
        offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
+       updateMetrics(false);
 }
 
 
@@ -507,7 +531,8 @@ Change const BufferView::getCurrentChange() const
 void BufferView::saveBookmark(bool persistent)
 {
        LyX::ref().session().bookmarks().save(
-               buffer_->fileName(),
+               FileName(buffer_->fileName()),
+               cursor_.pit(),
                cursor_.paragraph().id(),
                cursor_.pos(),
                persistent
@@ -518,15 +543,31 @@ void BufferView::saveBookmark(bool persistent)
 }
 
 
-void BufferView::moveToPosition(int par_id, pos_type par_pos)
+boost::tuple<pit_type, int> BufferView::moveToPosition(pit_type par_pit, int par_id, pos_type par_pos)
 {
        cursor_.clearSelection();
 
-       ParIterator par = buffer_->getParFromID(par_id);
-       if (par == buffer_->par_iterator_end())
-               return;
-
-       setCursor(makeDocIterator(par, min(par->size(), par_pos)));
+       // if a valid par_id is given, try it first
+       if (par_id > 0) {
+               ParIterator par = buffer_->getParFromID(par_id);
+               if (par != buffer_->par_iterator_end()) {
+                       setCursor(makeDocIterator(par, min(par->size(), par_pos)));
+                       return boost::make_tuple(cursor_.pit(), par_id);
+               }
+       }
+       // if par_id == 0, or searching through par_id failed
+       if (static_cast<size_t>(par_pit) < buffer_->paragraphs().size()) {
+               ParIterator it = buffer_->par_iterator_begin();
+               ParIterator const end = buffer_->par_iterator_end();
+               for (; it != end; ++it)
+                       if (it.pit() == par_pit) {
+                               // restored pos may be bigger than it->size
+                               setCursor(makeDocIterator(it, min(par_pos, it->size())));
+                               return boost::make_tuple(par_pit, it->id());
+                       }
+       }
+       // both methods fail
+       return boost::make_tuple(pit_type(0), 0);
 }
 
 
@@ -554,12 +595,13 @@ int BufferView::workWidth() const
 void BufferView::center()
 {
        CursorSlice & bot = cursor_.bottom();
+       TextMetrics & tm = text_metrics_[bot.text()];
        pit_type const pit = bot.pit();
-       bot.text()->redoParagraph(*this, pit);
-       Paragraph const & par = bot.text()->paragraphs()[pit];
+       tm.redoParagraph(pit);
+       ParagraphMetrics const & pm = tm.parMetrics(pit);
        anchor_ref_ = pit;
        offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
-               + par.ascent() - height_ / 2;
+               + pm.ascent() - height_ / 2;
 }
 
 
@@ -576,8 +618,8 @@ FuncStatus BufferView::getStatus(FuncRequest const & cmd)
                flag.enabled(!buffer_->redostack().empty());
                break;
        case LFUN_FILE_INSERT:
-       case LFUN_FILE_INSERT_ASCII_PARA:
-       case LFUN_FILE_INSERT_ASCII:
+       case LFUN_FILE_INSERT_PLAINTEXT_PARA:
+       case LFUN_FILE_INSERT_PLAINTEXT:
        case LFUN_BOOKMARK_SAVE:
                // FIXME: Actually, these LFUNS should be moved to LyXText
                flag.enabled(cursor_.inTexted());
@@ -628,7 +670,11 @@ FuncStatus BufferView::getStatus(FuncRequest const & cmd)
        case LFUN_CHANGE_NEXT:
        case LFUN_ALL_CHANGES_ACCEPT:
        case LFUN_ALL_CHANGES_REJECT:
-               flag.enabled(buffer_); // FIXME: Change tracking (MG)
+               // TODO: context-sensitive enabling of LFUNs
+               // In principle, these command should only be enabled if there
+               // is a change in the document. However, without proper
+               // optimizations, this will inevitably result in poor performance.
+               flag.enabled(buffer_);
                break;
 
        case LFUN_BUFFER_TOGGLE_COMPRESSION: {
@@ -685,22 +731,22 @@ bool BufferView::dispatch(FuncRequest const & cmd)
                break;
 
        case LFUN_FILE_INSERT:
-               // FIXME: We don't know the encoding of filenames
+               // FIXME UNICODE
                menuInsertLyXFile(to_utf8(cmd.argument()));
                break;
 
-       case LFUN_FILE_INSERT_ASCII_PARA:
-               // FIXME: We don't know the encoding of filenames
-               insertAsciiFile(this, to_utf8(cmd.argument()), true);
+       case LFUN_FILE_INSERT_PLAINTEXT_PARA:
+               // FIXME UNICODE
+               insertPlaintextFile(this, to_utf8(cmd.argument()), true);
                break;
 
-       case LFUN_FILE_INSERT_ASCII:
-               // FIXME: We don't know the encoding of filenames
-               insertAsciiFile(this, to_utf8(cmd.argument()), false);
+       case LFUN_FILE_INSERT_PLAINTEXT:
+               // FIXME UNICODE
+               insertPlaintextFile(this, to_utf8(cmd.argument()), false);
                break;
 
        case LFUN_FONT_STATE:
-               cur.message(from_utf8(cur.currentState()));
+               cur.message(cur.currentState());
                break;
 
        case LFUN_BOOKMARK_SAVE:
@@ -727,21 +773,34 @@ bool BufferView::dispatch(FuncRequest const & cmd)
 
        case LFUN_PARAGRAPH_GOTO: {
                int const id = convert<int>(to_utf8(cmd.argument()));
-               ParIterator par = buffer_->getParFromID(id);
-               if (par == buffer_->par_iterator_end()) {
-                       lyxerr[Debug::INFO] << "No matching paragraph found! ["
-                                           << id << ']' << endl;
-                       break;
-               } else {
-                       lyxerr[Debug::INFO] << "Paragraph " << par->id()
-                                           << " found." << endl;
+               int i = 0;
+               for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
+                       ParIterator par = b->getParFromID(id);
+                       if (par == b->par_iterator_end()) {
+                               lyxerr[Debug::INFO]
+                                       << "No matching paragraph found! ["
+                                       << id << "]." << endl;
+                       } else {
+                               lyxerr[Debug::INFO]
+                                       << "Paragraph " << par->id()
+                                       << " found in buffer `"
+                                       << b->fileName() << "'." << endl;
+
+                               if (b == buffer_) {
+                                       // Set the cursor
+                                       setCursor(makeDocIterator(par, 0));
+                                       update();
+                                       switchKeyMap();
+                               } else {
+                                       // Switch to other buffer view and resend cmd
+                                       theLyXFunc().dispatch(FuncRequest(
+                                               LFUN_BUFFER_SWITCH, b->fileName()));
+                                       theLyXFunc().dispatch(cmd);
+                               }
+                               break;
+                       }
+                       ++i;
                }
-
-               // Set the cursor
-               setCursor(makeDocIterator(par, 0));
-
-               update();
-               switchKeyMap();
                break;
        }
 
@@ -800,7 +859,7 @@ bool BufferView::dispatch(FuncRequest const & cmd)
 #warning FIXME changes
 #endif
                while (findNextChange(this))
-                       getLyXText()->acceptChange(cursor_);
+                       getLyXText()->acceptOrRejectChange(cursor_, true);
                update();
                break;
        }
@@ -811,7 +870,7 @@ bool BufferView::dispatch(FuncRequest const & cmd)
 #warning FIXME changes
 #endif
                while (findNextChange(this))
-                       getLyXText()->rejectChange(cursor_);
+                       getLyXText()->acceptOrRejectChange(cursor_, false);
                break;
        }
 
@@ -973,23 +1032,24 @@ void BufferView::clearSelection()
        if (buffer_) {
                cursor_.clearSelection();
                xsel_cache_.set = false;
+               // The buffer did not really change, but this causes the
+               // redraw we need because we cleared the selection above.
+               buffer_->changed();
        }
 }
 
 
 void BufferView::workAreaResize(int width, int height)
 {
-       bool const widthChange = width != width_;
-       bool const heightChange = height != height_;
-
        // Update from work area
        width_ = width;
        height_ = height;
 
+       // The complete text metrics will be redone.
+       text_metrics_.clear();
+
        if (buffer_)
                resize();
-
-       update();
 }
 
 
@@ -1005,12 +1065,9 @@ bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
        if (!buffer_)
                return false;
 
-       bool needRedraw = false;
-
        LCursor cur(*this);
        cur.push(buffer_->inset());
        cur.selection() = cursor_.selection();
-       needRedraw |= cur.selection();
 
        // Either the inset under the cursor or the
        // surrounding LyXText will handle this event.
@@ -1024,6 +1081,53 @@ bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
        //lyxerr << BOOST_CURRENT_FUNCTION
        //       << " * created temp cursor:" << cur << endl;
 
+       // NOTE: editXY returns the top level inset of nested insets. If you happen
+       // to move from a text (inset=0) to a text inside an inset (e.g. an opened
+       // footnote inset, again inset=0), that inset will not be redrawn.
+       if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
+               bool need_redraw = false;
+               
+               if (inset != last_inset_) {
+                       if (last_inset_)
+                               need_redraw |= last_inset_->setMouseHover(false);
+                       if (inset)
+                               need_redraw |= inset->setMouseHover(true);
+                       last_inset_ = inset;
+               }
+
+               // if last metrics update was in singlepar mode, WorkArea::redraw() will
+               // not expose the button for redraw. We adjust here the metrics dimension
+               // to enable a full redraw.
+               // FIXME: It is possible to redraw only the area around the button!
+               if (need_redraw 
+                       && metrics_info_.update_strategy == SingleParUpdate) {
+                       // FIXME: It should be possible to redraw only the area around 
+                       // the button by doing this:
+                       //
+                       //metrics_info_.singlepar = false;
+                       //metrics_info_.y1 = ymin of button;
+                       //metrics_info_.y2 = ymax of button;
+                       //
+                       // Unfortunately, rowpainter.C:paintText() does not distinguish
+                       // between background updates and text updates. So we use the hammer
+                       // solution for now. We could also avoid the updateMetrics() below
+                       // by using the first and last pit of the CoordCache. Have a look
+                       // at LyXText::getPitNearY() to see what I mean.
+                       //
+                       //metrics_info_.pit1 = first pit of CoordCache;
+                       //metrics_info_.pit2 = last pit of CoordCache;
+                       //metrics_info_.singlepar = false;
+                       //metrics_info_.y1 = 0;
+                       //metrics_info_.y2 = height_;
+                       //
+                       updateMetrics(false);
+               }
+
+               // This event (moving without mouse click) is not passed further.
+               // This should be changed if it is further utilized.
+               return need_redraw;
+       }
+
        // Put anchor at the same position.
        cur.resetAnchor();
 
@@ -1033,7 +1137,6 @@ bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
        //  cur.bv().cursor() = cur;  (or similar)
        if (inset) {
                inset->dispatch(cur, cmd);
-               needRedraw = true;
        }
 
        // Now dispatch to the temporary cursor. If the real cursor should
@@ -1041,17 +1144,11 @@ bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
        if (!cur.result().dispatched())
                cur.dispatch(cmd);
 
-       if (cur.result().dispatched()) {
-               // Redraw if requested or necessary.
-               if (cur.result().update())
-                       needRedraw |= update(Update::FitCursor | Update::Force);
-               else
-                       needRedraw |= update(Update::FitCursor | Update::MultiParSel);
-       }
+       // Redraw if requested and necessary.
+       if (cur.result().dispatched() && cur.result().update())
+               return update(cur.result().update());
 
-       // When the above and the inner function are fixed, we can do this:
-       //return needRedraw;
-       return true;
+       return false;
 }
 
 
@@ -1072,8 +1169,6 @@ void BufferView::scroll(int /*lines*/)
 //
 //     scrollDocView(new_top_y);
 //
-//     // Update the scrollbar.
-//     workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
 }
 
 
@@ -1121,6 +1216,30 @@ LyXText const * BufferView::getLyXText() const
 }
 
 
+TextMetrics const & BufferView::textMetrics(LyXText const * t) const
+{
+       return const_cast<BufferView *>(this)->textMetrics(t);
+}
+
+
+TextMetrics & BufferView::textMetrics(LyXText const * t)
+{
+       TextMetricsCache::iterator tmc_it  = text_metrics_.find(t);
+       if (tmc_it == text_metrics_.end()) {
+               tmc_it = text_metrics_.insert(
+                       make_pair(t, TextMetrics(this, const_cast<LyXText *>(t)))).first;
+       }       
+       return tmc_it->second;
+}
+
+
+ParagraphMetrics const & BufferView::parMetrics(LyXText const * t,
+               pit_type pit) const
+{
+       return textMetrics(t).parMetrics(pit);
+}
+
+
 int BufferView::workHeight() const
 {
        return height_;
@@ -1138,7 +1257,29 @@ void BufferView::setCursor(DocIterator const & dit)
 }
 
 
-void BufferView::mouseSetCursor(LCursor & cur)
+bool BufferView::checkDepm(LCursor & cur, LCursor & old)
+{
+       // Would be wrong to delete anything if we have a selection.
+       if (cur.selection())
+               return false;
+
+       bool need_anchor_change = false;
+       bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
+               need_anchor_change);
+
+       if (need_anchor_change)
+               cur.resetAnchor();
+       
+       if (!changed)
+               return false;
+
+       updateMetrics(false);
+       buffer_->changed();
+       return true;
+}
+
+
+bool BufferView::mouseSetCursor(LCursor & cur)
 {
        BOOST_ASSERT(&cur.bv() == this);
 
@@ -1149,14 +1290,33 @@ void BufferView::mouseSetCursor(LCursor & cur)
 
        // do the dEPM magic if needed
        // FIXME: move this to InsetText::notifyCursorLeaves?
+       bool update = false;
        if (!badcursor && cursor_.inTexted())
-               cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
+               checkDepm(cur, cursor_);
+
+       // if the cursor was in an empty script inset and the new
+       // position is in the nucleus of the inset, notifyCursorLeaves
+       // will kill the script inset itself. So we check all the
+       // elements of the cursor to make sure that they are correct.
+       // For an example, see bug 2933: 
+       // http://bugzilla.lyx.org/show_bug.cgi?id=2933
+       // The code below could maybe be moved to a DocIterator method.
+       //lyxerr << "cur before " << cur <<std::endl;
+       DocIterator dit(cur.inset());
+       dit.push_back(cur.bottom());
+       size_t i = 1;
+       while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
+               dit.push_back(cur[i]);
+               ++i;
+       }
+       //lyxerr << "5 cur after" << dit <<std::endl;
 
-       cursor_ = cur;
+       cursor_.setCursor(dit);
        cursor_.clearSelection();
+       // remember new position.
        cursor_.setTargetX();
        finishUndo();
-
+       return update;
 }
 
 
@@ -1173,6 +1333,7 @@ void BufferView::putSelectionAt(DocIterator const & cur,
                        cursor_.setSelection(cursor_, -length);
                } else
                        cursor_.setSelection(cursor_, length);
+               theSelection().haveSelection(cursor_.selection());
        }
 }
 
@@ -1201,47 +1362,56 @@ ViewMetricsInfo const & BufferView::viewMetricsInfo()
 }
 
 
+// FIXME: We should split-up updateMetrics() for the singlepar case.
 void BufferView::updateMetrics(bool singlepar)
 {
-       // Clear out the position cache in case of full screen redraw.
-       //if (!singlepar)
-               coord_cache_.clear();
-
        LyXText & buftext = buffer_->text();
+       TextMetrics & tm = textMetrics(&buftext);
        pit_type size = int(buftext.paragraphs().size());
 
        if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
                anchor_ref_ = int(buftext.paragraphs().size() - 1);
                offset_ref_ = 0;
        }
+       
+       // If the paragraph metrics has changed, we can not
+       // use the singlepar optimisation.
+       if (singlepar
+               // In Single Paragraph mode, rebreak only
+               // the (main text, not inset!) paragraph containing the cursor.
+               // (if this paragraph contains insets etc., rebreaking will
+               // recursively descend)
+               && tm.redoParagraph(cursor_.bottom().pit()))
+               singlepar = false;
 
        pit_type const pit = anchor_ref_;
        int pit1 = pit;
        int pit2 = pit;
        size_t const npit = buftext.paragraphs().size();
 
-       // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
-       // the (main text, not inset!) paragraph containing the cursor.
-       // (if this paragraph contains insets etc., rebreaking will
-       // recursively descend)
-       if (!singlepar || pit == cursor_.bottom().pit())
-               buftext.redoParagraph(*this, pit);
-       int y0 = buftext.getPar(pit).ascent() - offset_ref_;
+       // Rebreak anchor paragraph.
+       if (!singlepar)
+               tm.redoParagraph(pit);
+       
+       // Clear out the position cache in case of full screen redraw.
+       if (!singlepar)
+               coord_cache_.clear();
 
-       // Redo paragraphs above anchor if necessary; again, in Single Par
-       // mode, only if we encounter the (main text) one having the cursor.
+       int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
+
+       // Redo paragraphs above anchor if necessary.
        int y1 = y0;
        while (y1 > 0 && pit1 > 0) {
-               y1 -= buftext.getPar(pit1).ascent();
+               y1 -= tm.parMetrics(pit1).ascent();
                --pit1;
-               if (!singlepar || pit1 == cursor_.bottom().pit())
-                       buftext.redoParagraph(*this, pit1);
-               y1 -= buftext.getPar(pit1).descent();
+               if (!singlepar)
+                       tm.redoParagraph(pit1);
+               y1 -= tm.parMetrics(pit1).descent();
        }
 
 
        // Take care of ascent of first line
-       y1 -= buftext.getPar(pit1).ascent();
+       y1 -= tm.parMetrics(pit1).ascent();
 
        // Normalize anchor for next time
        anchor_ref_ = pit1;
@@ -1254,34 +1424,33 @@ void BufferView::updateMetrics(bool singlepar)
                anchor_ref_ = 0;
        }
 
-       // Redo paragraphs below the anchor if necessary. Single par mode:
-       // only the one containing the cursor if encountered.
+       // Redo paragraphs below the anchor if necessary.
        int y2 = y0;
        while (y2 < height_ && pit2 < int(npit) - 1) {
-               y2 += buftext.getPar(pit2).descent();
+               y2 += tm.parMetrics(pit2).descent();
                ++pit2;
-               if (!singlepar || pit2 == cursor_.bottom().pit())
-                       buftext.redoParagraph(*this, pit2);
-               y2 += buftext.getPar(pit2).ascent();
+               if (!singlepar)
+                       tm.redoParagraph(pit2);
+               y2 += tm.parMetrics(pit2).ascent();
        }
 
        // Take care of descent of last line
-       y2 += buftext.getPar(pit2).descent();
+       y2 += tm.parMetrics(pit2).descent();
 
        // The coordinates of all these paragraphs are correct, cache them
        int y = y1;
        CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
        for (pit_type pit = pit1; pit <= pit2; ++pit) {
-               Paragraph const & par = buftext.getPar(pit);
-               y += par.ascent();
+               ParagraphMetrics const & pm = tm.parMetrics(pit);
+               y += pm.ascent();
                parPos[pit] = Point(0, y);
                if (singlepar && pit == cursor_.bottom().pit()) {
                        // In Single Paragraph mode, collect here the
                        // y1 and y2 of the (one) paragraph the cursor is in
-                       y1 = y - par.ascent();
-                       y2 = y + par.descent();
+                       y1 = y - pm.ascent();
+                       y2 = y + pm.descent();
                }
-               y += par.descent();
+               y += pm.descent();
        }
 
        if (singlepar) {
@@ -1301,7 +1470,8 @@ void BufferView::updateMetrics(bool singlepar)
                << "size: " << size
                << endl;
 
-       metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
+       metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, 
+               singlepar? SingleParUpdate: FullScreenUpdate, size);
 
        if (lyxerr.debugging(Debug::WORKAREA)) {
                lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
@@ -1323,7 +1493,7 @@ void BufferView::menuInsertLyXFile(string const & filenm)
                if (buffer_) {
                        string const trypath = buffer_->filePath();
                        // If directory is writeable, use this as default.
-                       if (isDirWriteable(trypath))
+                       if (isDirWriteable(FileName(trypath)))
                                initpath = trypath;
                }
 
@@ -1354,7 +1524,7 @@ void BufferView::menuInsertLyXFile(string const & filenm)
 
        // Get absolute path of file and add ".lyx"
        // to the filename if necessary
-       filename = fileSearch(string(), filename, "lyx");
+       filename = fileSearch(string(), filename, "lyx").absFilename();
 
        docstring const disp_fn = makeDisplayPath(filename);
        // emit message signal.
@@ -1362,7 +1532,7 @@ void BufferView::menuInsertLyXFile(string const & filenm)
 
        docstring res;
        Buffer buf("", false);
-       if (lyx::loadLyXFile(&buf, makeAbsPath(filename))) {
+       if (lyx::loadLyXFile(&buf, FileName(filename))) {
                ErrorList & el = buffer_->errorList("Parse");
                // Copy the inserted document error list into the current buffer one.
                el = buf.errorList("Parse");
@@ -1379,5 +1549,4 @@ void BufferView::menuInsertLyXFile(string const & filenm)
        resize();
 }
 
-
 } // namespace lyx