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