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