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