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