]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
4982e2dc2004013992ab10a068aad31dc60922a8
[lyx.git] / src / BufferView.cpp
1 /**
2  * \file BufferView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "BranchList.h"
20 #include "Buffer.h"
21 #include "buffer_funcs.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "CoordCache.h"
25 #include "Cursor.h"
26 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
29 #include "factory.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "Intl.h"
34 #include "InsetIterator.h"
35 #include "Language.h"
36 #include "LaTeXFeatures.h"
37 #include "LyX.h"
38 #include "lyxfind.h"
39 #include "LyXFunc.h"
40 #include "Layout.h"
41 #include "LyXRC.h"
42 #include "MetricsInfo.h"
43 #include "Paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
47 #include "Session.h"
48 #include "Text.h"
49 #include "TextClass.h"
50 #include "TextMetrics.h"
51 #include "TexRow.h"
52 #include "TocBackend.h"
53 #include "VSpace.h"
54 #include "WordLangTuple.h"
55
56 #include "insets/InsetBibtex.h"
57 #include "insets/InsetCommand.h" // ChangeRefs
58 #include "insets/InsetExternal.h"
59 #include "insets/InsetGraphics.h"
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
62 #include "insets/InsetNote.h"
63
64 #include "frontends/alert.h"
65 #include "frontends/Application.h"
66 #include "frontends/Delegates.h"
67 #include "frontends/FontMetrics.h"
68 #include "frontends/Painter.h"
69 #include "frontends/Selection.h"
70
71 #include "graphics/Previews.h"
72
73 #include "support/convert.h"
74 #include "support/debug.h"
75 #include "support/ExceptionMessage.h"
76 #include "support/filetools.h"
77 #include "support/gettext.h"
78 #include "support/lstrings.h"
79 #include "support/Package.h"
80 #include "support/types.h"
81
82 #include <cerrno>
83 #include <fstream>
84 #include <functional>
85 #include <iterator>
86 #include <vector>
87
88 using namespace std;
89 using namespace lyx::support;
90
91 namespace lyx {
92
93 namespace Alert = frontend::Alert;
94
95 namespace {
96
97 /// Return an inset of this class if it exists at the current cursor position
98 template <class T>
99 T * getInsetByCode(Cursor const & cur, InsetCode code)
100 {
101         DocIterator it = cur;
102         Inset * inset = it.nextInset();
103         if (inset && inset->lyxCode() == code)
104                 return static_cast<T*>(inset);
105         return 0;
106 }
107
108
109 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
110         bool same_content);
111
112 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
113         docstring const & contents)
114 {
115         DocIterator tmpdit = dit;
116
117         while (tmpdit) {
118                 Inset const * inset = tmpdit.nextInset();
119                 if (inset
120                     && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
121                     && (contents.empty() ||
122                     static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
123                         dit = tmpdit;
124                         return true;
125                 }
126                 tmpdit.forwardInset();
127         }
128
129         return false;
130 }
131
132
133 /// Looks for next inset with one of the given codes.
134 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
135         bool same_content)
136 {
137         docstring contents;
138         DocIterator tmpdit = dit;
139         tmpdit.forwardInset();
140         if (!tmpdit)
141                 return false;
142
143         if (same_content) {
144                 Inset const * inset = tmpdit.nextInset();
145                 if (inset
146                     && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
147                         contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
148                 }
149         }
150
151         if (!findNextInset(tmpdit, codes, contents)) {
152                 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
153                         Inset * inset = &tmpdit.bottom().inset();
154                         tmpdit = doc_iterator_begin(&inset->buffer(), inset);
155                         if (!findNextInset(tmpdit, codes, contents))
156                                 return false;
157                 } else {
158                         return false;
159                 }
160         }
161
162         dit = tmpdit;
163         return true;
164 }
165
166
167 /// Looks for next inset with the given code
168 void findInset(DocIterator & dit, InsetCode code, bool same_content)
169 {
170         findInset(dit, vector<InsetCode>(1, code), same_content);
171 }
172
173
174 /// Moves cursor to the next inset with one of the given codes.
175 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
176                bool same_content)
177 {
178         Cursor tmpcur = bv->cursor();
179         if (!findInset(tmpcur, codes, same_content)) {
180                 bv->cursor().message(_("No more insets"));
181                 return;
182         }
183
184         tmpcur.clearSelection();
185         bv->setCursor(tmpcur);
186         bv->showCursor();
187 }
188
189
190 /// Moves cursor to the next inset with given code.
191 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
192 {
193         gotoInset(bv, vector<InsetCode>(1, code), same_content);
194 }
195
196
197 /// A map from a Text to the associated text metrics
198 typedef map<Text const *, TextMetrics> TextMetricsCache;
199
200 enum ScreenUpdateStrategy {
201         NoScreenUpdate,
202         SingleParUpdate,
203         FullScreenUpdate,
204         DecorationUpdate
205 };
206
207 } // anon namespace
208
209
210 /////////////////////////////////////////////////////////////////////
211 //
212 // BufferView
213 //
214 /////////////////////////////////////////////////////////////////////
215
216 struct BufferView::Private
217 {
218         Private(BufferView & bv): wh_(0), cursor_(bv),
219                 anchor_pit_(0), anchor_ypos_(0),
220                 inlineCompletionUniqueChars_(0),
221                 last_inset_(0), gui_(0)
222         {}
223
224         ///
225         ScrollbarParameters scrollbarParameters_;
226         ///
227         ScreenUpdateStrategy update_strategy_;
228         ///
229         CoordCache coord_cache_;
230
231         /// Estimated average par height for scrollbar.
232         int wh_;
233         /// this is used to handle XSelection events in the right manner.
234         struct {
235                 CursorSlice cursor;
236                 CursorSlice anchor;
237                 bool set;
238         } xsel_cache_;
239         ///
240         Cursor cursor_;
241         ///
242         pit_type anchor_pit_;
243         ///
244         int anchor_ypos_;
245         ///
246         vector<int> par_height_;
247
248         ///
249         DocIterator inlineCompletionPos_;
250         ///
251         docstring inlineCompletion_;
252         ///
253         size_t inlineCompletionUniqueChars_;
254
255         /// keyboard mapping object.
256         Intl intl_;
257
258         /// last visited inset.
259         /** kept to send setMouseHover(false).
260           * Not owned, so don't delete.
261           */
262         Inset * last_inset_;
263
264         mutable TextMetricsCache text_metrics_;
265
266         /// Whom to notify.
267         /** Not owned, so don't delete.
268           */
269         frontend::GuiBufferViewDelegate * gui_;
270
271         /// Cache for Find Next
272         FuncRequest search_request_cache_;
273 };
274
275
276 BufferView::BufferView(Buffer & buf)
277         : width_(0), height_(0), full_screen_(false), buffer_(buf),
278       d(new Private(*this))
279 {
280         d->xsel_cache_.set = false;
281         d->intl_.initKeyMapper(lyxrc.use_kbmap);
282
283         d->cursor_.setBuffer(&buf);
284         d->cursor_.push(buffer_.inset());
285         d->cursor_.resetAnchor();
286         d->cursor_.setCurrentFont();
287
288         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
289                 thePreviews().generateBufferPreviews(buffer_);
290 }
291
292
293 BufferView::~BufferView()
294 {
295         // current buffer is going to be switched-off, save cursor pos
296         // Ideally, the whole cursor stack should be saved, but session
297         // currently can only handle bottom (whole document) level pit and pos.
298         // That is to say, if a cursor is in a nested inset, it will be
299         // restore to the left of the top level inset.
300         LastFilePosSection::FilePos fp;
301         fp.pit = d->cursor_.bottom().pit();
302         fp.pos = d->cursor_.bottom().pos();
303         theSession().lastFilePos().save(buffer_.fileName(), fp);
304
305         delete d;
306 }
307
308
309 int BufferView::rightMargin() const
310 {
311         // The additional test for the case the outliner is opened.
312         if (!full_screen_ ||
313                 !lyxrc.full_screen_limit ||
314                 width_ < lyxrc.full_screen_width + 20)
315                         return 10;
316
317         return (width_ - lyxrc.full_screen_width) / 2;
318 }
319
320
321 int BufferView::leftMargin() const
322 {
323         return rightMargin();
324 }
325
326
327 bool BufferView::isTopScreen() const
328 {
329         return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
330 }
331
332
333 bool BufferView::isBottomScreen() const
334 {
335         return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
336 }
337
338
339 Intl & BufferView::getIntl()
340 {
341         return d->intl_;
342 }
343
344
345 Intl const & BufferView::getIntl() const
346 {
347         return d->intl_;
348 }
349
350
351 CoordCache & BufferView::coordCache()
352 {
353         return d->coord_cache_;
354 }
355
356
357 CoordCache const & BufferView::coordCache() const
358 {
359         return d->coord_cache_;
360 }
361
362
363 Buffer & BufferView::buffer()
364 {
365         return buffer_;
366 }
367
368
369 Buffer const & BufferView::buffer() const
370 {
371         return buffer_;
372 }
373
374
375 bool BufferView::fitCursor()
376 {
377         if (cursorStatus(d->cursor_) == CUR_INSIDE) {
378                 frontend::FontMetrics const & fm =
379                         theFontMetrics(d->cursor_.getFont().fontInfo());
380                 int const asc = fm.maxAscent();
381                 int const des = fm.maxDescent();
382                 Point const p = getPos(d->cursor_, d->cursor_.boundary());
383                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
384                         return false;
385         }
386         return true;
387 }
388
389
390 void BufferView::processUpdateFlags(Update::flags flags)
391 {
392         // last_inset_ points to the last visited inset. This pointer may become
393         // invalid because of keyboard editing. Since all such operations
394         // causes screen update(), I reset last_inset_ to avoid such a problem.
395         d->last_inset_ = 0;
396         // This is close to a hot-path.
397         LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
398                 << "[fitcursor = " << (flags & Update::FitCursor)
399                 << ", forceupdate = " << (flags & Update::Force)
400                 << ", singlepar = " << (flags & Update::SinglePar)
401                 << "]  buffer: " << &buffer_);
402
403         buffer_.updateMacros();
404
405         // Now do the first drawing step if needed. This consists on updating
406         // the CoordCache in updateMetrics().
407         // The second drawing step is done in WorkArea::redraw() if needed.
408
409         // Case when no explicit update is requested.
410         if (!flags) {
411                 // no need to redraw anything.
412                 d->update_strategy_ = NoScreenUpdate;
413                 return;
414         }
415
416         if (flags == Update::Decoration) {
417                 d->update_strategy_ = DecorationUpdate;
418                 buffer_.changed();
419                 return;
420         }
421
422         if (flags == Update::FitCursor
423                 || flags == (Update::Decoration | Update::FitCursor)) {
424                 // tell the frontend to update the screen if needed.
425                 if (fitCursor()) {
426                         showCursor();
427                         return;
428                 }
429                 if (flags & Update::Decoration) {
430                         d->update_strategy_ = DecorationUpdate;
431                         buffer_.changed();
432                         return;
433                 }
434                 // no screen update is needed.
435                 d->update_strategy_ = NoScreenUpdate;
436                 return;
437         }
438
439         bool const full_metrics = flags & Update::Force || !singleParUpdate();
440
441         if (full_metrics)
442                 // We have to update the full screen metrics.
443                 updateMetrics();
444
445         if (!(flags & Update::FitCursor)) {
446                 // Nothing to do anymore. Trigger a redraw and return
447                 buffer_.changed();
448                 return;
449         }
450
451         // updateMetrics() does not update paragraph position
452         // This is done at draw() time. So we need a redraw!
453         buffer_.changed();
454
455         if (fitCursor()) {
456                 // The cursor is off screen so ensure it is visible.
457                 // refresh it:
458                 showCursor();
459         }
460 }
461
462
463 void BufferView::updateScrollbar()
464 {
465         if (height_ == 0 && width_ == 0)
466                 return;
467
468         // We prefer fixed size line scrolling.
469         d->scrollbarParameters_.single_step = defaultRowHeight();
470         // We prefer full screen page scrolling.
471         d->scrollbarParameters_.page_step = height_;
472
473         Text & t = buffer_.text();
474         TextMetrics & tm = d->text_metrics_[&t];                
475
476         LYXERR(Debug::GUI, " Updating scrollbar: height: "
477                 << t.paragraphs().size()
478                 << " curr par: " << d->cursor_.bottom().pit()
479                 << " default height " << defaultRowHeight());
480
481         size_t const parsize = t.paragraphs().size();
482         if (d->par_height_.size() != parsize) {
483                 d->par_height_.clear();
484                 // FIXME: We assume a default paragraph height of 2 rows. This
485                 // should probably be pondered with the screen width.
486                 d->par_height_.resize(parsize, defaultRowHeight() * 2);
487         }
488
489         // Look at paragraph heights on-screen
490         pair<pit_type, ParagraphMetrics const *> first = tm.first();
491         pair<pit_type, ParagraphMetrics const *> last = tm.last();
492         for (pit_type pit = first.first; pit <= last.first; ++pit) {
493                 d->par_height_[pit] = tm.parMetrics(pit).height();
494                 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
495                         << d->par_height_[pit]);
496         }
497
498         int top_pos = first.second->position() - first.second->ascent();
499         int bottom_pos = last.second->position() + last.second->descent();
500         bool first_visible = first.first == 0 && top_pos >= 0;
501         bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
502         if (first_visible && last_visible) {
503                 d->scrollbarParameters_.min = 0;
504                 d->scrollbarParameters_.max = 0;
505                 return;
506         }
507
508         d->scrollbarParameters_.min = top_pos;
509         for (size_t i = 0; i != size_t(first.first); ++i)
510                 d->scrollbarParameters_.min -= d->par_height_[i];
511         d->scrollbarParameters_.max = bottom_pos;
512         for (size_t i = last.first + 1; i != parsize; ++i)
513                 d->scrollbarParameters_.max += d->par_height_[i];
514
515         d->scrollbarParameters_.position = 0;
516         // The reference is the top position so we remove one page.
517         d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
518 }
519
520
521 ScrollbarParameters const & BufferView::scrollbarParameters() const
522 {
523         return d->scrollbarParameters_;
524 }
525
526
527 docstring BufferView::toolTip(int x, int y) const
528 {
529         // Get inset under mouse, if there is one.
530         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
531         if (!covering_inset)
532                 // No inset, no tooltip...
533                 return docstring();
534         return covering_inset->toolTip(*this, x, y);
535 }
536
537
538 docstring BufferView::contextMenu(int x, int y) const
539 {
540         //If there is a selection, return the containing inset menu
541         if (d->cursor_.selection())
542                 return d->cursor_.inset().contextMenu(*this, x, y);
543
544         // Get inset under mouse, if there is one.
545         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
546         if (covering_inset)
547                 return covering_inset->contextMenu(*this, x, y);
548
549         return buffer_.inset().contextMenu(*this, x, y);
550 }
551
552
553 void BufferView::scrollDocView(int value)
554 {
555         int const offset = value - d->scrollbarParameters_.position;
556
557         // No scrolling at all? No need to redraw anything
558         if (offset == 0)
559                 return;
560
561         // If the offset is less than 2 screen height, prefer to scroll instead.
562         if (abs(offset) <= 2 * height_) {
563                 d->anchor_ypos_ -= offset;
564                 updateMetrics();
565                 buffer_.changed();
566                 return;
567         }
568
569         // cut off at the top
570         if (value <= d->scrollbarParameters_.min) {
571                 DocIterator dit = doc_iterator_begin(&buffer_);
572                 showCursor(dit);
573                 LYXERR(Debug::SCROLLING, "scroll to top");
574                 return;
575         }
576
577         // cut off at the bottom
578         if (value >= d->scrollbarParameters_.max) {
579                 DocIterator dit = doc_iterator_end(&buffer_);
580                 dit.backwardPos();
581                 showCursor(dit);
582                 LYXERR(Debug::SCROLLING, "scroll to bottom");
583                 return;
584         }
585
586         // find paragraph at target position
587         int par_pos = d->scrollbarParameters_.min;
588         pit_type i = 0;
589         for (; i != int(d->par_height_.size()); ++i) {
590                 par_pos += d->par_height_[i];
591                 if (par_pos >= value)
592                         break;
593         }
594
595         if (par_pos < value) {
596                 // It seems we didn't find the correct pit so stay on the safe side and
597                 // scroll to bottom.
598                 LYXERR0("scrolling position not found!");
599                 scrollDocView(d->scrollbarParameters_.max);
600                 return;
601         }
602
603         DocIterator dit = doc_iterator_begin(&buffer_);
604         dit.pit() = i;
605         LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
606         showCursor(dit);
607 }
608
609
610 // FIXME: this method is not working well.
611 void BufferView::setCursorFromScrollbar()
612 {
613         TextMetrics & tm = d->text_metrics_[&buffer_.text()];
614
615         int const height = 2 * defaultRowHeight();
616         int const first = height;
617         int const last = height_ - height;
618         int newy = 0;
619         Cursor const & oldcur = d->cursor_;
620
621         switch (cursorStatus(oldcur)) {
622         case CUR_ABOVE:
623                 newy = first;
624                 break;
625         case CUR_BELOW:
626                 newy = last;
627                 break;
628         case CUR_INSIDE:
629                 int const y = getPos(oldcur, oldcur.boundary()).y_;
630                 newy = min(last, max(y, first));
631                 if (y == newy) 
632                         return;
633         }
634         // We reset the cursor because cursorStatus() does not
635         // work when the cursor is within mathed.
636         Cursor cur(*this);
637         cur.reset(buffer_.inset());
638         tm.setCursorFromCoordinates(cur, 0, newy);
639
640         // update the bufferview cursor and notify insets
641         // FIXME: Care about the d->cursor_ flags to redraw if needed
642         Cursor old = d->cursor_;
643         mouseSetCursor(cur);
644         bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
645         if (badcursor)
646                 d->cursor_.fixIfBroken();
647 }
648
649
650 Change const BufferView::getCurrentChange() const
651 {
652         if (!d->cursor_.selection())
653                 return Change(Change::UNCHANGED);
654
655         DocIterator dit = d->cursor_.selectionBegin();
656         return dit.paragraph().lookupChange(dit.pos());
657 }
658
659
660 // this could be used elsewhere as well?
661 // FIXME: This does not work within mathed!
662 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
663 {
664         Point const p = getPos(dit, dit.boundary());
665         if (p.y_ < 0)
666                 return CUR_ABOVE;
667         if (p.y_ > workHeight())
668                 return CUR_BELOW;
669         return CUR_INSIDE;
670 }
671
672
673 void BufferView::saveBookmark(unsigned int idx)
674 {
675         // tenatively save bookmark, id and pos will be used to
676         // acturately locate a bookmark in a 'live' lyx session.
677         // pit and pos will be updated with bottom level pit/pos
678         // when lyx exits.
679         theSession().bookmarks().save(
680                 buffer_.fileName(),
681                 d->cursor_.bottom().pit(),
682                 d->cursor_.bottom().pos(),
683                 d->cursor_.paragraph().id(),
684                 d->cursor_.pos(),
685                 idx
686         );
687         if (idx)
688                 // emit message signal.
689                 message(_("Save bookmark"));
690 }
691
692
693 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
694         int top_id, pos_type top_pos)
695 {
696         bool success = false;
697         DocIterator dit;
698
699         d->cursor_.clearSelection();
700
701         // if a valid par_id is given, try it first
702         // This is the case for a 'live' bookmark when unique paragraph ID
703         // is used to track bookmarks.
704         if (top_id > 0) {
705                 dit = buffer_.getParFromID(top_id);
706                 if (!dit.atEnd()) {
707                         dit.pos() = min(dit.paragraph().size(), top_pos);
708                         // Some slices of the iterator may not be
709                         // reachable (e.g. closed collapsable inset)
710                         // so the dociterator may need to be
711                         // shortened. Otherwise, setCursor may crash
712                         // lyx when the cursor can not be set to these
713                         // insets.
714                         size_t const n = dit.depth();
715                         for (size_t i = 0; i < n; ++i)
716                                 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
717                                         dit.resize(i);
718                                         break;
719                                 }
720                         success = true;
721                 }
722         }
723
724         // if top_id == 0, or searching through top_id failed
725         // This is the case for a 'restored' bookmark when only bottom
726         // (document level) pit was saved. Because of this, bookmark
727         // restoration is inaccurate. If a bookmark was within an inset,
728         // it will be restored to the left of the outmost inset that contains
729         // the bookmark.
730         if (bottom_pit < int(buffer_.paragraphs().size())) {
731                 dit = doc_iterator_begin(&buffer_);
732                                 
733                 dit.pit() = bottom_pit;
734                 dit.pos() = min(bottom_pos, dit.paragraph().size());
735                 success = true;
736         }
737
738         if (success) {
739                 // Note: only bottom (document) level pit is set.
740                 setCursor(dit);
741                 // set the current font.
742                 d->cursor_.setCurrentFont();
743                 // To center the screen on this new position we need the
744                 // paragraph position which is computed at draw() time.
745                 // So we need a redraw!
746                 buffer_.changed();
747                 if (fitCursor())
748                         showCursor();
749         }
750
751         return success;
752 }
753
754
755 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
756 {
757         if (lyxrc.rtl_support) {
758                 if (d->cursor_.real_current_font.isRightToLeft()) {
759                         if (d->intl_.keymap == Intl::PRIMARY)
760                                 d->intl_.keyMapSec();
761                 } else {
762                         if (d->intl_.keymap == Intl::SECONDARY)
763                                 d->intl_.keyMapPrim();
764                 }
765         }
766
767         d->intl_.getTransManager().translateAndInsert(c, t, cur);
768 }
769
770
771 int BufferView::workWidth() const
772 {
773         return width_;
774 }
775
776
777 void BufferView::showCursor()
778 {
779         showCursor(d->cursor_);
780 }
781
782
783 void BufferView::showCursor(DocIterator const & dit)
784 {
785         // We are not properly started yet, delay until resizing is
786         // done.
787         if (height_ == 0)
788                 return;
789
790         LYXERR(Debug::SCROLLING, "recentering!");
791
792         CursorSlice const & bot = dit.bottom();
793         TextMetrics & tm = d->text_metrics_[bot.text()];
794
795         pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
796         int bot_pit = bot.pit();
797         if (bot_pit > max_pit) {
798                 // FIXME: Why does this happen?
799                 LYXERR0("bottom pit is greater that max pit: "
800                         << bot_pit << " > " << max_pit);
801                 bot_pit = max_pit;
802         }
803
804         if (bot_pit == tm.first().first - 1)
805                 tm.newParMetricsUp();
806         else if (bot_pit == tm.last().first + 1)
807                 tm.newParMetricsDown();
808
809         if (tm.contains(bot_pit)) {
810                 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
811                 LASSERT(!pm.rows().empty(), /**/);
812                 // FIXME: smooth scrolling doesn't work in mathed.
813                 CursorSlice const & cs = dit.innerTextSlice();
814                 int offset = coordOffset(dit, dit.boundary()).y_;
815                 int ypos = pm.position() + offset;
816                 Dimension const & row_dim =
817                         pm.getRow(cs.pos(), dit.boundary()).dimension();
818                 int scrolled = 0;
819                 if (ypos - row_dim.ascent() < 0)
820                         scrolled = scrollUp(- ypos + row_dim.ascent());
821                 else if (ypos + row_dim.descent() > height_)
822                         scrolled = scrollDown(ypos - defaultRowHeight());
823
824                 // else, nothing to do, the cursor is already visible so we just return.
825                 if (scrolled != 0) {
826                         updateMetrics();
827                         buffer_.changed();
828                 }
829                 return;
830         }
831
832         // fix inline completion position
833         if (d->inlineCompletionPos_.fixIfBroken())
834                 d->inlineCompletionPos_ = DocIterator();
835
836         tm.redoParagraph(bot_pit);
837         ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
838         int offset = coordOffset(dit, dit.boundary()).y_;
839
840         d->anchor_pit_ = bot_pit;
841         CursorSlice const & cs = dit.innerTextSlice();
842         Dimension const & row_dim =
843                 pm.getRow(cs.pos(), dit.boundary()).dimension();
844
845         if (d->anchor_pit_ == 0)
846                 d->anchor_ypos_ = offset + pm.ascent();
847         else if (d->anchor_pit_ == max_pit)
848                 d->anchor_ypos_ = height_ - offset - row_dim.descent();
849         else if (offset > height_)
850                 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
851         else
852                 d->anchor_ypos_ = defaultRowHeight() * 2;
853
854         updateMetrics();
855         buffer_.changed();
856 }
857
858
859 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
860 {
861         FuncStatus flag;
862
863         Cursor & cur = d->cursor_;
864
865         switch (cmd.action) {
866
867         case LFUN_UNDO:
868                 flag.setEnabled(buffer_.undo().hasUndoStack());
869                 break;
870         case LFUN_REDO:
871                 flag.setEnabled(buffer_.undo().hasRedoStack());
872                 break;
873         case LFUN_FILE_INSERT:
874         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
875         case LFUN_FILE_INSERT_PLAINTEXT:
876         case LFUN_BOOKMARK_SAVE:
877                 // FIXME: Actually, these LFUNS should be moved to Text
878                 flag.setEnabled(cur.inTexted());
879                 break;
880         case LFUN_FONT_STATE:
881         case LFUN_LABEL_INSERT:
882         case LFUN_INFO_INSERT:
883         case LFUN_INSET_EDIT:
884         case LFUN_PARAGRAPH_GOTO:
885         case LFUN_NOTE_NEXT:
886         case LFUN_REFERENCE_NEXT:
887         case LFUN_WORD_FIND:
888         case LFUN_WORD_FINDADV:
889         case LFUN_WORD_REPLACE:
890         case LFUN_MARK_OFF:
891         case LFUN_MARK_ON:
892         case LFUN_MARK_TOGGLE:
893         case LFUN_SCREEN_RECENTER:
894         case LFUN_BIBTEX_DATABASE_ADD:
895         case LFUN_BIBTEX_DATABASE_DEL:
896         case LFUN_NOTES_MUTATE:
897         case LFUN_ALL_INSETS_TOGGLE:
898         case LFUN_STATISTICS:
899                 flag.setEnabled(true);
900                 break;
901
902         // @todo Test if current WorkArea is the search WorkArea
903         case LFUN_REGEXP_MODE:
904                 flag.setEnabled(! this->cursor().inRegexped());
905                 break;
906
907         case LFUN_COPY_LABEL_AS_REF: {
908                 // if there is an inset at cursor, see whether it
909                 // handles the lfun
910                 Inset * inset = cur.nextInset();
911                 if (!inset || !inset->getStatus(cur, cmd, flag))
912                         flag.setEnabled(false);
913                 break;
914         }
915
916         case LFUN_NEXT_INSET_TOGGLE: 
917         case LFUN_NEXT_INSET_MODIFY: {
918                 // this is the real function we want to invoke
919                 FuncRequest tmpcmd = cmd;
920                 tmpcmd.action = (cmd.action == LFUN_NEXT_INSET_TOGGLE) 
921                         ? LFUN_INSET_TOGGLE : LFUN_INSET_MODIFY;
922                 // if there is an inset at cursor, see whether it
923                 // handles the lfun, other start from scratch
924                 Inset * inset = cur.nextInset();
925                 if (!inset || !inset->getStatus(cur, tmpcmd, flag))
926                         flag = lyx::getStatus(tmpcmd);
927                 break;
928         }
929
930         case LFUN_LABEL_GOTO: {
931                 flag.setEnabled(!cmd.argument().empty()
932                     || getInsetByCode<InsetRef>(cur, REF_CODE));
933                 break;
934         }
935
936         case LFUN_CHANGES_TRACK:
937                 flag.setEnabled(true);
938                 flag.setOnOff(buffer_.params().trackChanges);
939                 break;
940
941         case LFUN_CHANGES_OUTPUT:
942                 flag.setEnabled(true);
943                 flag.setOnOff(buffer_.params().outputChanges);
944                 break;
945
946         case LFUN_CHANGES_MERGE:
947         case LFUN_CHANGE_NEXT:
948         case LFUN_ALL_CHANGES_ACCEPT:
949         case LFUN_ALL_CHANGES_REJECT:
950                 // TODO: context-sensitive enabling of LFUNs
951                 // In principle, these command should only be enabled if there
952                 // is a change in the document. However, without proper
953                 // optimizations, this will inevitably result in poor performance.
954                 flag.setEnabled(true);
955                 break;
956
957         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
958                 flag.setOnOff(buffer_.params().compressed);
959                 break;
960         }
961         
962         case LFUN_SCREEN_UP:
963         case LFUN_SCREEN_DOWN:
964         case LFUN_SCROLL:
965         case LFUN_SCREEN_UP_SELECT:
966         case LFUN_SCREEN_DOWN_SELECT:
967                 flag.setEnabled(true);
968                 break;
969
970         case LFUN_LAYOUT_TABULAR:
971                 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
972                 break;
973
974         case LFUN_LAYOUT:
975                 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
976                 break;
977
978         case LFUN_LAYOUT_PARAGRAPH:
979                 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
980                 break;
981
982         case LFUN_INSET_SETTINGS: {
983                 InsetCode code = cur.inset().lyxCode();
984                 if (cmd.getArg(0) == insetName(code)) {
985                         flag.setEnabled(true);
986                         break;
987                 }
988                 bool enable = false;
989                 InsetCode next_code = cur.nextInset()
990                         ? cur.nextInset()->lyxCode() : NO_CODE;
991                 //FIXME: remove these special cases:
992                 switch (next_code) {
993                         case TABULAR_CODE:
994                         case ERT_CODE:
995                         case FLOAT_CODE:
996                         case WRAP_CODE:
997                         case NOTE_CODE:
998                         case BRANCH_CODE:
999                         case PHANTOM_CODE:
1000                         case BOX_CODE:
1001                         case LISTINGS_CODE:
1002                                 enable = (cmd.argument().empty() ||
1003                                           cmd.getArg(0) == insetName(next_code));
1004                                 break;
1005                         default:
1006                                 break;
1007                 }
1008                 flag.setEnabled(enable);
1009                 break;
1010         }
1011
1012         case LFUN_DIALOG_SHOW_NEW_INSET:
1013                 flag.setEnabled(cur.inset().lyxCode() != ERT_CODE &&
1014                         cur.inset().lyxCode() != LISTINGS_CODE);
1015                 if (cur.inset().lyxCode() == CAPTION_CODE) {
1016                         FuncStatus flag;
1017                         if (cur.inset().getStatus(cur, cmd, flag))
1018                                 return flag;
1019                 }
1020                 break;
1021
1022         case LFUN_BRANCH_ACTIVATE: 
1023         case LFUN_BRANCH_DEACTIVATE: {
1024                 bool enable = false;
1025                 docstring const branchName = cmd.argument();
1026                 if (!branchName.empty())
1027                         enable = buffer_.params().branchlist().find(branchName);
1028                 flag.setEnabled(enable);
1029                 break;
1030         }
1031
1032         default:
1033                 flag.setEnabled(false);
1034         }
1035
1036         return flag;
1037 }
1038
1039
1040 bool BufferView::dispatch(FuncRequest const & cmd)
1041 {
1042         //lyxerr << [ cmd = " << cmd << "]" << endl;
1043
1044         // Make sure that the cached BufferView is correct.
1045         LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1046                 << " arg[" << to_utf8(cmd.argument()) << ']'
1047                 << " x[" << cmd.x << ']'
1048                 << " y[" << cmd.y << ']'
1049                 << " button[" << cmd.button() << ']');
1050
1051         Cursor & cur = d->cursor_;
1052
1053         switch (cmd.action) {
1054
1055         case LFUN_UNDO:
1056                 cur.message(_("Undo"));
1057                 cur.clearSelection();
1058                 if (!cur.textUndo())
1059                         cur.message(_("No further undo information"));
1060                 else
1061                         processUpdateFlags(Update::Force | Update::FitCursor);
1062                 break;
1063
1064         case LFUN_REDO:
1065                 cur.message(_("Redo"));
1066                 cur.clearSelection();
1067                 if (!cur.textRedo())
1068                         cur.message(_("No further redo information"));
1069                 else
1070                         processUpdateFlags(Update::Force | Update::FitCursor);
1071                 break;
1072
1073         case LFUN_FONT_STATE:
1074                 cur.message(cur.currentState());
1075                 break;
1076
1077         case LFUN_BOOKMARK_SAVE:
1078                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1079                 break;
1080
1081         case LFUN_LABEL_GOTO: {
1082                 docstring label = cmd.argument();
1083                 if (label.empty()) {
1084                         InsetRef * inset =
1085                                 getInsetByCode<InsetRef>(d->cursor_, REF_CODE);
1086                         if (inset) {
1087                                 label = inset->getParam("reference");
1088                                 // persistent=false: use temp_bookmark
1089                                 saveBookmark(0);
1090                         }
1091                 }
1092                 if (!label.empty())
1093                         gotoLabel(label);
1094                 break;
1095         }
1096         
1097         case LFUN_INSET_EDIT: {
1098                 FuncRequest fr(cmd);
1099                 // if there is an inset at cursor, see whether it
1100                 // can be modified.
1101                 Inset * inset = cur.nextInset();
1102                 if (inset)
1103                         inset->dispatch(cur, fr);
1104                 // if it did not work, try the underlying inset.
1105                 if (!inset || !cur.result().dispatched())
1106                         cur.dispatch(cmd);
1107
1108                 // FIXME I'm adding the last break to solve a crash,
1109                 // but that is obviously not right.
1110                 if (!cur.result().dispatched())
1111                         // It did not work too; no action needed.
1112                         break;
1113                 break;
1114         }
1115
1116         case LFUN_PARAGRAPH_GOTO: {
1117                 int const id = convert<int>(cmd.getArg(0));
1118                 int const pos = convert<int>(cmd.getArg(1));
1119                 int i = 0;
1120                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1121                         b = theBufferList().next(b)) {
1122
1123                         DocIterator dit = b->getParFromID(id);
1124                         if (dit.atEnd()) {
1125                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1126                                 ++i;
1127                                 continue;
1128                         }
1129                         LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1130                                 << " found in buffer `"
1131                                 << b->absFileName() << "'.");
1132
1133                         if (b == &buffer_) {
1134                                 // Set the cursor
1135                                 dit.pos() = pos;
1136                                 setCursor(dit);
1137                                 processUpdateFlags(Update::Force | Update::FitCursor);
1138                         } else {
1139                                 // Switch to other buffer view and resend cmd
1140                                 theLyXFunc().dispatch(FuncRequest(
1141                                         LFUN_BUFFER_SWITCH, b->absFileName()));
1142                                 theLyXFunc().dispatch(cmd);
1143                         }
1144                         break;
1145                 }
1146                 break;
1147         }
1148
1149         case LFUN_NOTE_NEXT:
1150                 gotoInset(this, NOTE_CODE, false);
1151                 break;
1152
1153         case LFUN_REFERENCE_NEXT: {
1154                 vector<InsetCode> tmp;
1155                 tmp.push_back(LABEL_CODE);
1156                 tmp.push_back(REF_CODE);
1157                 gotoInset(this, tmp, true);
1158                 break;
1159         }
1160
1161         case LFUN_CHANGES_TRACK:
1162                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1163                 break;
1164
1165         case LFUN_CHANGES_OUTPUT:
1166                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1167                 if (buffer_.params().outputChanges) {
1168                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1169                         bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1170                                           LaTeXFeatures::isAvailable("xcolor");
1171
1172                         if (!dvipost && !xcolorulem) {
1173                                 Alert::warning(_("Changes not shown in LaTeX output"),
1174                                                _("Changes will not be highlighted in LaTeX output, "
1175                                                  "because neither dvipost nor xcolor/ulem are installed.\n"
1176                                                  "Please install these packages or redefine "
1177                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1178                         } else if (!xcolorulem) {
1179                                 Alert::warning(_("Changes not shown in LaTeX output"),
1180                                                _("Changes will not be highlighted in LaTeX output "
1181                                                  "when using pdflatex, because xcolor and ulem are not installed.\n"
1182                                                  "Please install both packages or redefine "
1183                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1184                         }
1185                 }
1186                 break;
1187
1188         case LFUN_CHANGE_NEXT:
1189                 findNextChange(this);
1190                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1191                 processUpdateFlags(Update::Force | Update::FitCursor);
1192                 break;
1193
1194         case LFUN_CHANGES_MERGE:
1195                 if (findNextChange(this)) {
1196                         processUpdateFlags(Update::Force | Update::FitCursor);
1197                         showDialog("changes");
1198                 }
1199                 break;
1200
1201         case LFUN_ALL_CHANGES_ACCEPT:
1202                 // select complete document
1203                 d->cursor_.reset(buffer_.inset());
1204                 d->cursor_.selHandle(true);
1205                 buffer_.text().cursorBottom(d->cursor_);
1206                 // accept everything in a single step to support atomic undo
1207                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1208                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1209                 processUpdateFlags(Update::Force | Update::FitCursor);
1210                 break;
1211
1212         case LFUN_ALL_CHANGES_REJECT:
1213                 // select complete document
1214                 d->cursor_.reset(buffer_.inset());
1215                 d->cursor_.selHandle(true);
1216                 buffer_.text().cursorBottom(d->cursor_);
1217                 // reject everything in a single step to support atomic undo
1218                 // Note: reject does not work recursively; the user may have to repeat the operation
1219                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1220                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1221                 processUpdateFlags(Update::Force | Update::FitCursor);
1222                 break;
1223
1224         case LFUN_WORD_FIND: {
1225                 FuncRequest req = cmd;
1226                 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1227                         req = d->search_request_cache_;
1228                 if (req.argument().empty()) {
1229                         theLyXFunc().dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1230                         break;
1231                 }
1232                 if (find(this, req))
1233                         showCursor();
1234                 else
1235                         message(_("String not found!"));
1236                 d->search_request_cache_ = req;
1237                 break;
1238         }
1239
1240         case LFUN_WORD_REPLACE: {
1241                 bool has_deleted = false;
1242                 if (cur.selection()) {
1243                         DocIterator beg = cur.selectionBegin();
1244                         DocIterator end = cur.selectionEnd();
1245                         if (beg.pit() == end.pit()) {
1246                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1247                                         if (cur.paragraph().isDeleted(p))
1248                                                 has_deleted = true;
1249                                 }
1250                         }
1251                 }
1252                 replace(this, cmd, has_deleted);
1253                 break;
1254         }
1255
1256         case LFUN_WORD_FINDADV:
1257                 findAdv(this, cmd);
1258                 break;
1259
1260         case LFUN_MARK_OFF:
1261                 cur.clearSelection();
1262                 cur.resetAnchor();
1263                 cur.message(from_utf8(N_("Mark off")));
1264                 break;
1265
1266         case LFUN_MARK_ON:
1267                 cur.clearSelection();
1268                 cur.setMark(true);
1269                 cur.resetAnchor();
1270                 cur.message(from_utf8(N_("Mark on")));
1271                 break;
1272
1273         case LFUN_MARK_TOGGLE:
1274                 cur.clearSelection();
1275                 if (cur.mark()) {
1276                         cur.setMark(false);
1277                         cur.message(from_utf8(N_("Mark removed")));
1278                 } else {
1279                         cur.setMark(true);
1280                         cur.message(from_utf8(N_("Mark set")));
1281                 }
1282                 cur.resetAnchor();
1283                 break;
1284
1285         case LFUN_SCREEN_RECENTER:
1286                 showCursor();
1287                 break;
1288
1289         case LFUN_BIBTEX_DATABASE_ADD: {
1290                 Cursor tmpcur = d->cursor_;
1291                 findInset(tmpcur, BIBTEX_CODE, false);
1292                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1293                                                 BIBTEX_CODE);
1294                 if (inset) {
1295                         if (inset->addDatabase(cmd.argument()))
1296                                 buffer_.updateBibfilesCache();
1297                 }
1298                 break;
1299         }
1300
1301         case LFUN_BIBTEX_DATABASE_DEL: {
1302                 Cursor tmpcur = d->cursor_;
1303                 findInset(tmpcur, BIBTEX_CODE, false);
1304                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1305                                                 BIBTEX_CODE);
1306                 if (inset) {
1307                         if (inset->delDatabase(cmd.argument()))
1308                                 buffer_.updateBibfilesCache();
1309                 }
1310                 break;
1311         }
1312
1313         case LFUN_STATISTICS: {
1314                 DocIterator from, to;
1315                 if (cur.selection()) {
1316                         from = cur.selectionBegin();
1317                         to = cur.selectionEnd();
1318                 } else {
1319                         from = doc_iterator_begin(&buffer_);
1320                         to = doc_iterator_end(&buffer_);
1321                 }
1322                 int const words = countWords(from, to);
1323                 int const chars = countChars(from, to, false);
1324                 int const chars_blanks = countChars(from, to, true);
1325                 docstring message;
1326                 if (cur.selection())
1327                         message = _("Statistics for the selection:");
1328                 else
1329                         message = _("Statistics for the document:");
1330                 message += "\n\n";
1331                 if (words != 1)
1332                         message += bformat(_("%1$d words"), words);
1333                 else
1334                         message += _("One word");
1335                 message += "\n";
1336                 if (chars_blanks != 1)
1337                         message += bformat(_("%1$d characters (including blanks)"),
1338                                           chars_blanks);
1339                 else
1340                         message += _("One character (including blanks)");
1341                 message += "\n";
1342                 if (chars != 1)
1343                         message += bformat(_("%1$d characters (excluding blanks)"),
1344                                           chars);
1345                 else
1346                         message += _("One character (excluding blanks)");
1347
1348                 Alert::information(_("Statistics"), message);
1349         }
1350                 break;
1351
1352         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1353                 // turn compression on/off
1354                 buffer_.params().compressed = !buffer_.params().compressed;
1355                 break;
1356         case LFUN_COPY_LABEL_AS_REF: {
1357                 // if there is an inset at cursor, try to copy it
1358                 Inset * inset = cur.nextInset();
1359                 if (inset) {
1360                         FuncRequest tmpcmd = cmd;
1361                         inset->dispatch(cur, tmpcmd);
1362                 }
1363                 if (!cur.result().dispatched())
1364                         // It did not work too; no action needed.
1365                         break;
1366                 cur.clearSelection();
1367                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1368                 break;
1369         }
1370         case LFUN_NEXT_INSET_TOGGLE: {
1371                 // create the the real function we want to invoke
1372                 FuncRequest tmpcmd = cmd;
1373                 tmpcmd.action = LFUN_INSET_TOGGLE;
1374                 // if there is an inset at cursor, see whether it
1375                 // wants to toggle.
1376                 Inset * inset = cur.nextInset();
1377                 if (inset) {
1378                         if (inset->isActive()) {
1379                                 Cursor tmpcur = cur;
1380                                 tmpcur.pushBackward(*inset);
1381                                 inset->dispatch(tmpcur, tmpcmd);
1382                                 if (tmpcur.result().dispatched())
1383                                         cur.dispatched();
1384                         } else 
1385                                 inset->dispatch(cur, tmpcmd);
1386                 }
1387                 // if it did not work, try the underlying inset.
1388                 if (!inset || !cur.result().dispatched())
1389                         cur.dispatch(tmpcmd);
1390
1391                 if (!cur.result().dispatched())
1392                         // It did not work too; no action needed.
1393                         break;
1394                 cur.clearSelection();
1395                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1396                 break;
1397         }
1398
1399         case LFUN_NEXT_INSET_MODIFY: {
1400                 // create the the real function we want to invoke
1401                 FuncRequest tmpcmd = cmd;
1402                 tmpcmd.action = LFUN_INSET_MODIFY;
1403                 // if there is an inset at cursor, see whether it
1404                 // can be modified.
1405                 Inset * inset = cur.nextInset();
1406                 if (inset) {
1407                         cur.recordUndo();
1408                         inset->dispatch(cur, tmpcmd);
1409                 }
1410                 // if it did not work, try the underlying inset.
1411                 if (!inset || !cur.result().dispatched()) {
1412                         cur.recordUndo();
1413                         cur.dispatch(tmpcmd);
1414                 }
1415
1416                 if (!cur.result().dispatched())
1417                         // It did not work too; no action needed.
1418                         break;
1419                 cur.clearSelection();
1420                 processUpdateFlags(Update::Force | Update::FitCursor);
1421                 break;
1422         }
1423
1424         case LFUN_SCREEN_UP:
1425         case LFUN_SCREEN_DOWN: {
1426                 Point p = getPos(cur, cur.boundary());
1427                 if (p.y_ < 0 || p.y_ > height_) {
1428                         // The cursor is off-screen so recenter before proceeding.
1429                         showCursor();
1430                         p = getPos(cur, cur.boundary());
1431                 }
1432                 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1433                         ? - height_ : height_);
1434                 if (cmd.action == LFUN_SCREEN_UP && scrolled > - height_)
1435                         p = Point(0, 0);
1436                 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1437                         p = Point(width_, height_);
1438                 cur.reset(buffer_.inset());
1439                 updateMetrics();
1440                 buffer_.changed();
1441                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1442                 //FIXME: what to do with cur.x_target()?
1443                 cur.finishUndo();
1444                 break;
1445         }
1446
1447         case LFUN_SCROLL:
1448                 lfunScroll(cmd);
1449                 break;
1450
1451         case LFUN_SCREEN_UP_SELECT: {
1452                 cur.selHandle(true);
1453                 if (isTopScreen()) {
1454                         lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1455                         cur.finishUndo();
1456                         break;
1457                 }
1458                 int y = getPos(cur, cur.boundary()).y_;
1459                 int const ymin = y - height_ + defaultRowHeight();
1460                 while (y > ymin && cur.up())
1461                         y = getPos(cur, cur.boundary()).y_;
1462
1463                 cur.finishUndo();
1464                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1465                 break;
1466         }
1467
1468         case LFUN_SCREEN_DOWN_SELECT: {
1469                 cur.selHandle(true);
1470                 if (isBottomScreen()) {
1471                         lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1472                         cur.finishUndo();
1473                         break;
1474                 }
1475                 int y = getPos(cur, cur.boundary()).y_;
1476                 int const ymax = y + height_ - defaultRowHeight();
1477                 while (y < ymax && cur.down())
1478                         y = getPos(cur, cur.boundary()).y_;
1479
1480                 cur.finishUndo();
1481                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1482                 break;
1483         }
1484
1485         case LFUN_BRANCH_ACTIVATE:
1486         case LFUN_BRANCH_DEACTIVATE:
1487                 buffer_.dispatch(cmd);
1488                 processUpdateFlags(Update::Force);
1489                 break;
1490
1491         // This could be rewriten using some command like forall <insetname> <command>
1492         // once the insets refactoring is done.
1493         case LFUN_NOTES_MUTATE: {
1494                 if (cmd.argument().empty())
1495                         break;
1496
1497                 if (mutateNotes(cur, cmd.getArg(0), cmd.getArg(1))) {
1498                         processUpdateFlags(Update::Force);
1499                 }
1500                 break;
1501         }
1502
1503         case LFUN_ALL_INSETS_TOGGLE: {
1504                 string action;
1505                 string const name = split(to_utf8(cmd.argument()), action, ' ');
1506                 InsetCode const inset_code = insetCode(name);
1507
1508                 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1509
1510                 Inset & inset = cur.buffer()->inset();
1511                 InsetIterator it  = inset_iterator_begin(inset);
1512                 InsetIterator const end = inset_iterator_end(inset);
1513                 for (; it != end; ++it) {
1514                         if (it->asInsetCollapsable()
1515                             && (inset_code == NO_CODE
1516                             || inset_code == it->lyxCode())) {
1517                                 Cursor tmpcur = cur;
1518                                 tmpcur.pushBackward(*it);
1519                                 it->dispatch(tmpcur, fr);
1520                         }
1521                 }
1522                 processUpdateFlags(Update::Force | Update::FitCursor);
1523                 break;
1524         }
1525
1526         default:
1527                 return false;
1528         }
1529
1530         return true;
1531 }
1532
1533
1534 docstring const BufferView::requestSelection()
1535 {
1536         Cursor & cur = d->cursor_;
1537
1538         LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1539         if (!cur.selection()) {
1540                 d->xsel_cache_.set = false;
1541                 return docstring();
1542         }
1543
1544         LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1545         if (!d->xsel_cache_.set ||
1546             cur.top() != d->xsel_cache_.cursor ||
1547             cur.anchor_.top() != d->xsel_cache_.anchor)
1548         {
1549                 d->xsel_cache_.cursor = cur.top();
1550                 d->xsel_cache_.anchor = cur.anchor_.top();
1551                 d->xsel_cache_.set = cur.selection();
1552                 return cur.selectionAsString(false);
1553         }
1554         return docstring();
1555 }
1556
1557
1558 void BufferView::clearSelection()
1559 {
1560         d->cursor_.clearSelection();
1561         // Clear the selection buffer. Otherwise a subsequent
1562         // middle-mouse-button paste would use the selection buffer,
1563         // not the more current external selection.
1564         cap::clearSelection();
1565         d->xsel_cache_.set = false;
1566         // The buffer did not really change, but this causes the
1567         // redraw we need because we cleared the selection above.
1568         buffer_.changed();
1569 }
1570
1571
1572 void BufferView::resize(int width, int height)
1573 {
1574         // Update from work area
1575         width_ = width;
1576         height_ = height;
1577
1578         // Clear the paragraph height cache.
1579         d->par_height_.clear();
1580         // Redo the metrics.
1581         updateMetrics();
1582 }
1583
1584
1585 Inset const * BufferView::getCoveringInset(Text const & text,
1586                 int x, int y) const
1587 {
1588         TextMetrics & tm = d->text_metrics_[&text];
1589         Inset * inset = tm.checkInsetHit(x, y);
1590         if (!inset)
1591                 return 0;
1592
1593         if (!inset->descendable())
1594                 // No need to go further down if the inset is not
1595                 // descendable.
1596                 return inset;
1597
1598         size_t cell_number = inset->nargs();
1599         // Check all the inner cell.
1600         for (size_t i = 0; i != cell_number; ++i) {
1601                 Text const * inner_text = inset->getText(i);
1602                 if (inner_text) {
1603                         // Try deeper.
1604                         Inset const * inset_deeper =
1605                                 getCoveringInset(*inner_text, x, y);
1606                         if (inset_deeper)
1607                                 return inset_deeper;
1608                 }
1609         }
1610
1611         return inset;
1612 }
1613
1614
1615 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1616 {
1617         //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1618
1619         // This is only called for mouse related events including
1620         // LFUN_FILE_OPEN generated by drag-and-drop.
1621         FuncRequest cmd = cmd0;
1622
1623         Cursor old = cursor();
1624         Cursor cur(*this);
1625         cur.push(buffer_.inset());
1626         cur.setSelection(d->cursor_.selection());
1627
1628         // Either the inset under the cursor or the
1629         // surrounding Text will handle this event.
1630
1631         // make sure we stay within the screen...
1632         cmd.y = min(max(cmd.y, -1), height_);
1633
1634         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1635
1636                 // Get inset under mouse, if there is one.
1637                 Inset const * covering_inset =
1638                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1639                 if (covering_inset == d->last_inset_)
1640                         // Same inset, no need to do anything...
1641                         return;
1642
1643                 bool need_redraw = false;
1644                 // const_cast because of setMouseHover().
1645                 Inset * inset = const_cast<Inset *>(covering_inset);
1646                 if (d->last_inset_)
1647                         // Remove the hint on the last hovered inset (if any).
1648                         need_redraw |= d->last_inset_->setMouseHover(false);
1649                 if (inset)
1650                         // Highlighted the newly hovered inset (if any).
1651                         need_redraw |= inset->setMouseHover(true);
1652                 d->last_inset_ = inset;
1653                 if (!need_redraw)
1654                         return;
1655
1656                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1657                         << cmd.x << ", " << cmd.y << ")");
1658
1659                 d->update_strategy_ = DecorationUpdate;
1660
1661                 // This event (moving without mouse click) is not passed further.
1662                 // This should be changed if it is further utilized.
1663                 buffer_.changed();
1664                 return;
1665         }
1666
1667         // Build temporary cursor.
1668         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1669
1670         // Put anchor at the same position.
1671         cur.resetAnchor();
1672
1673         cur.beginUndoGroup();
1674
1675         // Try to dispatch to an non-editable inset near this position
1676         // via the temp cursor. If the inset wishes to change the real
1677         // cursor it has to do so explicitly by using
1678         //  cur.bv().cursor() = cur;  (or similar)
1679         if (inset)
1680                 inset->dispatch(cur, cmd);
1681
1682         // Now dispatch to the temporary cursor. If the real cursor should
1683         // be modified, the inset's dispatch has to do so explicitly.
1684         if (!inset || !cur.result().dispatched())
1685                 cur.dispatch(cmd);
1686
1687         cur.endUndoGroup();
1688
1689         // Notify left insets
1690         if (cur != old) {
1691                 old.fixIfBroken();
1692                 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
1693                 if (badcursor)
1694                         cursor().fixIfBroken();
1695         }
1696         
1697         // Do we have a selection?
1698         theSelection().haveSelection(cursor().selection());
1699
1700         // If the command has been dispatched,
1701         if (cur.result().dispatched() || cur.result().update())
1702                 processUpdateFlags(cur.result().update());
1703 }
1704
1705
1706 void BufferView::lfunScroll(FuncRequest const & cmd)
1707 {
1708         string const scroll_type = cmd.getArg(0);
1709         int const scroll_step = 
1710                 (scroll_type == "line") ? d->scrollbarParameters_.single_step
1711                 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
1712         if (scroll_step == 0)
1713                 return;
1714         string const scroll_quantity = cmd.getArg(1);
1715         if (scroll_quantity == "up")
1716                 scrollUp(scroll_step);
1717         else if (scroll_quantity == "down")
1718                 scrollDown(scroll_step);
1719         else {
1720                 int const scroll_value = convert<int>(scroll_quantity);
1721                 if (scroll_value)
1722                         scroll(scroll_step * scroll_value);
1723         }
1724         updateMetrics();
1725         buffer_.changed();
1726 }
1727
1728
1729 int BufferView::scroll(int y)
1730 {
1731         if (y > 0)
1732                 return scrollDown(y);
1733         if (y < 0)
1734                 return scrollUp(-y);
1735         return 0;
1736 }
1737
1738
1739 int BufferView::scrollDown(int offset)
1740 {
1741         Text * text = &buffer_.text();
1742         TextMetrics & tm = d->text_metrics_[text];
1743         int ymax = height_ + offset;
1744         while (true) {
1745                 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1746                 int bottom_pos = last.second->position() + last.second->descent();
1747                 if (last.first + 1 == int(text->paragraphs().size())) {
1748                         if (bottom_pos <= height_)
1749                                 return 0;
1750                         offset = min(offset, bottom_pos - height_);
1751                         break;
1752                 }
1753                 if (bottom_pos > ymax)
1754                         break;
1755                 tm.newParMetricsDown();
1756         }
1757         d->anchor_ypos_ -= offset;
1758         return -offset;
1759 }
1760
1761
1762 int BufferView::scrollUp(int offset)
1763 {
1764         Text * text = &buffer_.text();
1765         TextMetrics & tm = d->text_metrics_[text];
1766         int ymin = - offset;
1767         while (true) {
1768                 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1769                 int top_pos = first.second->position() - first.second->ascent();
1770                 if (first.first == 0) {
1771                         if (top_pos >= 0)
1772                                 return 0;
1773                         offset = min(offset, - top_pos);
1774                         break;
1775                 }
1776                 if (top_pos < ymin)
1777                         break;
1778                 tm.newParMetricsUp();
1779         }
1780         d->anchor_ypos_ += offset;
1781         return offset;
1782 }
1783
1784
1785 void BufferView::setCursorFromRow(int row)
1786 {
1787         int tmpid = -1;
1788         int tmppos = -1;
1789
1790         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1791
1792         d->cursor_.reset(buffer_.inset());
1793         if (tmpid == -1)
1794                 buffer_.text().setCursor(d->cursor_, 0, 0);
1795         else
1796                 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1797 }
1798
1799
1800 bool BufferView::setCursorFromInset(Inset const * inset)
1801 {
1802         // are we already there?
1803         if (cursor().nextInset() == inset)
1804                 return true;
1805
1806         // Inset is not at cursor position. Find it in the document.
1807         Cursor cur(*this);
1808         cur.reset(buffer().inset());
1809         while (cur && cur.nextInset() != inset)
1810                 cur.forwardInset();
1811
1812         if (cur) {
1813                 setCursor(cur);
1814                 return true;
1815         }
1816         return false;
1817 }
1818
1819
1820 void BufferView::gotoLabel(docstring const & label)
1821 {
1822         std::vector<Buffer const *> bufs = buffer().allRelatives();
1823         std::vector<Buffer const *>::iterator it = bufs.begin();
1824         for (; it != bufs.end(); ++it) {
1825                 Buffer const * buf = *it;
1826
1827                 // find label
1828                 Toc & toc = buf->tocBackend().toc("label");
1829                 TocIterator toc_it = toc.begin();
1830                 TocIterator end = toc.end();
1831                 for (; toc_it != end; ++toc_it) {
1832                         if (label == toc_it->str()) {
1833                                 dispatch(toc_it->action());
1834                                 return;
1835                         }
1836                 }
1837         }
1838 }
1839
1840
1841 TextMetrics const & BufferView::textMetrics(Text const * t) const
1842 {
1843         return const_cast<BufferView *>(this)->textMetrics(t);
1844 }
1845
1846
1847 TextMetrics & BufferView::textMetrics(Text const * t)
1848 {
1849         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
1850         if (tmc_it == d->text_metrics_.end()) {
1851                 tmc_it = d->text_metrics_.insert(
1852                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1853         }
1854         return tmc_it->second;
1855 }
1856
1857
1858 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1859                 pit_type pit) const
1860 {
1861         return textMetrics(t).parMetrics(pit);
1862 }
1863
1864
1865 int BufferView::workHeight() const
1866 {
1867         return height_;
1868 }
1869
1870
1871 void BufferView::setCursor(DocIterator const & dit)
1872 {
1873         size_t const n = dit.depth();
1874         for (size_t i = 0; i < n; ++i)
1875                 dit[i].inset().edit(d->cursor_, true);
1876
1877         d->cursor_.setCursor(dit);
1878         d->cursor_.setSelection(false);
1879 }
1880
1881
1882 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1883 {
1884         // Would be wrong to delete anything if we have a selection.
1885         if (cur.selection())
1886                 return false;
1887
1888         bool need_anchor_change = false;
1889         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1890                 need_anchor_change);
1891
1892         if (need_anchor_change)
1893                 cur.resetAnchor();
1894
1895         if (!changed)
1896                 return false;
1897
1898         d->cursor_ = cur;
1899
1900         buffer_.updateLabels();
1901
1902         updateMetrics();
1903         buffer_.changed();
1904         return true;
1905 }
1906
1907
1908 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1909 {
1910         LASSERT(&cur.bv() == this, /**/);
1911
1912         if (!select)
1913                 // this event will clear selection so we save selection for
1914                 // persistent selection
1915                 cap::saveSelection(cursor());
1916
1917         // Has the cursor just left the inset?
1918         bool leftinset = (&d->cursor_.inset() != &cur.inset());
1919         if (leftinset)
1920                 d->cursor_.fixIfBroken();
1921
1922         // FIXME: shift-mouse selection doesn't work well across insets.
1923         bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1924
1925         // do the dEPM magic if needed
1926         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1927         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1928         // the leftinset bool would not be necessary (badcursor instead).
1929         bool update = leftinset;
1930         if (!do_selection && d->cursor_.inTexted())
1931                 update |= checkDepm(cur, d->cursor_);
1932
1933         d->cursor_.setCursor(cur);
1934         d->cursor_.boundary(cur.boundary());
1935         if (do_selection)
1936                 d->cursor_.setSelection();
1937         else
1938                 d->cursor_.clearSelection();
1939
1940         d->cursor_.finishUndo();
1941         d->cursor_.setCurrentFont();
1942         return update;
1943 }
1944
1945
1946 void BufferView::putSelectionAt(DocIterator const & cur,
1947                                 int length, bool backwards)
1948 {
1949         d->cursor_.clearSelection();
1950
1951         setCursor(cur);
1952
1953         if (length) {
1954                 if (backwards) {
1955                         d->cursor_.pos() += length;
1956                         d->cursor_.setSelection(d->cursor_, -length);
1957                 } else
1958                         d->cursor_.setSelection(d->cursor_, length);
1959         }
1960         // Ensure a redraw happens in any case because the new selection could 
1961         // possibly be on the same screen as the previous selection.
1962         processUpdateFlags(Update::Force | Update::FitCursor);
1963 }
1964
1965
1966 Cursor & BufferView::cursor()
1967 {
1968         return d->cursor_;
1969 }
1970
1971
1972 Cursor const & BufferView::cursor() const
1973 {
1974         return d->cursor_;
1975 }
1976
1977
1978 pit_type BufferView::anchor_ref() const
1979 {
1980         return d->anchor_pit_;
1981 }
1982
1983
1984 bool BufferView::singleParUpdate()
1985 {
1986         Text & buftext = buffer_.text();
1987         pit_type const bottom_pit = d->cursor_.bottom().pit();
1988         TextMetrics & tm = textMetrics(&buftext);
1989         int old_height = tm.parMetrics(bottom_pit).height();
1990
1991         // make sure inline completion pointer is ok
1992         if (d->inlineCompletionPos_.fixIfBroken())
1993                 d->inlineCompletionPos_ = DocIterator();
1994
1995         // In Single Paragraph mode, rebreak only
1996         // the (main text, not inset!) paragraph containing the cursor.
1997         // (if this paragraph contains insets etc., rebreaking will
1998         // recursively descend)
1999         tm.redoParagraph(bottom_pit);
2000         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
2001         if (pm.height() != old_height)
2002                 // Paragraph height has changed so we cannot proceed to
2003                 // the singlePar optimisation.
2004                 return false;
2005
2006         d->update_strategy_ = SingleParUpdate;
2007
2008         LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2009                 << " y2: " << pm.position() + pm.descent()
2010                 << " pit: " << bottom_pit
2011                 << " singlepar: 1");
2012         return true;
2013 }
2014
2015
2016 void BufferView::updateMetrics()
2017 {
2018         if (height_ == 0 || width_ == 0)
2019                 return;
2020
2021         Text & buftext = buffer_.text();
2022         pit_type const npit = int(buftext.paragraphs().size());
2023
2024         // Clear out the position cache in case of full screen redraw,
2025         d->coord_cache_.clear();
2026
2027         // Clear out paragraph metrics to avoid having invalid metrics
2028         // in the cache from paragraphs not relayouted below
2029         // The complete text metrics will be redone.
2030         d->text_metrics_.clear();
2031
2032         TextMetrics & tm = textMetrics(&buftext);
2033
2034         // make sure inline completion pointer is ok
2035         if (d->inlineCompletionPos_.fixIfBroken())
2036                 d->inlineCompletionPos_ = DocIterator();
2037         
2038         if (d->anchor_pit_ >= npit)
2039                 // The anchor pit must have been deleted...
2040                 d->anchor_pit_ = npit - 1;
2041
2042         // Rebreak anchor paragraph.
2043         tm.redoParagraph(d->anchor_pit_);
2044         ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2045         
2046         // position anchor
2047         if (d->anchor_pit_ == 0) {
2048                 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2049                 
2050                 // Complete buffer visible? Then it's easy.
2051                 if (scrollRange == 0)
2052                         d->anchor_ypos_ = anchor_pm.ascent();
2053         
2054                 // FIXME: Some clever handling needed to show
2055                 // the _first_ paragraph up to the top if the cursor is
2056                 // in the first line.
2057         }               
2058         anchor_pm.setPosition(d->anchor_ypos_);
2059
2060         LYXERR(Debug::PAINTING, "metrics: "
2061                 << " anchor pit = " << d->anchor_pit_
2062                 << " anchor ypos = " << d->anchor_ypos_);
2063
2064         // Redo paragraphs above anchor if necessary.
2065         int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2066         // We are now just above the anchor paragraph.
2067         pit_type pit1 = d->anchor_pit_ - 1;
2068         for (; pit1 >= 0 && y1 >= 0; --pit1) {
2069                 tm.redoParagraph(pit1);
2070                 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2071                 y1 -= pm.descent();
2072                 // Save the paragraph position in the cache.
2073                 pm.setPosition(y1);
2074                 y1 -= pm.ascent();
2075         }
2076
2077         // Redo paragraphs below the anchor if necessary.
2078         int y2 = d->anchor_ypos_ + anchor_pm.descent();
2079         // We are now just below the anchor paragraph.
2080         pit_type pit2 = d->anchor_pit_ + 1;
2081         for (; pit2 < npit && y2 <= height_; ++pit2) {
2082                 tm.redoParagraph(pit2);
2083                 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2084                 y2 += pm.ascent();
2085                 // Save the paragraph position in the cache.
2086                 pm.setPosition(y2);
2087                 y2 += pm.descent();
2088         }
2089
2090         LYXERR(Debug::PAINTING, "Metrics: "
2091                 << " anchor pit = " << d->anchor_pit_
2092                 << " anchor ypos = " << d->anchor_ypos_
2093                 << " y1 = " << y1
2094                 << " y2 = " << y2
2095                 << " pit1 = " << pit1
2096                 << " pit2 = " << pit2);
2097
2098         d->update_strategy_ = FullScreenUpdate;
2099
2100         if (lyxerr.debugging(Debug::WORKAREA)) {
2101                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2102                 d->coord_cache_.dump();
2103         }
2104 }
2105
2106
2107 void BufferView::insertLyXFile(FileName const & fname)
2108 {
2109         LASSERT(d->cursor_.inTexted(), /**/);
2110
2111         // Get absolute path of file and add ".lyx"
2112         // to the filename if necessary
2113         FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2114
2115         docstring const disp_fn = makeDisplayPath(filename.absFilename());
2116         // emit message signal.
2117         message(bformat(_("Inserting document %1$s..."), disp_fn));
2118
2119         docstring res;
2120         Buffer buf("", false);
2121         if (buf.loadLyXFile(filename)) {
2122                 ErrorList & el = buffer_.errorList("Parse");
2123                 // Copy the inserted document error list into the current buffer one.
2124                 el = buf.errorList("Parse");
2125                 buffer_.undo().recordUndo(d->cursor_);
2126                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2127                                              buf.params().documentClassPtr(), el);
2128                 res = _("Document %1$s inserted.");
2129         } else {
2130                 res = _("Could not insert document %1$s");
2131         }
2132
2133         updateMetrics();
2134         buffer_.changed();
2135         // emit message signal.
2136         message(bformat(res, disp_fn));
2137         buffer_.errors("Parse");
2138 }
2139
2140
2141 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2142 {
2143         int x = 0;
2144         int y = 0;
2145         int lastw = 0;
2146
2147         // Addup contribution of nested insets, from inside to outside,
2148         // keeping the outer paragraph for a special handling below
2149         for (size_t i = dit.depth() - 1; i >= 1; --i) {
2150                 CursorSlice const & sl = dit[i];
2151                 int xx = 0;
2152                 int yy = 0;
2153                 
2154                 // get relative position inside sl.inset()
2155                 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2156                 
2157                 // Make relative position inside of the edited inset relative to sl.inset()
2158                 x += xx;
2159                 y += yy;
2160                 
2161                 // In case of an RTL inset, the edited inset will be positioned to the left
2162                 // of xx:yy
2163                 if (sl.text()) {
2164                         bool boundary_i = boundary && i + 1 == dit.depth();
2165                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2166                         if (rtl)
2167                                 x -= lastw;
2168                 }
2169
2170                 // remember width for the case that sl.inset() is positioned in an RTL inset
2171                 if (i && dit[i - 1].text()) {
2172                         // If this Inset is inside a Text Inset, retrieve the Dimension
2173                         // from the containing text instead of using Inset::dimension() which
2174                         // might not be implemented.
2175                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2176                         // elimination of Inset::dim_ cache. This coordOffset() method needs
2177                         // to be rewritten in light of the new design.
2178                         Dimension const & dim = parMetrics(dit[i - 1].text(),
2179                                 dit[i - 1].pit()).insetDimension(&sl.inset());
2180                         lastw = dim.wid;
2181                 } else {
2182                         Dimension const dim = sl.inset().dimension(*this);
2183                         lastw = dim.wid;
2184                 }
2185                 
2186                 //lyxerr << "Cursor::getPos, i: "
2187                 // << i << " x: " << xx << " y: " << y << endl;
2188         }
2189
2190         // Add contribution of initial rows of outermost paragraph
2191         CursorSlice const & sl = dit[0];
2192         TextMetrics const & tm = textMetrics(sl.text());
2193         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2194         LASSERT(!pm.rows().empty(), /**/);
2195         y -= pm.rows()[0].ascent();
2196 #if 1
2197         // FIXME: document this mess
2198         size_t rend;
2199         if (sl.pos() > 0 && dit.depth() == 1) {
2200                 int pos = sl.pos();
2201                 if (pos && boundary)
2202                         --pos;
2203 //              lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2204                 rend = pm.pos2row(pos);
2205         } else
2206                 rend = pm.pos2row(sl.pos());
2207 #else
2208         size_t rend = pm.pos2row(sl.pos());
2209 #endif
2210         for (size_t rit = 0; rit != rend; ++rit)
2211                 y += pm.rows()[rit].height();
2212         y += pm.rows()[rend].ascent();
2213         
2214         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2215         
2216         // Make relative position from the nested inset now bufferview absolute.
2217         int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2218         x += xx;
2219         
2220         // In the RTL case place the nested inset at the left of the cursor in 
2221         // the outer paragraph
2222         bool boundary_1 = boundary && 1 == dit.depth();
2223         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2224         if (rtl)
2225                 x -= lastw;
2226         
2227         return Point(x, y);
2228 }
2229
2230
2231 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2232 {
2233         if (!paragraphVisible(dit))
2234                 return Point(-1, -1);
2235
2236         CursorSlice const & bot = dit.bottom();
2237         TextMetrics const & tm = textMetrics(bot.text());
2238
2239         Point p = coordOffset(dit, boundary); // offset from outer paragraph
2240         p.y_ += tm.parMetrics(bot.pit()).position();
2241         return p;
2242 }
2243
2244
2245 bool BufferView::paragraphVisible(DocIterator const & dit) const
2246 {
2247         CursorSlice const & bot = dit.bottom();
2248         TextMetrics const & tm = textMetrics(bot.text());
2249
2250         return tm.contains(bot.pit());
2251 }
2252
2253
2254 void BufferView::draw(frontend::Painter & pain)
2255 {
2256         if (height_ == 0 || width_ == 0)
2257                 return;
2258         LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2259
2260         Text & text = buffer_.text();
2261         TextMetrics const & tm = d->text_metrics_[&text];
2262         int const y = tm.first().second->position();
2263         PainterInfo pi(this, pain);
2264
2265         switch (d->update_strategy_) {
2266
2267         case NoScreenUpdate:
2268                 // If no screen painting is actually needed, only some the different
2269                 // coordinates of insets and paragraphs needs to be updated.
2270                 pi.full_repaint = true;
2271                 pi.pain.setDrawingEnabled(false);
2272                 tm.draw(pi, 0, y);
2273                 break;
2274
2275         case SingleParUpdate:
2276                 pi.full_repaint = false;
2277                 // In general, only the current row of the outermost paragraph
2278                 // will be redrawn. Particular cases where selection spans
2279                 // multiple paragraph are correctly detected in TextMetrics.
2280                 tm.draw(pi, 0, y);
2281                 break;
2282
2283         case DecorationUpdate:
2284                 // FIXME: We should also distinguish DecorationUpdate to avoid text
2285                 // drawing if possible. This is not possible to do easily right now
2286                 // because of the single backing pixmap.
2287
2288         case FullScreenUpdate:
2289                 // The whole screen, including insets, will be refreshed.
2290                 pi.full_repaint = true;
2291
2292                 // Clear background.
2293                 pain.fillRectangle(0, 0, width_, height_,
2294                         pi.backgroundColor(&buffer_.inset()));
2295
2296                 // Draw everything.
2297                 tm.draw(pi, 0, y);
2298
2299                 // and possibly grey out below
2300                 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2301                 int const y2 = lastpm.second->position() + lastpm.second->descent();
2302                 if (y2 < height_)
2303                         pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2304                 break;
2305         }
2306         LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING  ***");
2307
2308         // The scrollbar needs an update.
2309         updateScrollbar();
2310
2311         // Normalize anchor for next time
2312         pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2313         pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2314         for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2315                 ParagraphMetrics const & pm = tm.parMetrics(pit);
2316                 if (pm.position() + pm.descent() > 0) {
2317                         d->anchor_pit_ = pit;
2318                         d->anchor_ypos_ = pm.position();
2319                         break;
2320                 }
2321         }
2322         LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2323                 << "  anchor ypos = " << d->anchor_ypos_);
2324 }
2325
2326
2327 void BufferView::message(docstring const & msg)
2328 {
2329         if (d->gui_)
2330                 d->gui_->message(msg);
2331 }
2332
2333
2334 void BufferView::showDialog(string const & name)
2335 {
2336         if (d->gui_)
2337                 d->gui_->showDialog(name, string());
2338 }
2339
2340
2341 void BufferView::showDialog(string const & name,
2342         string const & data, Inset * inset)
2343 {
2344         if (d->gui_)
2345                 d->gui_->showDialog(name, data, inset);
2346 }
2347
2348
2349 void BufferView::updateDialog(string const & name, string const & data)
2350 {
2351         if (d->gui_)
2352                 d->gui_->updateDialog(name, data);
2353 }
2354
2355
2356 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2357 {
2358         d->gui_ = gui;
2359 }
2360
2361
2362 // FIXME: Move this out of BufferView again
2363 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2364 {
2365         if (!fname.isReadableFile()) {
2366                 docstring const error = from_ascii(strerror(errno));
2367                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2368                 docstring const text =
2369                   bformat(_("Could not read the specified document\n"
2370                             "%1$s\ndue to the error: %2$s"), file, error);
2371                 Alert::error(_("Could not read file"), text);
2372                 return docstring();
2373         }
2374
2375         if (!fname.isReadableFile()) {
2376                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2377                 docstring const text =
2378                   bformat(_("%1$s\n is not readable."), file);
2379                 Alert::error(_("Could not open file"), text);
2380                 return docstring();
2381         }
2382
2383         // FIXME UNICODE: We don't know the encoding of the file
2384         docstring file_content = fname.fileContents("UTF-8");
2385         if (file_content.empty()) {
2386                 Alert::error(_("Reading not UTF-8 encoded file"),
2387                              _("The file is not UTF-8 encoded.\n"
2388                                "It will be read as local 8Bit-encoded.\n"
2389                                "If this does not give the correct result\n"
2390                                "then please change the encoding of the file\n"
2391                                "to UTF-8 with a program other than LyX.\n"));
2392                 file_content = fname.fileContents("local8bit");
2393         }
2394
2395         return normalize_c(file_content);
2396 }
2397
2398
2399 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2400 {
2401         docstring const tmpstr = contentsOfPlaintextFile(f);
2402
2403         if (tmpstr.empty())
2404                 return;
2405
2406         Cursor & cur = cursor();
2407         cap::replaceSelection(cur);
2408         buffer_.undo().recordUndo(cur);
2409         if (asParagraph)
2410                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2411         else
2412                 cur.innerText()->insertStringAsLines(cur, tmpstr);
2413
2414         updateMetrics();
2415         buffer_.changed();
2416 }
2417
2418
2419 docstring const & BufferView::inlineCompletion() const
2420 {
2421         return d->inlineCompletion_;
2422 }
2423
2424
2425 size_t const & BufferView::inlineCompletionUniqueChars() const
2426 {
2427         return d->inlineCompletionUniqueChars_;
2428 }
2429
2430
2431 DocIterator const & BufferView::inlineCompletionPos() const
2432 {
2433         return d->inlineCompletionPos_;
2434 }
2435
2436
2437 bool samePar(DocIterator const & a, DocIterator const & b)
2438 {
2439         if (a.empty() && b.empty())
2440                 return true;
2441         if (a.empty() || b.empty())
2442                 return false;
2443         return &a.innerParagraph() == &b.innerParagraph();
2444 }
2445
2446
2447 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos, 
2448         docstring const & completion, size_t uniqueChars)
2449 {
2450         uniqueChars = min(completion.size(), uniqueChars);
2451         bool changed = d->inlineCompletion_ != completion
2452                 || d->inlineCompletionUniqueChars_ != uniqueChars;
2453         bool singlePar = true;
2454         d->inlineCompletion_ = completion;
2455         d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2456         
2457         //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2458         
2459         // at new position?
2460         DocIterator const & old = d->inlineCompletionPos_;
2461         if (old != pos) {
2462                 //lyxerr << "inlineCompletionPos changed" << std::endl;
2463                 // old or pos are in another paragraph?
2464                 if ((!samePar(cur, pos) && !pos.empty())
2465                     || (!samePar(cur, old) && !old.empty())) {
2466                         singlePar = false;
2467                         //lyxerr << "different paragraph" << std::endl;
2468                 }
2469                 d->inlineCompletionPos_ = pos;
2470         }
2471         
2472         // set update flags
2473         if (changed) {
2474                 if (singlePar && !(cur.disp_.update() & Update::Force))
2475                         cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2476                 else
2477                         cur.updateFlags(cur.disp_.update() | Update::Force);
2478         }
2479 }
2480
2481 } // namespace lyx