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