]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
header cleanups and removal of unused methods.
[lyx.git] / src / BufferView_pimpl.C
1 /**
2  * \file BufferView_pimpl.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Alfredo Braunstein
8  * \author Lars Gullik Bjønnes
9  * \author Jean-Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  * \author Dekel Tsur
14  * \author Jürgen Vigna
15  *
16  * Full author contact details are available in file CREDITS.
17  */
18
19 #include <config.h>
20
21 #include "BufferView_pimpl.h"
22 #include "buffer.h"
23 #include "buffer_funcs.h"
24 #include "bufferlist.h"
25 #include "bufferparams.h"
26 #include "coordcache.h"
27 #include "cursor.h"
28 #include "CutAndPaste.h"
29 #include "debug.h"
30 #include "dispatchresult.h"
31 #include "factory.h"
32 #include "FloatList.h"
33 #include "funcrequest.h"
34 #include "FuncStatus.h"
35 #include "gettext.h"
36 #include "intl.h"
37 #include "insetiterator.h"
38 #include "LaTeXFeatures.h"
39 #include "lyx_cb.h" // added for Dispatch functions
40 #include "lyx_main.h"
41 #include "lyxfind.h"
42 #include "lyxfunc.h"
43 #include "lyxtext.h"
44 #include "lyxrc.h"
45 #include "session.h"
46 #include "metricsinfo.h"
47 #include "paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "pariterator.h"
51 #include "rowpainter.h"
52 #include "toc.h"
53 #include "undo.h"
54 #include "vspace.h"
55
56 #include "insets/insetbibtex.h"
57 #include "insets/insetref.h"
58 #include "insets/insettext.h"
59
60 #include "frontends/Alert.h"
61 #include "frontends/Clipboard.h"
62 #include "frontends/Dialogs.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/font_metrics.h"
65 #include "frontends/Gui.h"
66 #include "frontends/LyXView.h"
67 #include "frontends/Painter.h"
68 #include "frontends/WorkArea.h"
69
70 #include "graphics/Previews.h"
71
72 #include "support/convert.h"
73 #include "support/filefilterlist.h"
74 #include "support/filetools.h"
75 #include "support/forkedcontr.h"
76 #include "support/package.h"
77 #include "support/types.h"
78
79 #include <boost/bind.hpp>
80 #include <boost/current_function.hpp>
81
82 #include <functional>
83 #include <vector>
84
85 using lyx::frontend::WorkArea;
86 using lyx::frontend::Clipboard;
87 using lyx::frontend::Gui;
88
89 using lyx::pos_type;
90
91 using lyx::support::addPath;
92 using lyx::support::bformat;
93 using lyx::support::FileFilterList;
94 using lyx::support::fileSearch;
95 using lyx::support::ForkedcallsController;
96 using lyx::support::isDirWriteable;
97 using lyx::support::makeDisplayPath;
98 using lyx::support::makeAbsPath;
99 using lyx::support::package;
100
101 using std::endl;
102 using std::istringstream;
103 using std::make_pair;
104 using std::min;
105 using std::max;
106 using std::string;
107 using std::mem_fun_ref;
108 using std::vector;
109
110 extern BufferList bufferlist;
111
112
113 namespace {
114
115 unsigned int const saved_positions_num = 20;
116
117 // All the below connection objects are needed because of a bug in some
118 // versions of GCC (<=2.96 are on the suspects list.) By having and assigning
119 // to these connections we avoid a segfault upon startup, and also at exit.
120 // (Lgb)
121
122 boost::signals::connection timecon;
123
124 /// Return an inset of this class if it exists at the current cursor position
125 template <class T>
126 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
127 {
128         T * inset = 0;
129         DocIterator it = cur;
130         if (it.nextInset() &&
131             it.nextInset()->lyxCode() == code) {
132                 inset = static_cast<T*>(it.nextInset());
133         }
134         return inset;
135 }
136
137 } // anon namespace
138
139
140 BufferView::Pimpl::Pimpl(BufferView & bv, LyXView * owner, WorkArea * workArea)
141         : bv_(&bv), owner_(owner), workArea_(workArea), buffer_(0), wh_(0), cursor_timeout(400),
142           using_xterm_cursor(false), cursor_(bv),
143           anchor_ref_(0), offset_ref_(0)
144 {
145         xsel_cache_.set = false;
146
147         // Setup the signals
148         timecon = cursor_timeout.timeout
149                 .connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
150
151         cursor_timeout.start();
152         
153         saved_positions.resize(saved_positions_num);
154         // load saved bookmarks
155         lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
156         for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
157                 bm != bmList.end(); ++bm)
158                 if (bm->get<0>() < saved_positions_num)
159                         saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
160         // and then clear them
161         bmList.clear();
162 }
163
164
165 void BufferView::Pimpl::addError(ErrorItem const & ei)
166 {
167         errorlist_.push_back(ei);
168 }
169
170
171 void BufferView::Pimpl::showReadonly(bool)
172 {
173         owner_->updateWindowTitle();
174         owner_->getDialogs().updateBufferDependent(false);
175 }
176
177
178 void BufferView::Pimpl::connectBuffer(Buffer & buf)
179 {
180         if (errorConnection_.connected())
181                 disconnectBuffer();
182
183         errorConnection_ =
184                 buf.error.connect(
185                         boost::bind(&BufferView::Pimpl::addError, this, _1));
186
187         messageConnection_ =
188                 buf.message.connect(
189                         boost::bind(&LyXView::message, owner_, _1));
190
191         busyConnection_ =
192                 buf.busy.connect(
193                         boost::bind(&LyXView::busy, owner_, _1));
194
195         titleConnection_ =
196                 buf.updateTitles.connect(
197                         boost::bind(&LyXView::updateWindowTitle, owner_));
198
199         timerConnection_ =
200                 buf.resetAutosaveTimers.connect(
201                         boost::bind(&LyXView::resetAutosaveTimer, owner_));
202
203         readonlyConnection_ =
204                 buf.readonly.connect(
205                         boost::bind(&BufferView::Pimpl::showReadonly, this, _1));
206
207         closingConnection_ =
208                 buf.closing.connect(
209                         boost::bind(&BufferView::Pimpl::setBuffer, this, (Buffer *)0));
210 }
211
212
213 void BufferView::Pimpl::disconnectBuffer()
214 {
215         errorConnection_.disconnect();
216         messageConnection_.disconnect();
217         busyConnection_.disconnect();
218         titleConnection_.disconnect();
219         timerConnection_.disconnect();
220         readonlyConnection_.disconnect();
221         closingConnection_.disconnect();
222 }
223
224
225 void BufferView::Pimpl::newFile(string const & filename, string const & tname,
226         bool isNamed)
227 {
228         setBuffer(::newFile(filename, tname, isNamed));
229 }
230
231
232 bool BufferView::Pimpl::loadLyXFile(string const & filename, bool tolastfiles)
233 {
234         // Get absolute path of file and add ".lyx"
235         // to the filename if necessary
236         string s = fileSearch(string(), filename, "lyx");
237
238         bool const found = !s.empty();
239
240         if (!found)
241                 s = filename;
242
243         // File already open?
244         if (bufferlist.exists(s)) {
245                 string const file = makeDisplayPath(s, 20);
246                 string text = bformat(_("The document %1$s is already "
247                                         "loaded.\n\nDo you want to revert "
248                                         "to the saved version?"), file);
249                 int const ret = Alert::prompt(_("Revert to saved document?"),
250                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
251
252                 if (ret != 0) {
253                         setBuffer(bufferlist.getBuffer(s));
254                         return true;
255                 }
256                 // FIXME: should be LFUN_REVERT
257                 if (!bufferlist.close(bufferlist.getBuffer(s), false))
258                         return false;
259                 // Fall through to new load. (Asger)
260         }
261
262         Buffer * b = 0;
263
264         if (found) {
265                 b = bufferlist.newBuffer(s);
266                 connectBuffer(*b);
267                 if (!::loadLyXFile(b, s)) {
268                         bufferlist.release(b);
269                         return false;
270                 }
271         } else {
272                 string text = bformat(_("The document %1$s does not yet "
273                                         "exist.\n\nDo you want to create "
274                                         "a new document?"), s);
275                 int const ret = Alert::prompt(_("Create new document?"),
276                          text, 0, 1, _("&Create"), _("Cancel"));
277
278                 if (ret == 0)
279                         b = ::newFile(s, string(), true);
280                 else
281                         return false;
282         }
283
284         setBuffer(b);
285         bv_->showErrorList(_("Parse"));
286
287         // scroll to the position when the file was last closed
288         if (lyxrc.use_lastfilepos) {
289                 lyx::pit_type pit;
290                 lyx::pos_type pos;
291                 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
292                 // I am not sure how to separate the following part to a function
293                 // so I will leave this to Lars.
294                 //
295                 // check pit since the document may be externally changed.
296                 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
297                         ParIterator it = b->par_iterator_begin();
298                         ParIterator const end = b->par_iterator_end();
299                         for (; it != end; ++it)
300                                 if (it.pit() == pit) {
301                                         // restored pos may be bigger than it->size
302                                         bv_->setCursor(makeDocIterator(it, min(pos, it->size())));
303                                         bv_->update(Update::FitCursor);
304                                         break;
305                                 }
306                 }
307         }
308
309         if (tolastfiles)
310                 LyX::ref().session().addLastFile(b->fileName());
311
312         return true;
313 }
314
315
316 lyx::frontend::Gui & BufferView::Pimpl::gui() const
317 {
318         return owner_->gui();
319 }
320
321
322 lyx::frontend::Painter & BufferView::Pimpl::painter() const
323 {
324         return workArea_->getPainter();
325 }
326
327
328 int BufferView::Pimpl::width() const
329 {
330         return width_;
331 }
332
333
334 int BufferView::Pimpl::height() const
335 {
336         return height_;
337 }
338
339
340 void BufferView::Pimpl::setBuffer(Buffer * b)
341 {
342         lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
343                             << "[ b = " << b << "]" << endl;
344
345         if (buffer_) {
346                 disconnectBuffer();
347                 // Save the actual cursor position and anchor inside the
348                 // buffer so that it can be restored in case we rechange
349                 // to this buffer later on.
350                 buffer_->saveCursor(cursor_.selectionBegin(),
351                                     cursor_.selectionEnd());
352                 // current buffer is going to be switched-off, save cursor pos
353                 LyX::ref().session().saveFilePosition(buffer_->fileName(),
354                         boost::tie(cursor_.pit(), cursor_.pos()) );
355         }
356
357         // If we are closing current buffer, switch to the first in
358         // buffer list.
359         if (!b) {
360                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
361                                     << " No Buffer!" << endl;
362                 // We are closing the buffer, use the first buffer as current
363                 buffer_ = bufferlist.first();
364                 owner_->getDialogs().hideBufferDependent();
365         } else {
366                 // Set current buffer
367                 buffer_ = b;
368         }
369
370         // Reset old cursor
371         cursor_ = LCursor(*bv_);
372         anchor_ref_ = 0;
373         offset_ref_ = 0;
374
375
376         // If we're quitting lyx, don't bother updating stuff
377         if (quitting)
378                 return;
379
380         if (buffer_) {
381                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
382                                     << "Buffer addr: " << buffer_ << endl;
383                 connectBuffer(*buffer_);
384                 cursor_.push(buffer_->inset());
385                 cursor_.resetAnchor();
386                 buffer_->text().init(bv_);
387                 buffer_->text().setCurrentFont(cursor_);
388                 if (buffer_->getCursor().size() > 0 &&
389                     buffer_->getAnchor().size() > 0)
390                 {
391                         cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
392                         cursor_.resetAnchor();
393                         cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
394                         cursor_.setSelection();
395                 }
396
397                 // Buffer-dependent dialogs should be updated or
398                 // hidden. This should go here because some dialogs (eg ToC)
399                 // require bv_->text.
400                 owner_->getDialogs().updateBufferDependent(true);
401         }
402
403         update();
404         owner_->updateMenubar();
405         owner_->updateToolbars();
406         owner_->updateLayoutChoice();
407         owner_->updateWindowTitle();
408
409         // This is done after the layout combox has been populated
410         if (buffer_) {
411                 size_t i = cursor_.depth() - 1;
412                 // we know we'll eventually find a paragraph
413                 while (true) {
414                         CursorSlice const & slice = cursor_[i];
415                         if (!slice.inset().inMathed()) {
416                                 LyXLayout_ptr const layout = slice.paragraph().layout();
417                                 owner_->setLayout(layout->name());
418                                 break;
419                         }
420                         BOOST_ASSERT(i>0);
421                         --i;
422                 }
423         }
424
425         if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
426                 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
427 }
428
429
430 void BufferView::Pimpl::resizeCurrentBuffer()
431 {
432         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
433         owner_->busy(true);
434         owner_->message(_("Formatting document..."));
435
436         LyXText * text = bv_->text();
437         if (!text)
438                 return;
439
440         text->init(bv_);
441         update();
442
443         switchKeyMap();
444         owner_->busy(false);
445
446         // Reset the "Formatting..." message
447         owner_->clearMessage();
448 }
449
450
451 void BufferView::Pimpl::updateScrollbar()
452 {
453         if (!bv_->text()) {
454                 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
455                                      << " no text in updateScrollbar" << endl;
456                 scrollbarParameters_.reset();
457                 return;
458         }
459
460         LyXText & t = *bv_->text();
461         int const parsize = int(t.paragraphs().size() - 1);
462         if (anchor_ref_ >  parsize)  {
463                 anchor_ref_ = parsize;
464                 offset_ref_ = 0;
465         }
466
467         lyxerr[Debug::GUI]
468                 << BOOST_CURRENT_FUNCTION
469                 << " Updating scrollbar: height: " << t.paragraphs().size()
470                 << " curr par: " << cursor_.bottom().pit()
471                 << " default height " << defaultRowHeight() << endl;
472
473         // It would be better to fix the scrollbar to understand
474         // values in [0..1] and divide everything by wh
475
476         // estimated average paragraph height:
477         if (wh_ == 0)
478                 wh_ = height_ / 4;
479         int h = t.getPar(anchor_ref_).height();
480
481         // Normalize anchor/offset (MV):
482         while (offset_ref_ > h && anchor_ref_ < parsize) {
483                 anchor_ref_++;
484                 offset_ref_ -= h;
485                 h = t.getPar(anchor_ref_).height();
486         }
487         // Look at paragraph heights on-screen
488         int sumh = 0;
489         int nh = 0;
490         for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
491                 if (sumh > height_)
492                         break;
493                 int const h2 = t.getPar(pit).height();
494                 sumh += h2;
495                 nh++;
496         }
497         int const hav = sumh / nh;
498         // More realistic average paragraph height
499         if (hav > wh_)
500                 wh_ = hav;
501
502         scrollbarParameters_.height = (parsize + 1) * wh_;
503         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
504         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
505 }
506
507
508 ScrollbarParameters const & BufferView::Pimpl::scrollbarParameters() const
509 {
510         return scrollbarParameters_;
511 }
512
513
514 void BufferView::Pimpl::scrollDocView(int value)
515 {
516         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
517                            << "[ value = " << value << "]" << endl;
518
519         if (!buffer_)
520                 return;
521
522         owner_->gui().guiCursor().hide();
523
524         LyXText & t = *bv_->text();
525
526         float const bar = value / float(wh_ * t.paragraphs().size());
527
528         anchor_ref_ = int(bar * t.paragraphs().size());
529         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
530                 anchor_ref_ = int(t.paragraphs().size()) - 1;
531         t.redoParagraph(anchor_ref_);
532         int const h = t.getPar(anchor_ref_).height();
533         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
534         update();
535
536         if (!lyxrc.cursor_follows_scrollbar)
537                 return;
538
539         int const height = 2 * defaultRowHeight();
540         int const first = height;
541         int const last = height_ - height;
542         LCursor & cur = cursor_;
543
544         bv_funcs::CurStatus st = bv_funcs::status(bv_, cur);
545
546         switch (st) {
547         case bv_funcs::CUR_ABOVE:
548                 t.setCursorFromCoordinates(cur, 0, first);
549                 cur.clearSelection();
550                 break;
551         case bv_funcs::CUR_BELOW:
552                 t.setCursorFromCoordinates(cur, 0, last);
553                 cur.clearSelection();
554                 break;
555         case bv_funcs::CUR_INSIDE:
556                 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
557                 int const newy = min(last, max(y, first));
558                 if (y != newy) {
559                         cur.reset(buffer_->inset());
560                         t.setCursorFromCoordinates(cur, 0, newy);
561                 }
562         }
563         owner_->updateLayoutChoice();
564 }
565
566
567 void BufferView::Pimpl::scroll(int /*lines*/)
568 {
569 //      if (!buffer_)
570 //              return;
571 //
572 //      LyXText const * t = bv_->text();
573 //      int const line_height = defaultRowHeight();
574 //
575 //      // The new absolute coordinate
576 //      int new_top_y = top_y() + lines * line_height;
577 //
578 //      // Restrict to a valid value
579 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
580 //      new_top_y = std::max(0, new_top_y);
581 //
582 //      scrollDocView(new_top_y);
583 //
584 //      // Update the scrollbar.
585 //      workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());
586 }
587
588
589 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
590                                          key_modifier::state state)
591 {
592         owner_->getLyXFunc().processKeySym(key, state);
593
594         /* This is perhaps a bit of a hack. When we move
595          * around, or type, it's nice to be able to see
596          * the cursor immediately after the keypress. So
597          * we reset the toggle timeout and force the visibility
598          * of the cursor. Note we cannot do this inside
599          * dispatch() itself, because that's called recursively.
600          */
601         if (available())
602                 owner_->gui().guiCursor().show(*bv_);
603 }
604
605
606 void BufferView::Pimpl::selectionRequested()
607 {
608         static string sel;
609
610         if (!available())
611                 return;
612
613         LCursor & cur = cursor_;
614
615         if (!cur.selection()) {
616                 xsel_cache_.set = false;
617                 return;
618         }
619
620         if (!xsel_cache_.set ||
621             cur.top() != xsel_cache_.cursor ||
622             cur.anchor_.top() != xsel_cache_.anchor)
623         {
624                 xsel_cache_.cursor = cur.top();
625                 xsel_cache_.anchor = cur.anchor_.top();
626                 xsel_cache_.set = cur.selection();
627                 sel = cur.selectionAsString(false);
628                 if (!sel.empty())
629                         owner_->gui().clipboard().put(sel);
630         }
631 }
632
633
634 void BufferView::Pimpl::selectionLost()
635 {
636         if (available()) {
637                 owner_->gui().guiCursor().hide();
638                 cursor_.clearSelection();
639                 xsel_cache_.set = false;
640         }
641 }
642
643
644 void BufferView::Pimpl::workAreaResize(int width, int height)
645 {
646         bool const widthChange = width != width_;
647         bool const heightChange = height != height_;
648
649         // Update from work area
650         width_ = width;
651         height_ = height;
652
653         if (buffer_ && widthChange) {
654                 // The visible LyXView need a resize
655                 resizeCurrentBuffer();
656         }
657
658         if (widthChange || heightChange)
659                 update();
660
661         owner_->updateLayoutChoice();
662 }
663
664
665 bool BufferView::Pimpl::fitCursor()
666 {
667         if (bv_funcs::status(bv_, cursor_) == bv_funcs::CUR_INSIDE) {
668                 LyXFont const font = cursor_.getFont();
669                 int const asc = font_metrics::maxAscent(font);
670                 int const des = font_metrics::maxDescent(font);
671                 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
672                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
673                         return false;
674         }
675         center();
676         return true;
677 }
678
679
680 bool BufferView::Pimpl::multiParSel()
681 {
682         if (!cursor_.selection())
683                 return false;
684         bool ret = multiparsel_cache_;
685         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
686         // Either this, or previous selection spans paragraphs
687         return ret || multiparsel_cache_;
688 }
689
690
691 void BufferView::Pimpl::update(Update::flags flags)
692 {
693         lyxerr[Debug::DEBUG]
694                 << BOOST_CURRENT_FUNCTION
695                 << "[fitcursor = " << (flags & Update::FitCursor)
696                 << ", forceupdate = " << (flags & Update::Force)
697                 << ", singlepar = " << (flags & Update::SinglePar)
698                 << "]  buffer: " << buffer_ << endl;
699
700         // Check needed to survive LyX startup
701         if (buffer_) {
702                 // Update macro store
703                 buffer_->buildMacros();
704
705                 CoordCache backup;
706                 std::swap(theCoords, backup);
707
708                 // This, together with doneUpdating(), verifies (using
709                 // asserts) that screen redraw is not called from
710                 // within itself.
711                 theCoords.startUpdating();
712
713                 // First drawing step
714                 ViewMetricsInfo vi = metrics(flags & Update::SinglePar);
715                 bool forceupdate(flags & (Update::Force | Update::SinglePar));
716
717                 if ((flags & Update::FitCursor) && fitCursor()) {
718                         forceupdate = true;
719                         vi = metrics();
720                 }
721                 if ((flags & Update::MultiParSel) && multiParSel()) {
722                         forceupdate = true;
723                         vi = metrics();
724                 }
725                 if (forceupdate) {
726                         // Second drawing step
727                         workArea_->redraw(*bv_, vi);
728                 } else {
729                         // Abort updating of the coord
730                         // cache - just restore the old one
731                         std::swap(theCoords, backup);
732                 }
733         } else
734                 workArea_->greyOut();
735
736         owner_->view_state_changed();
737 }
738
739
740 // Callback for cursor timer
741 void BufferView::Pimpl::cursorToggle()
742 {
743         if (buffer_) {
744                 owner_->gui().guiCursor().toggle(*bv_);
745
746                 // Use this opportunity to deal with any child processes that
747                 // have finished but are waiting to communicate this fact
748                 // to the rest of LyX.
749                 ForkedcallsController & fcc = ForkedcallsController::get();
750                 fcc.handleCompletedProcesses();
751         }
752
753         cursor_timeout.restart();
754 }
755
756
757 bool BufferView::Pimpl::available() const
758 {
759         return buffer_ && bv_->text();
760 }
761
762
763 Change const BufferView::Pimpl::getCurrentChange()
764 {
765         if (!buffer_->params().tracking_changes)
766                 return Change(Change::UNCHANGED);
767
768         LyXText * text = bv_->getLyXText();
769         LCursor & cur = cursor_;
770
771         if (!cur.selection())
772                 return Change(Change::UNCHANGED);
773
774         return text->getPar(cur.selBegin().pit()).
775                         lookupChange(cur.selBegin().pos());
776 }
777
778
779 void BufferView::Pimpl::savePosition(unsigned int i)
780 {
781         if (i >= saved_positions_num)
782                 return;
783         BOOST_ASSERT(cursor_.inTexted());
784         saved_positions[i] = Position(buffer_->fileName(),
785                                       cursor_.paragraph().id(),
786                                       cursor_.pos());
787         if (i > 0)
788                 owner_->message(bformat(_("Saved bookmark %1$d"), i));
789 }
790
791
792 void BufferView::Pimpl::restorePosition(unsigned int i)
793 {
794         if (i >= saved_positions_num)
795                 return;
796
797         string const fname = saved_positions[i].filename;
798
799         cursor_.clearSelection();
800
801         if (fname != buffer_->fileName()) {
802                 Buffer * b = 0;
803                 if (bufferlist.exists(fname))
804                         b = bufferlist.getBuffer(fname);
805                 else {
806                         b = bufferlist.newBuffer(fname);
807                         // Don't ask, just load it
808                         ::loadLyXFile(b, fname);
809                 }
810                 if (b)
811                         setBuffer(b);
812         }
813
814         ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
815         if (par == buffer_->par_iterator_end())
816                 return;
817
818         bv_->setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
819
820         if (i > 0)
821                 owner_->message(bformat(_("Moved to bookmark %1$d"), i));
822 }
823
824
825 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
826 {
827         return i < saved_positions_num && !saved_positions[i].filename.empty();
828 }
829
830
831 void BufferView::Pimpl::saveSavedPositions()
832 {
833         // save bookmarks. It is better to use the pit interface
834         // but I do not know how to effectively convert between
835         // par_id and pit.
836         for (unsigned int i=1; i < saved_positions_num; ++i) {
837                 if ( isSavedPosition(i) )
838                         LyX::ref().session().saveBookmark( boost::tie(
839                                 i,
840                                 saved_positions[i].filename,
841                                 saved_positions[i].par_id,
842                                 saved_positions[i].par_pos) );
843         }
844 }
845
846
847 void BufferView::Pimpl::switchKeyMap()
848 {
849         if (!lyxrc.rtl_support)
850                 return;
851
852         Intl & intl = owner_->getIntl();
853         if (bv_->getLyXText()->real_current_font.isRightToLeft()) {
854                 if (intl.keymap == Intl::PRIMARY)
855                         intl.keyMapSec();
856         } else {
857                 if (intl.keymap == Intl::SECONDARY)
858                         intl.keyMapPrim();
859         }
860 }
861
862
863 void BufferView::Pimpl::center()
864 {
865         CursorSlice & bot = cursor_.bottom();
866         lyx::pit_type const pit = bot.pit();
867         bot.text()->redoParagraph(pit);
868         Paragraph const & par = bot.text()->paragraphs()[pit];
869         anchor_ref_ = pit;
870         offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
871                 + par.ascent() - height_ / 2;
872 }
873
874
875 void BufferView::Pimpl::stuffClipboard(string const & content) const
876 {
877         owner_->gui().clipboard().put(content);
878 }
879
880
881 void BufferView::Pimpl::menuInsertLyXFile(string const & filenm)
882 {
883         BOOST_ASSERT(cursor_.inTexted());
884         string filename = filenm;
885
886         if (filename.empty()) {
887                 // Launch a file browser
888                 string initpath = lyxrc.document_path;
889
890                 if (available()) {
891                         string const trypath = owner_->buffer()->filePath();
892                         // If directory is writeable, use this as default.
893                         if (isDirWriteable(trypath))
894                                 initpath = trypath;
895                 }
896
897                 FileDialog fileDlg(_("Select LyX document to insert"),
898                         LFUN_FILE_INSERT,
899                         make_pair(string(_("Documents|#o#O")),
900                                   string(lyxrc.document_path)),
901                         make_pair(string(_("Examples|#E#e")),
902                                   string(addPath(package().system_support(), "examples"))));
903
904                 FileDialog::Result result =
905                         fileDlg.open(initpath,
906                                      FileFilterList(_("LyX Documents (*.lyx)")),
907                                      string());
908
909                 if (result.first == FileDialog::Later)
910                         return;
911
912                 filename = result.second;
913
914                 // check selected filename
915                 if (filename.empty()) {
916                         owner_->message(_("Canceled."));
917                         return;
918                 }
919         }
920
921         // Get absolute path of file and add ".lyx"
922         // to the filename if necessary
923         filename = fileSearch(string(), filename, "lyx");
924
925         string const disp_fn = makeDisplayPath(filename);
926         owner_->message(bformat(_("Inserting document %1$s..."), disp_fn));
927
928         string res;
929         Buffer buf("", false);
930         buf.error.connect(boost::bind(&BufferView::Pimpl::addError, this, _1));
931         if (::loadLyXFile(&buf, makeAbsPath(filename))) {
932                 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
933                                              buf.params().textclass);
934                 res = _("Document %1$s inserted.");
935         } else
936                 res = _("Could not insert document %1$s");
937
938         owner_->message(bformat(res, disp_fn));
939         bv_->showErrorList(_("Document insertion"));
940         resizeCurrentBuffer();
941 }
942
943
944 void BufferView::Pimpl::trackChanges()
945 {
946         bool const tracking = buffer_->params().tracking_changes;
947
948         if (!tracking) {
949                 for_each(buffer_->par_iterator_begin(),
950                          buffer_->par_iterator_end(),
951                          bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
952                 buffer_->params().tracking_changes = true;
953
954                 // We cannot allow undos beyond the freeze point
955                 buffer_->undostack().clear();
956         } else {
957                 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
958                 if (lyx::find::findNextChange(bv_)) {
959                         owner_->getDialogs().show("changes");
960                         return;
961                 }
962
963                 for_each(buffer_->par_iterator_begin(),
964                          buffer_->par_iterator_end(),
965                          mem_fun_ref(&Paragraph::untrackChanges));
966
967                 buffer_->params().tracking_changes = false;
968         }
969
970         buffer_->redostack().clear();
971 }
972
973
974 bool BufferView::Pimpl::workAreaDispatch(FuncRequest const & cmd0)
975 {
976         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
977
978         // This is only called for mouse related events including
979         // LFUN_FILE_OPEN generated by drag-and-drop.
980         FuncRequest cmd = cmd0;
981
982         // Handle drag&drop
983         if (cmd.action == LFUN_FILE_OPEN) {
984                 owner_->dispatch(cmd);
985                 return true;
986         }
987
988         if (!buffer_)
989                 return false;
990
991         LCursor cur(*bv_);
992         cur.push(buffer_->inset());
993         cur.selection() = cursor_.selection();
994
995         // Doesn't go through lyxfunc, so we need to update
996         // the layout choice etc. ourselves
997
998         // E.g. Qt mouse press when no buffer
999         if (!available())
1000                 return false;
1001
1002         owner_->gui().guiCursor().hide();
1003
1004         // Either the inset under the cursor or the
1005         // surrounding LyXText will handle this event.
1006
1007         // Build temporary cursor.
1008         cmd.y = min(max(cmd.y, -1), height_);
1009         InsetBase * inset = bv_->text()->editXY(cur, cmd.x, cmd.y);
1010         //lyxerr << BOOST_CURRENT_FUNCTION
1011         //       << " * hit inset at tip: " << inset << endl;
1012         //lyxerr << BOOST_CURRENT_FUNCTION
1013         //       << " * created temp cursor:" << cur << endl;
1014
1015         // Put anchor at the same position.
1016         cur.resetAnchor();
1017
1018         // Try to dispatch to an non-editable inset near this position
1019         // via the temp cursor. If the inset wishes to change the real
1020         // cursor it has to do so explicitly by using
1021         //  cur.bv().cursor() = cur;  (or similar)
1022         if (inset)
1023                 inset->dispatch(cur, cmd);
1024
1025         // Now dispatch to the temporary cursor. If the real cursor should
1026         // be modified, the inset's dispatch has to do so explicitly.
1027         if (!cur.result().dispatched())
1028                 cur.dispatch(cmd);
1029
1030         if (cur.result().dispatched()) {
1031                 // Redraw if requested or necessary.
1032                 if (cur.result().update())
1033                         update(Update::FitCursor | Update::Force);
1034                 else
1035                         update(Update::FitCursor | Update::MultiParSel);
1036         }
1037
1038         // See workAreaKeyPress
1039         cursor_timeout.restart();
1040         owner_->gui().guiCursor().show(*bv_);
1041
1042         // Skip these when selecting
1043         if (cmd.action != LFUN_MOUSE_MOTION) {
1044                 owner_->updateLayoutChoice();
1045                 owner_->updateToolbars();
1046         }
1047
1048         // Slight hack: this is only called currently when we
1049         // clicked somewhere, so we force through the display
1050         // of the new status here.
1051         owner_->clearMessage();
1052         return true;
1053 }
1054
1055
1056 FuncStatus BufferView::Pimpl::getStatus(FuncRequest const & cmd)
1057 {
1058         FuncStatus flag;
1059
1060         switch (cmd.action) {
1061
1062         case LFUN_UNDO:
1063                 flag.enabled(!buffer_->undostack().empty());
1064                 break;
1065         case LFUN_REDO:
1066                 flag.enabled(!buffer_->redostack().empty());
1067                 break;
1068         case LFUN_FILE_INSERT:
1069         case LFUN_FILE_INSERT_ASCII_PARA:
1070         case LFUN_FILE_INSERT_ASCII:
1071         case LFUN_BOOKMARK_SAVE:
1072                 // FIXME: Actually, these LFUNS should be moved to LyXText
1073                 flag.enabled(cursor_.inTexted());
1074                 break;
1075         case LFUN_FONT_STATE:
1076         case LFUN_LABEL_INSERT:
1077         case LFUN_PARAGRAPH_GOTO:
1078         // FIXME handle non-trivially
1079         case LFUN_OUTLINE_UP:
1080         case LFUN_OUTLINE_DOWN:
1081         case LFUN_OUTLINE_IN:
1082         case LFUN_OUTLINE_OUT:
1083         case LFUN_ERROR_NEXT:
1084         case LFUN_NOTE_NEXT:
1085         case LFUN_REFERENCE_NEXT:
1086         case LFUN_WORD_FIND:
1087         case LFUN_WORD_REPLACE:
1088         case LFUN_MARK_OFF:
1089         case LFUN_MARK_ON:
1090         case LFUN_MARK_TOGGLE:
1091         case LFUN_SCREEN_RECENTER:
1092         case LFUN_BIBTEX_DATABASE_ADD:
1093         case LFUN_BIBTEX_DATABASE_DEL:
1094         case LFUN_WORDS_COUNT:
1095                 flag.enabled(true);
1096                 break;
1097
1098         case LFUN_LABEL_GOTO: {
1099                 flag.enabled(!cmd.argument.empty()
1100                     || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
1101                 break;
1102         }
1103
1104         case LFUN_BOOKMARK_GOTO:
1105                 flag.enabled(isSavedPosition(convert<unsigned int>(cmd.argument)));
1106                 break;
1107         case LFUN_CHANGES_TRACK:
1108                 flag.enabled(true);
1109                 flag.setOnOff(buffer_->params().tracking_changes);
1110                 break;
1111
1112         case LFUN_CHANGES_OUTPUT: {
1113                 OutputParams runparams;
1114                 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
1115                 flag.enabled(buffer_ && buffer_->params().tracking_changes
1116                         && features.isAvailable("dvipost"));
1117                 flag.setOnOff(buffer_->params().output_changes);
1118                 break;
1119         }
1120
1121         case LFUN_CHANGES_MERGE:
1122         case LFUN_CHANGE_ACCEPT: // what about these two
1123         case LFUN_CHANGE_REJECT: // what about these two
1124         case LFUN_ALL_CHANGES_ACCEPT:
1125         case LFUN_ALL_CHANGES_REJECT:
1126                 flag.enabled(buffer_ && buffer_->params().tracking_changes);
1127                 break;
1128
1129         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1130                 flag.setOnOff(buffer_->params().compressed);
1131                 break;
1132         }
1133
1134         default:
1135                 flag.enabled(false);
1136         }
1137
1138         return flag;
1139 }
1140
1141
1142
1143 bool BufferView::Pimpl::dispatch(FuncRequest const & cmd)
1144 {
1145         //lyxerr << BOOST_CURRENT_FUNCTION
1146         //       << [ cmd = " << cmd << "]" << endl;
1147
1148         // Make sure that the cached BufferView is correct.
1149         lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
1150                 << " action[" << cmd.action << ']'
1151                 << " arg[" << cmd.argument << ']'
1152                 << " x[" << cmd.x << ']'
1153                 << " y[" << cmd.y << ']'
1154                 << " button[" << cmd.button() << ']'
1155                 << endl;
1156
1157         LCursor & cur = cursor_;
1158
1159         switch (cmd.action) {
1160
1161         case LFUN_UNDO:
1162                 if (available()) {
1163                         cur.message(_("Undo"));
1164                         cur.clearSelection();
1165                         if (!textUndo(*bv_))
1166                                 cur.message(_("No further undo information"));
1167                         update();
1168                         switchKeyMap();
1169                 }
1170                 break;
1171
1172         case LFUN_REDO:
1173                 if (available()) {
1174                         cur.message(_("Redo"));
1175                         cur.clearSelection();
1176                         if (!textRedo(*bv_))
1177                                 cur.message(_("No further redo information"));
1178                         update();
1179                         switchKeyMap();
1180                 }
1181                 break;
1182
1183         case LFUN_FILE_INSERT:
1184                 menuInsertLyXFile(cmd.argument);
1185                 break;
1186
1187         case LFUN_FILE_INSERT_ASCII_PARA:
1188                 insertAsciiFile(bv_, cmd.argument, true);
1189                 break;
1190
1191         case LFUN_FILE_INSERT_ASCII:
1192                 insertAsciiFile(bv_, cmd.argument, false);
1193                 break;
1194
1195         case LFUN_FONT_STATE:
1196                 cur.message(cur.currentState());
1197                 break;
1198
1199         case LFUN_BOOKMARK_SAVE:
1200                 savePosition(convert<unsigned int>(cmd.argument));
1201                 break;
1202
1203         case LFUN_BOOKMARK_GOTO:
1204                 restorePosition(convert<unsigned int>(cmd.argument));
1205                 break;
1206
1207         case LFUN_LABEL_GOTO: {
1208                 string label = cmd.argument;
1209                 if (label.empty()) {
1210                         InsetRef * inset =
1211                                 getInsetByCode<InsetRef>(cursor_,
1212                                                          InsetBase::REF_CODE);
1213                         if (inset) {
1214                                 label = inset->getContents();
1215                                 savePosition(0);
1216                         }
1217                 }
1218
1219                 if (!label.empty())
1220                         bv_->gotoLabel(label);
1221                 break;
1222         }
1223
1224         case LFUN_PARAGRAPH_GOTO: {
1225                 int const id = convert<int>(cmd.argument);
1226                 ParIterator par = buffer_->getParFromID(id);
1227                 if (par == buffer_->par_iterator_end()) {
1228                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1229                                             << id << ']' << endl;
1230                         break;
1231                 } else {
1232                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
1233                                             << " found." << endl;
1234                 }
1235
1236                 // Set the cursor
1237                 bv_->setCursor(makeDocIterator(par, 0));
1238
1239                 update();
1240                 switchKeyMap();
1241                 break;
1242         }
1243
1244         case LFUN_OUTLINE_UP:
1245                 lyx::toc::outline(lyx::toc::Up, cursor_);
1246                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1247                 updateLabels(*buffer_);
1248                 break;
1249         case LFUN_OUTLINE_DOWN:
1250                 lyx::toc::outline(lyx::toc::Down, cursor_);
1251                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
1252                 updateLabels(*buffer_);
1253                 break;
1254         case LFUN_OUTLINE_IN:
1255                 lyx::toc::outline(lyx::toc::In, cursor_);
1256                 updateLabels(*buffer_);
1257                 break;  
1258         case LFUN_OUTLINE_OUT:
1259                 lyx::toc::outline(lyx::toc::Out, cursor_);
1260                 updateLabels(*buffer_);
1261                 break;
1262
1263         case LFUN_ERROR_NEXT:
1264                 bv_funcs::gotoInset(bv_, InsetBase::ERROR_CODE, false);
1265                 break;
1266
1267         case LFUN_NOTE_NEXT:
1268                 bv_funcs::gotoInset(bv_, InsetBase::NOTE_CODE, false);
1269                 break;
1270
1271         case LFUN_REFERENCE_NEXT: {
1272                 vector<InsetBase_code> tmp;
1273                 tmp.push_back(InsetBase::LABEL_CODE);
1274                 tmp.push_back(InsetBase::REF_CODE);
1275                 bv_funcs::gotoInset(bv_, tmp, true);
1276                 break;
1277         }
1278
1279         case LFUN_CHANGES_TRACK:
1280                 trackChanges();
1281                 break;
1282
1283         case LFUN_CHANGES_OUTPUT: {
1284                 bool const state = buffer_->params().output_changes;
1285                 buffer_->params().output_changes = !state;
1286                 break;
1287         }
1288
1289         case LFUN_CHANGES_MERGE:
1290                 if (lyx::find::findNextChange(bv_))
1291                         owner_->getDialogs().show("changes");
1292                 break;
1293
1294         case LFUN_ALL_CHANGES_ACCEPT: {
1295                 cursor_.reset(buffer_->inset());
1296 #ifdef WITH_WARNINGS
1297 #warning FIXME changes
1298 #endif
1299                 while (lyx::find::findNextChange(bv_))
1300                         bv_->getLyXText()->acceptChange(cursor_);
1301                 update();
1302                 break;
1303         }
1304
1305         case LFUN_ALL_CHANGES_REJECT: {
1306                 cursor_.reset(buffer_->inset());
1307 #ifdef WITH_WARNINGS
1308 #warning FIXME changes
1309 #endif
1310                 while (lyx::find::findNextChange(bv_))
1311                         bv_->getLyXText()->rejectChange(cursor_);
1312                 break;
1313         }
1314
1315         case LFUN_WORD_FIND:
1316                 lyx::find::find(bv_, cmd);
1317                 break;
1318
1319         case LFUN_WORD_REPLACE:
1320                 lyx::find::replace(bv_, cmd);
1321                 break;
1322
1323         case LFUN_MARK_OFF:
1324                 cur.clearSelection();
1325                 cur.resetAnchor();
1326                 cur.message(N_("Mark off"));
1327                 break;
1328
1329         case LFUN_MARK_ON:
1330                 cur.clearSelection();
1331                 cur.mark() = true;
1332                 cur.resetAnchor();
1333                 cur.message(N_("Mark on"));
1334                 break;
1335
1336         case LFUN_MARK_TOGGLE:
1337                 cur.clearSelection();
1338                 if (cur.mark()) {
1339                         cur.mark() = false;
1340                         cur.message(N_("Mark removed"));
1341                 } else {
1342                         cur.mark() = true;
1343                         cur.message(N_("Mark set"));
1344                 }
1345                 cur.resetAnchor();
1346                 break;
1347
1348         case LFUN_SCREEN_RECENTER:
1349                 center();
1350                 break;
1351
1352         case LFUN_BIBTEX_DATABASE_ADD: {
1353                 LCursor tmpcur = cursor_;
1354                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1355                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1356                                                 InsetBase::BIBTEX_CODE);
1357                 if (inset) {
1358                         if (inset->addDatabase(cmd.argument))
1359                                 buffer_->updateBibfilesCache();
1360                 }
1361                 break;
1362         }
1363
1364         case LFUN_BIBTEX_DATABASE_DEL: {
1365                 LCursor tmpcur = cursor_;
1366                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
1367                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1368                                                 InsetBase::BIBTEX_CODE);
1369                 if (inset) {
1370                         if (inset->delDatabase(cmd.argument))
1371                                 buffer_->updateBibfilesCache();
1372                 }
1373                 break;
1374         }
1375
1376         case LFUN_WORDS_COUNT: {
1377                 DocIterator from, to;
1378                 if (cur.selection()) {
1379                         from = cur.selectionBegin();
1380                         to = cur.selectionEnd();
1381                 } else {
1382                         from = doc_iterator_begin(buffer_->inset());
1383                         to = doc_iterator_end(buffer_->inset());
1384                 }
1385                 int const count = countWords(from, to);
1386                 string message;
1387                 if (count != 1) {
1388                         if (cur.selection())
1389                                 message = bformat(_("%1$d words in selection."),
1390                                           count);
1391                                 else
1392                                         message = bformat(_("%1$d words in document."),
1393                                                           count);
1394                 }
1395                 else {
1396                         if (cur.selection())
1397                                 message = _("One word in selection.");
1398                         else
1399                                 message = _("One word in document.");
1400                 }
1401
1402                 Alert::information(_("Count words"), message);
1403         }
1404                 break;
1405
1406         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1407                 // turn compression on/off
1408                 buffer_->params().compressed = !buffer_->params().compressed;
1409                 break;
1410
1411         default:
1412                 return false;
1413         }
1414
1415         return true;
1416 }
1417
1418
1419 ViewMetricsInfo BufferView::Pimpl::metrics(bool singlepar)
1420 {
1421         // Remove old position cache
1422         theCoords.clear();
1423         BufferView & bv = *bv_;
1424         LyXText * const text = bv.text();
1425         lyx::pit_type size = int(text->paragraphs().size());
1426
1427         if (anchor_ref_ > int(text->paragraphs().size() - 1)) {
1428                 anchor_ref_ = int(text->paragraphs().size() - 1);
1429                 offset_ref_ = 0;
1430         }
1431
1432         lyx::pit_type const pit = anchor_ref_;
1433         int pit1 = pit;
1434         int pit2 = pit;
1435         size_t const npit = text->paragraphs().size();
1436
1437         // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1438         // the (main text, not inset!) paragraph containing the cursor.
1439         // (if this paragraph contains insets etc., rebreaking will
1440         // recursively descend)
1441         if (!singlepar || pit == cursor_.bottom().pit())
1442                 text->redoParagraph(pit);
1443         int y0 = text->getPar(pit).ascent() - offset_ref_;
1444
1445         // Redo paragraphs above anchor if necessary; again, in Single Par
1446         // mode, only if we encounter the (main text) one having the cursor.
1447         int y1 = y0;
1448         while (y1 > 0 && pit1 > 0) {
1449                 y1 -= text->getPar(pit1).ascent();
1450                 --pit1;
1451                 if (!singlepar || pit1 == cursor_.bottom().pit())
1452                         text->redoParagraph(pit1);
1453                 y1 -= text->getPar(pit1).descent();
1454         }
1455
1456
1457         // Take care of ascent of first line
1458         y1 -= text->getPar(pit1).ascent();
1459
1460         // Normalize anchor for next time
1461         anchor_ref_ = pit1;
1462         offset_ref_ = -y1;
1463
1464         // Grey at the beginning is ugly
1465         if (pit1 == 0 && y1 > 0) {
1466                 y0 -= y1;
1467                 y1 = 0;
1468                 anchor_ref_ = 0;
1469         }
1470
1471         // Redo paragraphs below the anchor if necessary. Single par mode:
1472         // only the one containing the cursor if encountered.
1473         int y2 = y0;
1474         while (y2 < bv.workHeight() && pit2 < int(npit) - 1) {
1475                 y2 += text->getPar(pit2).descent();
1476                 ++pit2;
1477                 if (!singlepar || pit2 == cursor_.bottom().pit())
1478                         text->redoParagraph(pit2);
1479                 y2 += text->getPar(pit2).ascent();
1480         }
1481
1482         // Take care of descent of last line
1483         y2 += text->getPar(pit2).descent();
1484
1485         // The coordinates of all these paragraphs are correct, cache them
1486         int y = y1;
1487         for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1488                 y += text->getPar(pit).ascent();
1489                 theCoords.parPos()[text][pit] = Point(0, y);
1490                 if (singlepar && pit == cursor_.bottom().pit()) {
1491                         // In Single Paragraph mode, collect here the
1492                         // y1 and y2 of the (one) paragraph the cursor is in
1493                         y1 = y - text->getPar(pit).ascent();
1494                         y2 = y + text->getPar(pit).descent();
1495                 }
1496                 y += text->getPar(pit).descent();
1497         }
1498
1499         if (singlepar) {
1500                 // collect cursor paragraph iter bounds
1501                 pit1 = cursor_.bottom().pit();
1502                 pit2 = cursor_.bottom().pit();
1503         }
1504
1505         lyxerr[Debug::DEBUG]
1506                 << BOOST_CURRENT_FUNCTION
1507                 << " y1: " << y1
1508                 << " y2: " << y2
1509                 << " pit1: " << pit1
1510                 << " pit2: " << pit2
1511                 << " npit: " << npit
1512                 << " singlepar: " << singlepar
1513                 << "size: " << size
1514                 << endl;
1515
1516         return ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1517 }