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