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