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