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