]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
Bug 5562: Fix command line output of subfigure insets by introducing new OutputParams...
[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 - height_ + row_dim.descent());
823                 // else, nothing to do, the cursor is already visible so we just return.
824                 if (scrolled != 0) {
825                         updateMetrics();
826                         buffer_.changed();
827                 }
828                 return;
829         }
830
831         // fix inline completion position
832         if (d->inlineCompletionPos_.fixIfBroken())
833                 d->inlineCompletionPos_ = DocIterator();
834
835         tm.redoParagraph(bot_pit);
836         ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
837         int offset = coordOffset(dit, dit.boundary()).y_;
838
839         d->anchor_pit_ = bot_pit;
840         CursorSlice const & cs = dit.innerTextSlice();
841         Dimension const & row_dim =
842                 pm.getRow(cs.pos(), dit.boundary()).dimension();
843
844         if (d->anchor_pit_ == 0)
845                 d->anchor_ypos_ = offset + pm.ascent();
846         else if (d->anchor_pit_ == max_pit)
847                 d->anchor_ypos_ = height_ - offset - row_dim.descent();
848         else
849                 d->anchor_ypos_ = defaultRowHeight() * 2 - offset - row_dim.descent();
850
851         updateMetrics();
852         buffer_.changed();
853 }
854
855
856 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
857 {
858         FuncStatus flag;
859
860         Cursor & cur = d->cursor_;
861
862         switch (cmd.action) {
863
864         case LFUN_UNDO:
865                 flag.setEnabled(buffer_.undo().hasUndoStack());
866                 break;
867         case LFUN_REDO:
868                 flag.setEnabled(buffer_.undo().hasRedoStack());
869                 break;
870         case LFUN_FILE_INSERT:
871         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
872         case LFUN_FILE_INSERT_PLAINTEXT:
873         case LFUN_BOOKMARK_SAVE:
874                 // FIXME: Actually, these LFUNS should be moved to Text
875                 flag.setEnabled(cur.inTexted());
876                 break;
877         case LFUN_FONT_STATE:
878         case LFUN_LABEL_INSERT:
879         case LFUN_INFO_INSERT:
880         case LFUN_INSET_EDIT:
881         case LFUN_PARAGRAPH_GOTO:
882         case LFUN_NOTE_NEXT:
883         case LFUN_REFERENCE_NEXT:
884         case LFUN_WORD_FIND:
885         case LFUN_WORD_FINDADV:
886         case LFUN_WORD_REPLACE:
887         case LFUN_MARK_OFF:
888         case LFUN_MARK_ON:
889         case LFUN_MARK_TOGGLE:
890         case LFUN_SCREEN_RECENTER:
891         case LFUN_BIBTEX_DATABASE_ADD:
892         case LFUN_BIBTEX_DATABASE_DEL:
893         case LFUN_NOTES_MUTATE:
894         case LFUN_ALL_INSETS_TOGGLE:
895         case LFUN_STATISTICS:
896                 flag.setEnabled(true);
897                 break;
898
899         // @todo Test if current WorkArea is the search WorkArea
900         case LFUN_REGEXP_MODE:
901                 flag.setEnabled(! this->cursor().inRegexped());
902                 break;
903
904         case LFUN_COPY_LABEL_AS_REF: {
905                 // if there is an inset at cursor, see whether it
906                 // handles the lfun
907                 Inset * inset = cur.nextInset();
908                 if (!inset || !inset->getStatus(cur, cmd, flag))
909                         flag.setEnabled(false);
910                 break;
911         }
912
913         case LFUN_NEXT_INSET_TOGGLE: 
914         case LFUN_NEXT_INSET_MODIFY: {
915                 // this is the real function we want to invoke
916                 FuncRequest tmpcmd = cmd;
917                 tmpcmd.action = (cmd.action == LFUN_NEXT_INSET_TOGGLE) 
918                         ? LFUN_INSET_TOGGLE : LFUN_INSET_MODIFY;
919                 // if there is an inset at cursor, see whether it
920                 // handles the lfun, other start from scratch
921                 Inset * inset = cur.nextInset();
922                 if (!inset || !inset->getStatus(cur, tmpcmd, flag))
923                         flag = lyx::getStatus(tmpcmd);
924                 break;
925         }
926
927         case LFUN_LABEL_GOTO: {
928                 flag.setEnabled(!cmd.argument().empty()
929                     || getInsetByCode<InsetRef>(cur, REF_CODE));
930                 break;
931         }
932
933         case LFUN_CHANGES_TRACK:
934                 flag.setEnabled(true);
935                 flag.setOnOff(buffer_.params().trackChanges);
936                 break;
937
938         case LFUN_CHANGES_OUTPUT:
939                 flag.setEnabled(true);
940                 flag.setOnOff(buffer_.params().outputChanges);
941                 break;
942
943         case LFUN_CHANGES_MERGE:
944         case LFUN_CHANGE_NEXT:
945         case LFUN_ALL_CHANGES_ACCEPT:
946         case LFUN_ALL_CHANGES_REJECT:
947                 // TODO: context-sensitive enabling of LFUNs
948                 // In principle, these command should only be enabled if there
949                 // is a change in the document. However, without proper
950                 // optimizations, this will inevitably result in poor performance.
951                 flag.setEnabled(true);
952                 break;
953
954         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
955                 flag.setOnOff(buffer_.params().compressed);
956                 break;
957         }
958         
959         case LFUN_SCREEN_UP:
960         case LFUN_SCREEN_DOWN:
961         case LFUN_SCROLL:
962         case LFUN_SCREEN_UP_SELECT:
963         case LFUN_SCREEN_DOWN_SELECT:
964                 flag.setEnabled(true);
965                 break;
966
967         case LFUN_LAYOUT_TABULAR:
968                 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
969                 break;
970
971         case LFUN_LAYOUT:
972                 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
973                 break;
974
975         case LFUN_LAYOUT_PARAGRAPH:
976                 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
977                 break;
978
979         case LFUN_INSET_SETTINGS: {
980                 InsetCode code = cur.inset().lyxCode();
981                 if (cmd.getArg(0) == insetName(code)) {
982                         flag.setEnabled(true);
983                         break;
984                 }
985                 bool enable = false;
986                 InsetCode next_code = cur.nextInset()
987                         ? cur.nextInset()->lyxCode() : NO_CODE;
988                 //FIXME: remove these special cases:
989                 switch (next_code) {
990                         case TABULAR_CODE:
991                         case ERT_CODE:
992                         case FLOAT_CODE:
993                         case WRAP_CODE:
994                         case NOTE_CODE:
995                         case BRANCH_CODE:
996                         case PHANTOM_CODE:
997                         case BOX_CODE:
998                         case LISTINGS_CODE:
999                                 enable = (cmd.argument().empty() ||
1000                                           cmd.getArg(0) == insetName(next_code));
1001                                 break;
1002                         default:
1003                                 break;
1004                 }
1005                 flag.setEnabled(enable);
1006                 break;
1007         }
1008
1009         case LFUN_DIALOG_SHOW_NEW_INSET:
1010                 flag.setEnabled(cur.inset().lyxCode() != ERT_CODE &&
1011                         cur.inset().lyxCode() != LISTINGS_CODE);
1012                 if (cur.inset().lyxCode() == CAPTION_CODE) {
1013                         FuncStatus flag;
1014                         if (cur.inset().getStatus(cur, cmd, flag))
1015                                 return flag;
1016                 }
1017                 break;
1018
1019         case LFUN_BRANCH_ACTIVATE: 
1020         case LFUN_BRANCH_DEACTIVATE: {
1021                 bool enable = false;
1022                 docstring const branchName = cmd.argument();
1023                 if (!branchName.empty())
1024                         enable = buffer_.params().branchlist().find(branchName);
1025                 flag.setEnabled(enable);
1026                 break;
1027         }
1028
1029         default:
1030                 flag.setEnabled(false);
1031         }
1032
1033         return flag;
1034 }
1035
1036
1037 bool BufferView::dispatch(FuncRequest const & cmd)
1038 {
1039         //lyxerr << [ cmd = " << cmd << "]" << endl;
1040
1041         // Make sure that the cached BufferView is correct.
1042         LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1043                 << " arg[" << to_utf8(cmd.argument()) << ']'
1044                 << " x[" << cmd.x << ']'
1045                 << " y[" << cmd.y << ']'
1046                 << " button[" << cmd.button() << ']');
1047
1048         Cursor & cur = d->cursor_;
1049
1050         switch (cmd.action) {
1051
1052         case LFUN_UNDO:
1053                 cur.message(_("Undo"));
1054                 cur.clearSelection();
1055                 if (!cur.textUndo())
1056                         cur.message(_("No further undo information"));
1057                 else
1058                         processUpdateFlags(Update::Force | Update::FitCursor);
1059                 break;
1060
1061         case LFUN_REDO:
1062                 cur.message(_("Redo"));
1063                 cur.clearSelection();
1064                 if (!cur.textRedo())
1065                         cur.message(_("No further redo information"));
1066                 else
1067                         processUpdateFlags(Update::Force | Update::FitCursor);
1068                 break;
1069
1070         case LFUN_FONT_STATE:
1071                 cur.message(cur.currentState());
1072                 break;
1073
1074         case LFUN_BOOKMARK_SAVE:
1075                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1076                 break;
1077
1078         case LFUN_LABEL_GOTO: {
1079                 docstring label = cmd.argument();
1080                 if (label.empty()) {
1081                         InsetRef * inset =
1082                                 getInsetByCode<InsetRef>(d->cursor_, REF_CODE);
1083                         if (inset) {
1084                                 label = inset->getParam("reference");
1085                                 // persistent=false: use temp_bookmark
1086                                 saveBookmark(0);
1087                         }
1088                 }
1089                 if (!label.empty())
1090                         gotoLabel(label);
1091                 break;
1092         }
1093         
1094         case LFUN_INSET_EDIT: {
1095                 FuncRequest fr(cmd);
1096                 // if there is an inset at cursor, see whether it
1097                 // can be modified.
1098                 Inset * inset = cur.nextInset();
1099                 if (inset)
1100                         inset->dispatch(cur, fr);
1101                 // if it did not work, try the underlying inset.
1102                 if (!inset || !cur.result().dispatched())
1103                         cur.dispatch(cmd);
1104
1105                 // FIXME I'm adding the last break to solve a crash,
1106                 // but that is obviously not right.
1107                 if (!cur.result().dispatched())
1108                         // It did not work too; no action needed.
1109                         break;
1110                 break;
1111         }
1112
1113         case LFUN_PARAGRAPH_GOTO: {
1114                 int const id = convert<int>(cmd.getArg(0));
1115                 int const pos = convert<int>(cmd.getArg(1));
1116                 int i = 0;
1117                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1118                         b = theBufferList().next(b)) {
1119
1120                         DocIterator dit = b->getParFromID(id);
1121                         if (dit.atEnd()) {
1122                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1123                                 ++i;
1124                                 continue;
1125                         }
1126                         LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1127                                 << " found in buffer `"
1128                                 << b->absFileName() << "'.");
1129
1130                         if (b == &buffer_) {
1131                                 // Set the cursor
1132                                 dit.pos() = pos;
1133                                 setCursor(dit);
1134                                 processUpdateFlags(Update::Force | Update::FitCursor);
1135                         } else {
1136                                 // Switch to other buffer view and resend cmd
1137                                 theLyXFunc().dispatch(FuncRequest(
1138                                         LFUN_BUFFER_SWITCH, b->absFileName()));
1139                                 theLyXFunc().dispatch(cmd);
1140                         }
1141                         break;
1142                 }
1143                 break;
1144         }
1145
1146         case LFUN_NOTE_NEXT:
1147                 gotoInset(this, NOTE_CODE, false);
1148                 break;
1149
1150         case LFUN_REFERENCE_NEXT: {
1151                 vector<InsetCode> tmp;
1152                 tmp.push_back(LABEL_CODE);
1153                 tmp.push_back(REF_CODE);
1154                 gotoInset(this, tmp, true);
1155                 break;
1156         }
1157
1158         case LFUN_CHANGES_TRACK:
1159                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1160                 break;
1161
1162         case LFUN_CHANGES_OUTPUT:
1163                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1164                 if (buffer_.params().outputChanges) {
1165                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1166                         bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1167                                           LaTeXFeatures::isAvailable("xcolor");
1168
1169                         if (!dvipost && !xcolorulem) {
1170                                 Alert::warning(_("Changes not shown in LaTeX output"),
1171                                                _("Changes will not be highlighted in LaTeX output, "
1172                                                  "because neither dvipost nor xcolor/ulem are installed.\n"
1173                                                  "Please install these packages or redefine "
1174                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1175                         } else if (!xcolorulem) {
1176                                 Alert::warning(_("Changes not shown in LaTeX output"),
1177                                                _("Changes will not be highlighted in LaTeX output "
1178                                                  "when using pdflatex, because xcolor and ulem are not installed.\n"
1179                                                  "Please install both packages or redefine "
1180                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1181                         }
1182                 }
1183                 break;
1184
1185         case LFUN_CHANGE_NEXT:
1186                 findNextChange(this);
1187                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1188                 processUpdateFlags(Update::Force | Update::FitCursor);
1189                 break;
1190
1191         case LFUN_CHANGES_MERGE:
1192                 if (findNextChange(this)) {
1193                         processUpdateFlags(Update::Force | Update::FitCursor);
1194                         showDialog("changes");
1195                 }
1196                 break;
1197
1198         case LFUN_ALL_CHANGES_ACCEPT:
1199                 // select complete document
1200                 d->cursor_.reset(buffer_.inset());
1201                 d->cursor_.selHandle(true);
1202                 buffer_.text().cursorBottom(d->cursor_);
1203                 // accept everything in a single step to support atomic undo
1204                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1205                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1206                 processUpdateFlags(Update::Force | Update::FitCursor);
1207                 break;
1208
1209         case LFUN_ALL_CHANGES_REJECT:
1210                 // select complete document
1211                 d->cursor_.reset(buffer_.inset());
1212                 d->cursor_.selHandle(true);
1213                 buffer_.text().cursorBottom(d->cursor_);
1214                 // reject everything in a single step to support atomic undo
1215                 // Note: reject does not work recursively; the user may have to repeat the operation
1216                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1217                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1218                 processUpdateFlags(Update::Force | Update::FitCursor);
1219                 break;
1220
1221         case LFUN_WORD_FIND: {
1222                 FuncRequest req = cmd;
1223                 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1224                         req = d->search_request_cache_;
1225                 if (req.argument().empty()) {
1226                         theLyXFunc().dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1227                         break;
1228                 }
1229                 if (find(this, req))
1230                         showCursor();
1231                 else
1232                         message(_("String not found!"));
1233                 d->search_request_cache_ = req;
1234                 break;
1235         }
1236
1237         case LFUN_WORD_REPLACE: {
1238                 bool has_deleted = false;
1239                 if (cur.selection()) {
1240                         DocIterator beg = cur.selectionBegin();
1241                         DocIterator end = cur.selectionEnd();
1242                         if (beg.pit() == end.pit()) {
1243                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1244                                         if (cur.paragraph().isDeleted(p))
1245                                                 has_deleted = true;
1246                                 }
1247                         }
1248                 }
1249                 replace(this, cmd, has_deleted);
1250                 break;
1251         }
1252
1253         case LFUN_WORD_FINDADV:
1254                 findAdv(this, cmd);
1255                 break;
1256
1257         case LFUN_MARK_OFF:
1258                 cur.clearSelection();
1259                 cur.resetAnchor();
1260                 cur.message(from_utf8(N_("Mark off")));
1261                 break;
1262
1263         case LFUN_MARK_ON:
1264                 cur.clearSelection();
1265                 cur.setMark(true);
1266                 cur.resetAnchor();
1267                 cur.message(from_utf8(N_("Mark on")));
1268                 break;
1269
1270         case LFUN_MARK_TOGGLE:
1271                 cur.clearSelection();
1272                 if (cur.mark()) {
1273                         cur.setMark(false);
1274                         cur.message(from_utf8(N_("Mark removed")));
1275                 } else {
1276                         cur.setMark(true);
1277                         cur.message(from_utf8(N_("Mark set")));
1278                 }
1279                 cur.resetAnchor();
1280                 break;
1281
1282         case LFUN_SCREEN_RECENTER:
1283                 showCursor();
1284                 break;
1285
1286         case LFUN_BIBTEX_DATABASE_ADD: {
1287                 Cursor tmpcur = d->cursor_;
1288                 findInset(tmpcur, BIBTEX_CODE, false);
1289                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1290                                                 BIBTEX_CODE);
1291                 if (inset) {
1292                         if (inset->addDatabase(cmd.argument()))
1293                                 buffer_.updateBibfilesCache();
1294                 }
1295                 break;
1296         }
1297
1298         case LFUN_BIBTEX_DATABASE_DEL: {
1299                 Cursor tmpcur = d->cursor_;
1300                 findInset(tmpcur, BIBTEX_CODE, false);
1301                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1302                                                 BIBTEX_CODE);
1303                 if (inset) {
1304                         if (inset->delDatabase(cmd.argument()))
1305                                 buffer_.updateBibfilesCache();
1306                 }
1307                 break;
1308         }
1309
1310         case LFUN_STATISTICS: {
1311                 DocIterator from, to;
1312                 if (cur.selection()) {
1313                         from = cur.selectionBegin();
1314                         to = cur.selectionEnd();
1315                 } else {
1316                         from = doc_iterator_begin(&buffer_);
1317                         to = doc_iterator_end(&buffer_);
1318                 }
1319                 int const words = countWords(from, to);
1320                 int const chars = countChars(from, to, false);
1321                 int const chars_blanks = countChars(from, to, true);
1322                 docstring message;
1323                 if (cur.selection())
1324                         message = _("Statistics for the selection:");
1325                 else
1326                         message = _("Statistics for the document:");
1327                 message += "\n\n";
1328                 if (words != 1)
1329                         message += bformat(_("%1$d words"), words);
1330                 else
1331                         message += _("One word");
1332                 message += "\n";
1333                 if (chars_blanks != 1)
1334                         message += bformat(_("%1$d characters (including blanks)"),
1335                                           chars_blanks);
1336                 else
1337                         message += _("One character (including blanks)");
1338                 message += "\n";
1339                 if (chars != 1)
1340                         message += bformat(_("%1$d characters (excluding blanks)"),
1341                                           chars);
1342                 else
1343                         message += _("One character (excluding blanks)");
1344
1345                 Alert::information(_("Statistics"), message);
1346         }
1347                 break;
1348
1349         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1350                 // turn compression on/off
1351                 buffer_.params().compressed = !buffer_.params().compressed;
1352                 break;
1353         case LFUN_COPY_LABEL_AS_REF: {
1354                 // if there is an inset at cursor, try to copy it
1355                 Inset * inset = cur.nextInset();
1356                 if (inset) {
1357                         FuncRequest tmpcmd = cmd;
1358                         inset->dispatch(cur, tmpcmd);
1359                 }
1360                 if (!cur.result().dispatched())
1361                         // It did not work too; no action needed.
1362                         break;
1363                 cur.clearSelection();
1364                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1365                 break;
1366         }
1367         case LFUN_NEXT_INSET_TOGGLE: {
1368                 // create the the real function we want to invoke
1369                 FuncRequest tmpcmd = cmd;
1370                 tmpcmd.action = LFUN_INSET_TOGGLE;
1371                 // if there is an inset at cursor, see whether it
1372                 // wants to toggle.
1373                 Inset * inset = cur.nextInset();
1374                 if (inset) {
1375                         if (inset->isActive()) {
1376                                 Cursor tmpcur = cur;
1377                                 tmpcur.pushBackward(*inset);
1378                                 inset->dispatch(tmpcur, tmpcmd);
1379                                 if (tmpcur.result().dispatched())
1380                                         cur.dispatched();
1381                         } else 
1382                                 inset->dispatch(cur, tmpcmd);
1383                 }
1384                 // if it did not work, try the underlying inset.
1385                 if (!inset || !cur.result().dispatched())
1386                         cur.dispatch(tmpcmd);
1387
1388                 if (!cur.result().dispatched())
1389                         // It did not work too; no action needed.
1390                         break;
1391                 cur.clearSelection();
1392                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1393                 break;
1394         }
1395
1396         case LFUN_NEXT_INSET_MODIFY: {
1397                 // create the the real function we want to invoke
1398                 FuncRequest tmpcmd = cmd;
1399                 tmpcmd.action = LFUN_INSET_MODIFY;
1400                 // if there is an inset at cursor, see whether it
1401                 // can be modified.
1402                 Inset * inset = cur.nextInset();
1403                 if (inset) {
1404                         cur.recordUndo();
1405                         inset->dispatch(cur, tmpcmd);
1406                 }
1407                 // if it did not work, try the underlying inset.
1408                 if (!inset || !cur.result().dispatched()) {
1409                         cur.recordUndo();
1410                         cur.dispatch(tmpcmd);
1411                 }
1412
1413                 if (!cur.result().dispatched())
1414                         // It did not work too; no action needed.
1415                         break;
1416                 cur.clearSelection();
1417                 processUpdateFlags(Update::Force | Update::FitCursor);
1418                 break;
1419         }
1420
1421         case LFUN_SCREEN_UP:
1422         case LFUN_SCREEN_DOWN: {
1423                 Point p = getPos(cur, cur.boundary());
1424                 if (p.y_ < 0 || p.y_ > height_) {
1425                         // The cursor is off-screen so recenter before proceeding.
1426                         showCursor();
1427                         p = getPos(cur, cur.boundary());
1428                 }
1429                 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1430                         ? - height_ : height_);
1431                 if (cmd.action == LFUN_SCREEN_UP && scrolled > - height_)
1432                         p = Point(0, 0);
1433                 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1434                         p = Point(width_, height_);
1435                 cur.reset(buffer_.inset());
1436                 updateMetrics();
1437                 buffer_.changed();
1438                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1439                 //FIXME: what to do with cur.x_target()?
1440                 cur.finishUndo();
1441                 break;
1442         }
1443
1444         case LFUN_SCROLL:
1445                 lfunScroll(cmd);
1446                 break;
1447
1448         case LFUN_SCREEN_UP_SELECT: {
1449                 cur.selHandle(true);
1450                 if (isTopScreen()) {
1451                         lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1452                         cur.finishUndo();
1453                         break;
1454                 }
1455                 int y = getPos(cur, cur.boundary()).y_;
1456                 int const ymin = y - height_ + defaultRowHeight();
1457                 while (y > ymin && cur.up())
1458                         y = getPos(cur, cur.boundary()).y_;
1459
1460                 cur.finishUndo();
1461                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1462                 break;
1463         }
1464
1465         case LFUN_SCREEN_DOWN_SELECT: {
1466                 cur.selHandle(true);
1467                 if (isBottomScreen()) {
1468                         lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1469                         cur.finishUndo();
1470                         break;
1471                 }
1472                 int y = getPos(cur, cur.boundary()).y_;
1473                 int const ymax = y + height_ - defaultRowHeight();
1474                 while (y < ymax && cur.down())
1475                         y = getPos(cur, cur.boundary()).y_;
1476
1477                 cur.finishUndo();
1478                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1479                 break;
1480         }
1481
1482         case LFUN_BRANCH_ACTIVATE:
1483         case LFUN_BRANCH_DEACTIVATE:
1484                 buffer_.dispatch(cmd);
1485                 processUpdateFlags(Update::Force);
1486                 break;
1487
1488         // This could be rewriten using some command like forall <insetname> <command>
1489         // once the insets refactoring is done.
1490         case LFUN_NOTES_MUTATE: {
1491                 if (cmd.argument().empty())
1492                         break;
1493
1494                 if (mutateNotes(cur, cmd.getArg(0), cmd.getArg(1))) {
1495                         processUpdateFlags(Update::Force);
1496                 }
1497                 break;
1498         }
1499
1500         case LFUN_ALL_INSETS_TOGGLE: {
1501                 string action;
1502                 string const name = split(to_utf8(cmd.argument()), action, ' ');
1503                 InsetCode const inset_code = insetCode(name);
1504
1505                 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1506
1507                 Inset & inset = cur.buffer()->inset();
1508                 InsetIterator it  = inset_iterator_begin(inset);
1509                 InsetIterator const end = inset_iterator_end(inset);
1510                 for (; it != end; ++it) {
1511                         if (it->asInsetCollapsable()
1512                             && (inset_code == NO_CODE
1513                             || inset_code == it->lyxCode())) {
1514                                 Cursor tmpcur = cur;
1515                                 tmpcur.pushBackward(*it);
1516                                 it->dispatch(tmpcur, fr);
1517                         }
1518                 }
1519                 processUpdateFlags(Update::Force | Update::FitCursor);
1520                 break;
1521         }
1522
1523         default:
1524                 return false;
1525         }
1526
1527         return true;
1528 }
1529
1530
1531 docstring const BufferView::requestSelection()
1532 {
1533         Cursor & cur = d->cursor_;
1534
1535         LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1536         if (!cur.selection()) {
1537                 d->xsel_cache_.set = false;
1538                 return docstring();
1539         }
1540
1541         LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1542         if (!d->xsel_cache_.set ||
1543             cur.top() != d->xsel_cache_.cursor ||
1544             cur.anchor_.top() != d->xsel_cache_.anchor)
1545         {
1546                 d->xsel_cache_.cursor = cur.top();
1547                 d->xsel_cache_.anchor = cur.anchor_.top();
1548                 d->xsel_cache_.set = cur.selection();
1549                 return cur.selectionAsString(false);
1550         }
1551         return docstring();
1552 }
1553
1554
1555 void BufferView::clearSelection()
1556 {
1557         d->cursor_.clearSelection();
1558         // Clear the selection buffer. Otherwise a subsequent
1559         // middle-mouse-button paste would use the selection buffer,
1560         // not the more current external selection.
1561         cap::clearSelection();
1562         d->xsel_cache_.set = false;
1563         // The buffer did not really change, but this causes the
1564         // redraw we need because we cleared the selection above.
1565         buffer_.changed();
1566 }
1567
1568
1569 void BufferView::resize(int width, int height)
1570 {
1571         // Update from work area
1572         width_ = width;
1573         height_ = height;
1574
1575         // Clear the paragraph height cache.
1576         d->par_height_.clear();
1577         // Redo the metrics.
1578         updateMetrics();
1579 }
1580
1581
1582 Inset const * BufferView::getCoveringInset(Text const & text,
1583                 int x, int y) const
1584 {
1585         TextMetrics & tm = d->text_metrics_[&text];
1586         Inset * inset = tm.checkInsetHit(x, y);
1587         if (!inset)
1588                 return 0;
1589
1590         if (!inset->descendable())
1591                 // No need to go further down if the inset is not
1592                 // descendable.
1593                 return inset;
1594
1595         size_t cell_number = inset->nargs();
1596         // Check all the inner cell.
1597         for (size_t i = 0; i != cell_number; ++i) {
1598                 Text const * inner_text = inset->getText(i);
1599                 if (inner_text) {
1600                         // Try deeper.
1601                         Inset const * inset_deeper =
1602                                 getCoveringInset(*inner_text, x, y);
1603                         if (inset_deeper)
1604                                 return inset_deeper;
1605                 }
1606         }
1607
1608         return inset;
1609 }
1610
1611
1612 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1613 {
1614         //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1615
1616         // This is only called for mouse related events including
1617         // LFUN_FILE_OPEN generated by drag-and-drop.
1618         FuncRequest cmd = cmd0;
1619
1620         Cursor old = cursor();
1621         Cursor cur(*this);
1622         cur.push(buffer_.inset());
1623         cur.setSelection(d->cursor_.selection());
1624
1625         // Either the inset under the cursor or the
1626         // surrounding Text will handle this event.
1627
1628         // make sure we stay within the screen...
1629         cmd.y = min(max(cmd.y, -1), height_);
1630
1631         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1632
1633                 // Get inset under mouse, if there is one.
1634                 Inset const * covering_inset =
1635                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1636                 if (covering_inset == d->last_inset_)
1637                         // Same inset, no need to do anything...
1638                         return;
1639
1640                 bool need_redraw = false;
1641                 // const_cast because of setMouseHover().
1642                 Inset * inset = const_cast<Inset *>(covering_inset);
1643                 if (d->last_inset_)
1644                         // Remove the hint on the last hovered inset (if any).
1645                         need_redraw |= d->last_inset_->setMouseHover(false);
1646                 if (inset)
1647                         // Highlighted the newly hovered inset (if any).
1648                         need_redraw |= inset->setMouseHover(true);
1649                 d->last_inset_ = inset;
1650                 if (!need_redraw)
1651                         return;
1652
1653                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1654                         << cmd.x << ", " << cmd.y << ")");
1655
1656                 d->update_strategy_ = DecorationUpdate;
1657
1658                 // This event (moving without mouse click) is not passed further.
1659                 // This should be changed if it is further utilized.
1660                 buffer_.changed();
1661                 return;
1662         }
1663
1664         // Build temporary cursor.
1665         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1666
1667         // Put anchor at the same position.
1668         cur.resetAnchor();
1669
1670         cur.beginUndoGroup();
1671
1672         // Try to dispatch to an non-editable inset near this position
1673         // via the temp cursor. If the inset wishes to change the real
1674         // cursor it has to do so explicitly by using
1675         //  cur.bv().cursor() = cur;  (or similar)
1676         if (inset)
1677                 inset->dispatch(cur, cmd);
1678
1679         // Now dispatch to the temporary cursor. If the real cursor should
1680         // be modified, the inset's dispatch has to do so explicitly.
1681         if (!inset || !cur.result().dispatched())
1682                 cur.dispatch(cmd);
1683
1684         cur.endUndoGroup();
1685
1686         // Notify left insets
1687         if (cur != old) {
1688                 old.fixIfBroken();
1689                 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
1690                 if (badcursor)
1691                         cursor().fixIfBroken();
1692         }
1693         
1694         // Do we have a selection?
1695         theSelection().haveSelection(cursor().selection());
1696
1697         // If the command has been dispatched,
1698         if (cur.result().dispatched() || cur.result().update())
1699                 processUpdateFlags(cur.result().update());
1700 }
1701
1702
1703 void BufferView::lfunScroll(FuncRequest const & cmd)
1704 {
1705         string const scroll_type = cmd.getArg(0);
1706         int const scroll_step = 
1707                 (scroll_type == "line") ? d->scrollbarParameters_.single_step
1708                 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
1709         if (scroll_step == 0)
1710                 return;
1711         string const scroll_quantity = cmd.getArg(1);
1712         if (scroll_quantity == "up")
1713                 scrollUp(scroll_step);
1714         else if (scroll_quantity == "down")
1715                 scrollDown(scroll_step);
1716         else {
1717                 int const scroll_value = convert<int>(scroll_quantity);
1718                 if (scroll_value)
1719                         scroll(scroll_step * scroll_value);
1720         }
1721         updateMetrics();
1722         buffer_.changed();
1723 }
1724
1725
1726 int BufferView::scroll(int y)
1727 {
1728         if (y > 0)
1729                 return scrollDown(y);
1730         if (y < 0)
1731                 return scrollUp(-y);
1732         return 0;
1733 }
1734
1735
1736 int BufferView::scrollDown(int offset)
1737 {
1738         Text * text = &buffer_.text();
1739         TextMetrics & tm = d->text_metrics_[text];
1740         int ymax = height_ + offset;
1741         while (true) {
1742                 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1743                 int bottom_pos = last.second->position() + last.second->descent();
1744                 if (last.first + 1 == int(text->paragraphs().size())) {
1745                         if (bottom_pos <= height_)
1746                                 return 0;
1747                         offset = min(offset, bottom_pos - height_);
1748                         break;
1749                 }
1750                 if (bottom_pos > ymax)
1751                         break;
1752                 tm.newParMetricsDown();
1753         }
1754         d->anchor_ypos_ -= offset;
1755         return -offset;
1756 }
1757
1758
1759 int BufferView::scrollUp(int offset)
1760 {
1761         Text * text = &buffer_.text();
1762         TextMetrics & tm = d->text_metrics_[text];
1763         int ymin = - offset;
1764         while (true) {
1765                 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1766                 int top_pos = first.second->position() - first.second->ascent();
1767                 if (first.first == 0) {
1768                         if (top_pos >= 0)
1769                                 return 0;
1770                         offset = min(offset, - top_pos);
1771                         break;
1772                 }
1773                 if (top_pos < ymin)
1774                         break;
1775                 tm.newParMetricsUp();
1776         }
1777         d->anchor_ypos_ += offset;
1778         return offset;
1779 }
1780
1781
1782 void BufferView::setCursorFromRow(int row)
1783 {
1784         int tmpid = -1;
1785         int tmppos = -1;
1786
1787         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1788
1789         d->cursor_.reset(buffer_.inset());
1790         if (tmpid == -1)
1791                 buffer_.text().setCursor(d->cursor_, 0, 0);
1792         else
1793                 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1794 }
1795
1796
1797 bool BufferView::setCursorFromInset(Inset const * inset)
1798 {
1799         // are we already there?
1800         if (cursor().nextInset() == inset)
1801                 return true;
1802
1803         // Inset is not at cursor position. Find it in the document.
1804         Cursor cur(*this);
1805         cur.reset(buffer().inset());
1806         while (cur && cur.nextInset() != inset)
1807                 cur.forwardInset();
1808
1809         if (cur) {
1810                 setCursor(cur);
1811                 return true;
1812         }
1813         return false;
1814 }
1815
1816
1817 void BufferView::gotoLabel(docstring const & label)
1818 {
1819         std::vector<Buffer const *> bufs = buffer().allRelatives();
1820         std::vector<Buffer const *>::iterator it = bufs.begin();
1821         for (; it != bufs.end(); ++it) {
1822                 Buffer const * buf = *it;
1823
1824                 // find label
1825                 Toc & toc = buf->tocBackend().toc("label");
1826                 TocIterator toc_it = toc.begin();
1827                 TocIterator end = toc.end();
1828                 for (; toc_it != end; ++toc_it) {
1829                         if (label == toc_it->str()) {
1830                                 dispatch(toc_it->action());
1831                                 return;
1832                         }
1833                 }
1834         }
1835 }
1836
1837
1838 TextMetrics const & BufferView::textMetrics(Text const * t) const
1839 {
1840         return const_cast<BufferView *>(this)->textMetrics(t);
1841 }
1842
1843
1844 TextMetrics & BufferView::textMetrics(Text const * t)
1845 {
1846         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
1847         if (tmc_it == d->text_metrics_.end()) {
1848                 tmc_it = d->text_metrics_.insert(
1849                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1850         }
1851         return tmc_it->second;
1852 }
1853
1854
1855 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1856                 pit_type pit) const
1857 {
1858         return textMetrics(t).parMetrics(pit);
1859 }
1860
1861
1862 int BufferView::workHeight() const
1863 {
1864         return height_;
1865 }
1866
1867
1868 void BufferView::setCursor(DocIterator const & dit)
1869 {
1870         size_t const n = dit.depth();
1871         for (size_t i = 0; i < n; ++i)
1872                 dit[i].inset().edit(d->cursor_, true);
1873
1874         d->cursor_.setCursor(dit);
1875         d->cursor_.setSelection(false);
1876 }
1877
1878
1879 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1880 {
1881         // Would be wrong to delete anything if we have a selection.
1882         if (cur.selection())
1883                 return false;
1884
1885         bool need_anchor_change = false;
1886         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1887                 need_anchor_change);
1888
1889         if (need_anchor_change)
1890                 cur.resetAnchor();
1891
1892         if (!changed)
1893                 return false;
1894
1895         d->cursor_ = cur;
1896
1897         buffer_.updateLabels();
1898
1899         updateMetrics();
1900         buffer_.changed();
1901         return true;
1902 }
1903
1904
1905 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1906 {
1907         LASSERT(&cur.bv() == this, /**/);
1908
1909         if (!select)
1910                 // this event will clear selection so we save selection for
1911                 // persistent selection
1912                 cap::saveSelection(cursor());
1913
1914         // Has the cursor just left the inset?
1915         bool leftinset = (&d->cursor_.inset() != &cur.inset());
1916         if (leftinset)
1917                 d->cursor_.fixIfBroken();
1918
1919         // FIXME: shift-mouse selection doesn't work well across insets.
1920         bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1921
1922         // do the dEPM magic if needed
1923         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1924         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1925         // the leftinset bool would not be necessary (badcursor instead).
1926         bool update = leftinset;
1927         if (!do_selection && d->cursor_.inTexted())
1928                 update |= checkDepm(cur, d->cursor_);
1929
1930         d->cursor_.setCursor(cur);
1931         d->cursor_.boundary(cur.boundary());
1932         if (do_selection)
1933                 d->cursor_.setSelection();
1934         else
1935                 d->cursor_.clearSelection();
1936
1937         d->cursor_.finishUndo();
1938         d->cursor_.setCurrentFont();
1939         return update;
1940 }
1941
1942
1943 void BufferView::putSelectionAt(DocIterator const & cur,
1944                                 int length, bool backwards)
1945 {
1946         d->cursor_.clearSelection();
1947
1948         setCursor(cur);
1949
1950         if (length) {
1951                 if (backwards) {
1952                         d->cursor_.pos() += length;
1953                         d->cursor_.setSelection(d->cursor_, -length);
1954                 } else
1955                         d->cursor_.setSelection(d->cursor_, length);
1956         }
1957         // Ensure a redraw happens in any case because the new selection could 
1958         // possibly be on the same screen as the previous selection.
1959         processUpdateFlags(Update::Force | Update::FitCursor);
1960 }
1961
1962
1963 Cursor & BufferView::cursor()
1964 {
1965         return d->cursor_;
1966 }
1967
1968
1969 Cursor const & BufferView::cursor() const
1970 {
1971         return d->cursor_;
1972 }
1973
1974
1975 pit_type BufferView::anchor_ref() const
1976 {
1977         return d->anchor_pit_;
1978 }
1979
1980
1981 bool BufferView::singleParUpdate()
1982 {
1983         Text & buftext = buffer_.text();
1984         pit_type const bottom_pit = d->cursor_.bottom().pit();
1985         TextMetrics & tm = textMetrics(&buftext);
1986         int old_height = tm.parMetrics(bottom_pit).height();
1987
1988         // make sure inline completion pointer is ok
1989         if (d->inlineCompletionPos_.fixIfBroken())
1990                 d->inlineCompletionPos_ = DocIterator();
1991
1992         // In Single Paragraph mode, rebreak only
1993         // the (main text, not inset!) paragraph containing the cursor.
1994         // (if this paragraph contains insets etc., rebreaking will
1995         // recursively descend)
1996         tm.redoParagraph(bottom_pit);
1997         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
1998         if (pm.height() != old_height)
1999                 // Paragraph height has changed so we cannot proceed to
2000                 // the singlePar optimisation.
2001                 return false;
2002
2003         d->update_strategy_ = SingleParUpdate;
2004
2005         LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2006                 << " y2: " << pm.position() + pm.descent()
2007                 << " pit: " << bottom_pit
2008                 << " singlepar: 1");
2009         return true;
2010 }
2011
2012
2013 void BufferView::updateMetrics()
2014 {
2015         if (height_ == 0 || width_ == 0)
2016                 return;
2017
2018         Text & buftext = buffer_.text();
2019         pit_type const npit = int(buftext.paragraphs().size());
2020
2021         // Clear out the position cache in case of full screen redraw,
2022         d->coord_cache_.clear();
2023
2024         // Clear out paragraph metrics to avoid having invalid metrics
2025         // in the cache from paragraphs not relayouted below
2026         // The complete text metrics will be redone.
2027         d->text_metrics_.clear();
2028
2029         TextMetrics & tm = textMetrics(&buftext);
2030
2031         // make sure inline completion pointer is ok
2032         if (d->inlineCompletionPos_.fixIfBroken())
2033                 d->inlineCompletionPos_ = DocIterator();
2034         
2035         if (d->anchor_pit_ >= npit)
2036                 // The anchor pit must have been deleted...
2037                 d->anchor_pit_ = npit - 1;
2038
2039         // Rebreak anchor paragraph.
2040         tm.redoParagraph(d->anchor_pit_);
2041         ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2042         
2043         // position anchor
2044         if (d->anchor_pit_ == 0) {
2045                 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2046                 
2047                 // Complete buffer visible? Then it's easy.
2048                 if (scrollRange == 0)
2049                         d->anchor_ypos_ = anchor_pm.ascent();
2050         
2051                 // FIXME: Some clever handling needed to show
2052                 // the _first_ paragraph up to the top if the cursor is
2053                 // in the first line.
2054         }               
2055         anchor_pm.setPosition(d->anchor_ypos_);
2056
2057         LYXERR(Debug::PAINTING, "metrics: "
2058                 << " anchor pit = " << d->anchor_pit_
2059                 << " anchor ypos = " << d->anchor_ypos_);
2060
2061         // Redo paragraphs above anchor if necessary.
2062         int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2063         // We are now just above the anchor paragraph.
2064         pit_type pit1 = d->anchor_pit_ - 1;
2065         for (; pit1 >= 0 && y1 >= 0; --pit1) {
2066                 tm.redoParagraph(pit1);
2067                 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2068                 y1 -= pm.descent();
2069                 // Save the paragraph position in the cache.
2070                 pm.setPosition(y1);
2071                 y1 -= pm.ascent();
2072         }
2073
2074         // Redo paragraphs below the anchor if necessary.
2075         int y2 = d->anchor_ypos_ + anchor_pm.descent();
2076         // We are now just below the anchor paragraph.
2077         pit_type pit2 = d->anchor_pit_ + 1;
2078         for (; pit2 < npit && y2 <= height_; ++pit2) {
2079                 tm.redoParagraph(pit2);
2080                 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2081                 y2 += pm.ascent();
2082                 // Save the paragraph position in the cache.
2083                 pm.setPosition(y2);
2084                 y2 += pm.descent();
2085         }
2086
2087         LYXERR(Debug::PAINTING, "Metrics: "
2088                 << " anchor pit = " << d->anchor_pit_
2089                 << " anchor ypos = " << d->anchor_ypos_
2090                 << " y1 = " << y1
2091                 << " y2 = " << y2
2092                 << " pit1 = " << pit1
2093                 << " pit2 = " << pit2);
2094
2095         d->update_strategy_ = FullScreenUpdate;
2096
2097         if (lyxerr.debugging(Debug::WORKAREA)) {
2098                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2099                 d->coord_cache_.dump();
2100         }
2101 }
2102
2103
2104 void BufferView::insertLyXFile(FileName const & fname)
2105 {
2106         LASSERT(d->cursor_.inTexted(), /**/);
2107
2108         // Get absolute path of file and add ".lyx"
2109         // to the filename if necessary
2110         FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2111
2112         docstring const disp_fn = makeDisplayPath(filename.absFilename());
2113         // emit message signal.
2114         message(bformat(_("Inserting document %1$s..."), disp_fn));
2115
2116         docstring res;
2117         Buffer buf("", false);
2118         if (buf.loadLyXFile(filename)) {
2119                 ErrorList & el = buffer_.errorList("Parse");
2120                 // Copy the inserted document error list into the current buffer one.
2121                 el = buf.errorList("Parse");
2122                 buffer_.undo().recordUndo(d->cursor_);
2123                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2124                                              buf.params().documentClassPtr(), el);
2125                 res = _("Document %1$s inserted.");
2126         } else {
2127                 res = _("Could not insert document %1$s");
2128         }
2129
2130         updateMetrics();
2131         buffer_.changed();
2132         // emit message signal.
2133         message(bformat(res, disp_fn));
2134         buffer_.errors("Parse");
2135 }
2136
2137
2138 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2139 {
2140         int x = 0;
2141         int y = 0;
2142         int lastw = 0;
2143
2144         // Addup contribution of nested insets, from inside to outside,
2145         // keeping the outer paragraph for a special handling below
2146         for (size_t i = dit.depth() - 1; i >= 1; --i) {
2147                 CursorSlice const & sl = dit[i];
2148                 int xx = 0;
2149                 int yy = 0;
2150                 
2151                 // get relative position inside sl.inset()
2152                 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2153                 
2154                 // Make relative position inside of the edited inset relative to sl.inset()
2155                 x += xx;
2156                 y += yy;
2157                 
2158                 // In case of an RTL inset, the edited inset will be positioned to the left
2159                 // of xx:yy
2160                 if (sl.text()) {
2161                         bool boundary_i = boundary && i + 1 == dit.depth();
2162                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2163                         if (rtl)
2164                                 x -= lastw;
2165                 }
2166
2167                 // remember width for the case that sl.inset() is positioned in an RTL inset
2168                 if (i && dit[i - 1].text()) {
2169                         // If this Inset is inside a Text Inset, retrieve the Dimension
2170                         // from the containing text instead of using Inset::dimension() which
2171                         // might not be implemented.
2172                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2173                         // elimination of Inset::dim_ cache. This coordOffset() method needs
2174                         // to be rewritten in light of the new design.
2175                         Dimension const & dim = parMetrics(dit[i - 1].text(),
2176                                 dit[i - 1].pit()).insetDimension(&sl.inset());
2177                         lastw = dim.wid;
2178                 } else {
2179                         Dimension const dim = sl.inset().dimension(*this);
2180                         lastw = dim.wid;
2181                 }
2182                 
2183                 //lyxerr << "Cursor::getPos, i: "
2184                 // << i << " x: " << xx << " y: " << y << endl;
2185         }
2186
2187         // Add contribution of initial rows of outermost paragraph
2188         CursorSlice const & sl = dit[0];
2189         TextMetrics const & tm = textMetrics(sl.text());
2190         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2191         LASSERT(!pm.rows().empty(), /**/);
2192         y -= pm.rows()[0].ascent();
2193 #if 1
2194         // FIXME: document this mess
2195         size_t rend;
2196         if (sl.pos() > 0 && dit.depth() == 1) {
2197                 int pos = sl.pos();
2198                 if (pos && boundary)
2199                         --pos;
2200 //              lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2201                 rend = pm.pos2row(pos);
2202         } else
2203                 rend = pm.pos2row(sl.pos());
2204 #else
2205         size_t rend = pm.pos2row(sl.pos());
2206 #endif
2207         for (size_t rit = 0; rit != rend; ++rit)
2208                 y += pm.rows()[rit].height();
2209         y += pm.rows()[rend].ascent();
2210         
2211         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2212         
2213         // Make relative position from the nested inset now bufferview absolute.
2214         int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2215         x += xx;
2216         
2217         // In the RTL case place the nested inset at the left of the cursor in 
2218         // the outer paragraph
2219         bool boundary_1 = boundary && 1 == dit.depth();
2220         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2221         if (rtl)
2222                 x -= lastw;
2223         
2224         return Point(x, y);
2225 }
2226
2227
2228 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2229 {
2230         if (!paragraphVisible(dit))
2231                 return Point(-1, -1);
2232
2233         CursorSlice const & bot = dit.bottom();
2234         TextMetrics const & tm = textMetrics(bot.text());
2235
2236         Point p = coordOffset(dit, boundary); // offset from outer paragraph
2237         p.y_ += tm.parMetrics(bot.pit()).position();
2238         return p;
2239 }
2240
2241
2242 bool BufferView::paragraphVisible(DocIterator const & dit) const
2243 {
2244         CursorSlice const & bot = dit.bottom();
2245         TextMetrics const & tm = textMetrics(bot.text());
2246
2247         return tm.contains(bot.pit());
2248 }
2249
2250
2251 void BufferView::draw(frontend::Painter & pain)
2252 {
2253         if (height_ == 0 || width_ == 0)
2254                 return;
2255         LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2256
2257         Text & text = buffer_.text();
2258         TextMetrics const & tm = d->text_metrics_[&text];
2259         int const y = tm.first().second->position();
2260         PainterInfo pi(this, pain);
2261
2262         switch (d->update_strategy_) {
2263
2264         case NoScreenUpdate:
2265                 // If no screen painting is actually needed, only some the different
2266                 // coordinates of insets and paragraphs needs to be updated.
2267                 pi.full_repaint = true;
2268                 pi.pain.setDrawingEnabled(false);
2269                 tm.draw(pi, 0, y);
2270                 break;
2271
2272         case SingleParUpdate:
2273                 pi.full_repaint = false;
2274                 // In general, only the current row of the outermost paragraph
2275                 // will be redrawn. Particular cases where selection spans
2276                 // multiple paragraph are correctly detected in TextMetrics.
2277                 tm.draw(pi, 0, y);
2278                 break;
2279
2280         case DecorationUpdate:
2281                 // FIXME: We should also distinguish DecorationUpdate to avoid text
2282                 // drawing if possible. This is not possible to do easily right now
2283                 // because of the single backing pixmap.
2284
2285         case FullScreenUpdate:
2286                 // The whole screen, including insets, will be refreshed.
2287                 pi.full_repaint = true;
2288
2289                 // Clear background.
2290                 pain.fillRectangle(0, 0, width_, height_,
2291                         pi.backgroundColor(&buffer_.inset()));
2292
2293                 // Draw everything.
2294                 tm.draw(pi, 0, y);
2295
2296                 // and possibly grey out below
2297                 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2298                 int const y2 = lastpm.second->position() + lastpm.second->descent();
2299                 if (y2 < height_)
2300                         pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2301                 break;
2302         }
2303         LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING  ***");
2304
2305         // The scrollbar needs an update.
2306         updateScrollbar();
2307
2308         // Normalize anchor for next time
2309         pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2310         pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2311         for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2312                 ParagraphMetrics const & pm = tm.parMetrics(pit);
2313                 if (pm.position() + pm.descent() > 0) {
2314                         d->anchor_pit_ = pit;
2315                         d->anchor_ypos_ = pm.position();
2316                         break;
2317                 }
2318         }
2319         LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2320                 << "  anchor ypos = " << d->anchor_ypos_);
2321 }
2322
2323
2324 void BufferView::message(docstring const & msg)
2325 {
2326         if (d->gui_)
2327                 d->gui_->message(msg);
2328 }
2329
2330
2331 void BufferView::showDialog(string const & name)
2332 {
2333         if (d->gui_)
2334                 d->gui_->showDialog(name, string());
2335 }
2336
2337
2338 void BufferView::showDialog(string const & name,
2339         string const & data, Inset * inset)
2340 {
2341         if (d->gui_)
2342                 d->gui_->showDialog(name, data, inset);
2343 }
2344
2345
2346 void BufferView::updateDialog(string const & name, string const & data)
2347 {
2348         if (d->gui_)
2349                 d->gui_->updateDialog(name, data);
2350 }
2351
2352
2353 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2354 {
2355         d->gui_ = gui;
2356 }
2357
2358
2359 // FIXME: Move this out of BufferView again
2360 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2361 {
2362         if (!fname.isReadableFile()) {
2363                 docstring const error = from_ascii(strerror(errno));
2364                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2365                 docstring const text =
2366                   bformat(_("Could not read the specified document\n"
2367                             "%1$s\ndue to the error: %2$s"), file, error);
2368                 Alert::error(_("Could not read file"), text);
2369                 return docstring();
2370         }
2371
2372         if (!fname.isReadableFile()) {
2373                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2374                 docstring const text =
2375                   bformat(_("%1$s\n is not readable."), file);
2376                 Alert::error(_("Could not open file"), text);
2377                 return docstring();
2378         }
2379
2380         // FIXME UNICODE: We don't know the encoding of the file
2381         docstring file_content = fname.fileContents("UTF-8");
2382         if (file_content.empty()) {
2383                 Alert::error(_("Reading not UTF-8 encoded file"),
2384                              _("The file is not UTF-8 encoded.\n"
2385                                "It will be read as local 8Bit-encoded.\n"
2386                                "If this does not give the correct result\n"
2387                                "then please change the encoding of the file\n"
2388                                "to UTF-8 with a program other than LyX.\n"));
2389                 file_content = fname.fileContents("local8bit");
2390         }
2391
2392         return normalize_c(file_content);
2393 }
2394
2395
2396 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2397 {
2398         docstring const tmpstr = contentsOfPlaintextFile(f);
2399
2400         if (tmpstr.empty())
2401                 return;
2402
2403         Cursor & cur = cursor();
2404         cap::replaceSelection(cur);
2405         buffer_.undo().recordUndo(cur);
2406         if (asParagraph)
2407                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2408         else
2409                 cur.innerText()->insertStringAsLines(cur, tmpstr);
2410
2411         updateMetrics();
2412         buffer_.changed();
2413 }
2414
2415
2416 docstring const & BufferView::inlineCompletion() const
2417 {
2418         return d->inlineCompletion_;
2419 }
2420
2421
2422 size_t const & BufferView::inlineCompletionUniqueChars() const
2423 {
2424         return d->inlineCompletionUniqueChars_;
2425 }
2426
2427
2428 DocIterator const & BufferView::inlineCompletionPos() const
2429 {
2430         return d->inlineCompletionPos_;
2431 }
2432
2433
2434 bool samePar(DocIterator const & a, DocIterator const & b)
2435 {
2436         if (a.empty() && b.empty())
2437                 return true;
2438         if (a.empty() || b.empty())
2439                 return false;
2440         return &a.innerParagraph() == &b.innerParagraph();
2441 }
2442
2443
2444 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos, 
2445         docstring const & completion, size_t uniqueChars)
2446 {
2447         uniqueChars = min(completion.size(), uniqueChars);
2448         bool changed = d->inlineCompletion_ != completion
2449                 || d->inlineCompletionUniqueChars_ != uniqueChars;
2450         bool singlePar = true;
2451         d->inlineCompletion_ = completion;
2452         d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2453         
2454         //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2455         
2456         // at new position?
2457         DocIterator const & old = d->inlineCompletionPos_;
2458         if (old != pos) {
2459                 //lyxerr << "inlineCompletionPos changed" << std::endl;
2460                 // old or pos are in another paragraph?
2461                 if ((!samePar(cur, pos) && !pos.empty())
2462                     || (!samePar(cur, old) && !old.empty())) {
2463                         singlePar = false;
2464                         //lyxerr << "different paragraph" << std::endl;
2465                 }
2466                 d->inlineCompletionPos_ = pos;
2467         }
2468         
2469         // set update flags
2470         if (changed) {
2471                 if (singlePar && !(cur.disp_.update() & Update::Force))
2472                         cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2473                 else
2474                         cur.updateFlags(cur.disp_.update() | Update::Force);
2475         }
2476 }
2477
2478 } // namespace lyx