]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
Leave alone the header and add the include where it is needed.
[lyx.git] / src / BufferView.cpp
1 /**
2  * \file BufferView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "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 "LayoutFile.h"
38 #include "Lexer.h"
39 #include "LyX.h"
40 #include "LyXAction.h"
41 #include "lyxfind.h"
42 #include "Layout.h"
43 #include "LyXRC.h"
44 #include "MetricsInfo.h"
45 #include "Paragraph.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
48 #include "Session.h"
49 #include "Text.h"
50 #include "TextClass.h"
51 #include "TextMetrics.h"
52 #include "TexRow.h"
53 #include "TocBackend.h"
54 #include "VSpace.h"
55 #include "WordLangTuple.h"
56
57 #include "insets/InsetBibtex.h"
58 #include "insets/InsetCommand.h" // ChangeRefs
59 #include "insets/InsetExternal.h"
60 #include "insets/InsetGraphics.h"
61 #include "insets/InsetNote.h"
62 #include "insets/InsetRef.h"
63 #include "insets/InsetText.h"
64
65 #include "frontends/alert.h"
66 #include "frontends/Application.h"
67 #include "frontends/Delegates.h"
68 #include "frontends/FontMetrics.h"
69 #include "frontends/Painter.h"
70 #include "frontends/Selection.h"
71
72 #include "support/convert.h"
73 #include "support/debug.h"
74 #include "support/ExceptionMessage.h"
75 #include "support/filetools.h"
76 #include "support/gettext.h"
77 #include "support/lassert.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 <sstream>
87 #include <vector>
88
89 using namespace std;
90 using namespace lyx::support;
91
92 namespace lyx {
93
94 namespace Alert = frontend::Alert;
95
96 namespace {
97
98 /// Return an inset of this class if it exists at the current cursor position
99 template <class T>
100 T * getInsetByCode(Cursor const & cur, InsetCode code)
101 {
102         DocIterator it = cur;
103         Inset * inset = it.nextInset();
104         if (inset && inset->lyxCode() == code)
105                 return static_cast<T*>(inset);
106         return 0;
107 }
108
109 /// Note that comparing contents can only be used for InsetCommand
110 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
111         docstring const & contents)
112 {
113         DocIterator tmpdit = dit;
114
115         while (tmpdit) {
116                 Inset const * inset = tmpdit.nextInset();
117                 if (inset) {
118                         bool const valid_code = std::find(codes.begin(), codes.end(), 
119                                 inset->lyxCode()) != codes.end();
120                         InsetCommand const * ic = inset->asInsetCommand();
121                         bool const same_or_no_contents =  contents.empty()
122                                 || (ic && (ic->getFirstNonOptParam() == contents));
123                         
124                         if (valid_code && same_or_no_contents) {
125                                 dit = tmpdit;
126                                 return true;
127                         }
128                 }
129                 tmpdit.forwardInset();
130         }
131
132         return false;
133 }
134
135
136 /// Looks for next inset with one of the given codes.
137 /// Note that same_content can only be used for InsetCommand
138 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
139         bool same_content)
140 {
141         docstring contents;
142         DocIterator tmpdit = dit;
143         tmpdit.forwardInset();
144         if (!tmpdit)
145                 return false;
146
147         Inset const * inset = tmpdit.nextInset();
148         if (same_content && inset) {
149                 InsetCommand const * ic = inset->asInsetCommand();
150                 if (ic) {
151                         bool const valid_code = std::find(codes.begin(), codes.end(),
152                                 ic->lyxCode()) != codes.end();
153                         if (valid_code)
154                                 contents = ic->getFirstNonOptParam();
155                 }
156         }
157
158         if (!findNextInset(tmpdit, codes, contents)) {
159                 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
160                         Inset * inset = &tmpdit.bottom().inset();
161                         tmpdit = doc_iterator_begin(&inset->buffer(), inset);
162                         if (!findNextInset(tmpdit, codes, contents))
163                                 return false;
164                 } else {
165                         return false;
166                 }
167         }
168
169         dit = tmpdit;
170         return true;
171 }
172
173
174 /// Looks for next inset with the given code
175 void findInset(DocIterator & dit, InsetCode code, bool same_content)
176 {
177         findInset(dit, vector<InsetCode>(1, code), same_content);
178 }
179
180
181 /// Moves cursor to the next inset with one of the given codes.
182 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
183                bool same_content)
184 {
185         Cursor tmpcur = bv->cursor();
186         if (!findInset(tmpcur, codes, same_content)) {
187                 bv->cursor().message(_("No more insets"));
188                 return;
189         }
190
191         tmpcur.clearSelection();
192         bv->setCursor(tmpcur);
193         bv->showCursor();
194 }
195
196
197 /// Moves cursor to the next inset with given code.
198 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
199 {
200         gotoInset(bv, vector<InsetCode>(1, code), same_content);
201 }
202
203
204 /// A map from a Text to the associated text metrics
205 typedef map<Text const *, TextMetrics> TextMetricsCache;
206
207 enum ScreenUpdateStrategy {
208         NoScreenUpdate,
209         SingleParUpdate,
210         FullScreenUpdate,
211         DecorationUpdate
212 };
213
214 } // anon namespace
215
216
217 /////////////////////////////////////////////////////////////////////
218 //
219 // BufferView
220 //
221 /////////////////////////////////////////////////////////////////////
222
223 struct BufferView::Private
224 {
225         Private(BufferView & bv): wh_(0), cursor_(bv),
226                 anchor_pit_(0), anchor_ypos_(0),
227                 inlineCompletionUniqueChars_(0),
228                 last_inset_(0), clickable_inset_(false), 
229                 mouse_position_cache_(),
230                 bookmark_edit_position_(-1), gui_(0)
231         {}
232
233         ///
234         ScrollbarParameters scrollbarParameters_;
235         ///
236         ScreenUpdateStrategy update_strategy_;
237         ///
238         CoordCache coord_cache_;
239
240         /// Estimated average par height for scrollbar.
241         int wh_;
242         /// this is used to handle XSelection events in the right manner.
243         struct {
244                 CursorSlice cursor;
245                 CursorSlice anchor;
246                 bool set;
247         } xsel_cache_;
248         ///
249         Cursor cursor_;
250         ///
251         pit_type anchor_pit_;
252         ///
253         int anchor_ypos_;
254         ///
255         vector<int> par_height_;
256
257         ///
258         DocIterator inlineCompletionPos_;
259         ///
260         docstring inlineCompletion_;
261         ///
262         size_t inlineCompletionUniqueChars_;
263
264         /// keyboard mapping object.
265         Intl intl_;
266
267         /// last visited inset.
268         /** kept to send setMouseHover(false).
269           * Not owned, so don't delete.
270           */
271         Inset const * last_inset_;
272         /// are we hovering something that we can click
273         bool clickable_inset_;
274
275         /// position of the mouse at the time of the last mouse move
276         /// This is used to update the hovering status of inset in
277         /// cases where the buffer is scrolled, but the mouse didn't move.
278         Point mouse_position_cache_;
279
280         // cache for id of the paragraph which was edited the last time
281         int bookmark_edit_position_;
282
283         mutable TextMetricsCache text_metrics_;
284
285         /// Whom to notify.
286         /** Not owned, so don't delete.
287           */
288         frontend::GuiBufferViewDelegate * gui_;
289
290         /// Cache for Find Next
291         FuncRequest search_request_cache_;
292
293         ///
294         map<string, Inset *> edited_insets_;
295 };
296
297
298 BufferView::BufferView(Buffer & buf)
299         : width_(0), height_(0), full_screen_(false), buffer_(buf),
300       d(new Private(*this))
301 {
302         d->xsel_cache_.set = false;
303         d->intl_.initKeyMapper(lyxrc.use_kbmap);
304
305         d->cursor_.setBuffer(&buf);
306         d->cursor_.push(buffer_.inset());
307         d->cursor_.resetAnchor();
308         d->cursor_.setCurrentFont();
309
310         buffer_.updatePreviews();
311 }
312
313
314 BufferView::~BufferView()
315 {
316         // current buffer is going to be switched-off, save cursor pos
317         // Ideally, the whole cursor stack should be saved, but session
318         // currently can only handle bottom (whole document) level pit and pos.
319         // That is to say, if a cursor is in a nested inset, it will be
320         // restore to the left of the top level inset.
321         LastFilePosSection::FilePos fp;
322         fp.pit = d->cursor_.bottom().pit();
323         fp.pos = d->cursor_.bottom().pos();
324         theSession().lastFilePos().save(buffer_.fileName(), fp);
325         
326         if (d->last_inset_)
327                 d->last_inset_->setMouseHover(this, false);     
328
329         delete d;
330 }
331
332
333 int BufferView::rightMargin() const
334 {
335         // The additional test for the case the outliner is opened.
336         if (!full_screen_ ||
337                 !lyxrc.full_screen_limit ||
338                 width_ < lyxrc.full_screen_width + 20)
339                         return 10;
340
341         return (width_ - lyxrc.full_screen_width) / 2;
342 }
343
344
345 int BufferView::leftMargin() const
346 {
347         return rightMargin();
348 }
349
350
351 bool BufferView::isTopScreen() const
352 {
353         return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
354 }
355
356
357 bool BufferView::isBottomScreen() const
358 {
359         return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
360 }
361
362
363 Intl & BufferView::getIntl()
364 {
365         return d->intl_;
366 }
367
368
369 Intl const & BufferView::getIntl() const
370 {
371         return d->intl_;
372 }
373
374
375 CoordCache & BufferView::coordCache()
376 {
377         return d->coord_cache_;
378 }
379
380
381 CoordCache const & BufferView::coordCache() const
382 {
383         return d->coord_cache_;
384 }
385
386
387 Buffer & BufferView::buffer()
388 {
389         return buffer_;
390 }
391
392
393 Buffer const & BufferView::buffer() const
394 {
395         return buffer_;
396 }
397
398
399 bool BufferView::fitCursor()
400 {
401         if (cursorStatus(d->cursor_) == CUR_INSIDE) {
402                 frontend::FontMetrics const & fm =
403                         theFontMetrics(d->cursor_.getFont().fontInfo());
404                 int const asc = fm.maxAscent();
405                 int const des = fm.maxDescent();
406                 Point const p = getPos(d->cursor_);
407                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
408                         return false;
409         }
410         return true;
411 }
412
413
414 void BufferView::processUpdateFlags(Update::flags flags)
415 {
416         // This is close to a hot-path.
417         LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
418                 << "[fitcursor = " << (flags & Update::FitCursor)
419                 << ", forceupdate = " << (flags & Update::Force)
420                 << ", singlepar = " << (flags & Update::SinglePar)
421                 << "]  buffer: " << &buffer_);
422
423         // FIXME Does this really need doing here? It's done in updateBuffer, and
424         // if the Buffer doesn't need updating, then do the macros?
425         buffer_.updateMacros();
426
427         // Now do the first drawing step if needed. This consists on updating
428         // the CoordCache in updateMetrics().
429         // The second drawing step is done in WorkArea::redraw() if needed.
430
431         // Case when no explicit update is requested.
432         if (!flags) {
433                 // no need to redraw anything.
434                 d->update_strategy_ = NoScreenUpdate;
435                 return;
436         }
437
438         if (flags == Update::Decoration) {
439                 d->update_strategy_ = DecorationUpdate;
440                 buffer_.changed(false);
441                 return;
442         }
443
444         if (flags == Update::FitCursor
445                 || flags == (Update::Decoration | Update::FitCursor)) {
446                 // tell the frontend to update the screen if needed.
447                 if (fitCursor()) {
448                         showCursor();
449                         return;
450                 }
451                 if (flags & Update::Decoration) {
452                         d->update_strategy_ = DecorationUpdate;
453                         buffer_.changed(false);
454                         return;
455                 }
456                 // no screen update is needed.
457                 d->update_strategy_ = NoScreenUpdate;
458                 return;
459         }
460
461         bool const full_metrics = flags & Update::Force || !singleParUpdate();
462
463         if (full_metrics)
464                 // We have to update the full screen metrics.
465                 updateMetrics();
466
467         if (!(flags & Update::FitCursor)) {
468                 // Nothing to do anymore. Trigger a redraw and return
469                 buffer_.changed(false);
470                 return;
471         }
472
473         // updateMetrics() does not update paragraph position
474         // This is done at draw() time. So we need a redraw!
475         buffer_.changed(false);
476
477         if (fitCursor()) {
478                 // The cursor is off screen so ensure it is visible.
479                 // refresh it:
480                 showCursor();
481         }
482
483         updateHoveredInset();
484 }
485
486
487 void BufferView::updateScrollbar()
488 {
489         if (height_ == 0 && width_ == 0)
490                 return;
491
492         // We prefer fixed size line scrolling.
493         d->scrollbarParameters_.single_step = defaultRowHeight();
494         // We prefer full screen page scrolling.
495         d->scrollbarParameters_.page_step = height_;
496
497         Text & t = buffer_.text();
498         TextMetrics & tm = d->text_metrics_[&t];                
499
500         LYXERR(Debug::GUI, " Updating scrollbar: height: "
501                 << t.paragraphs().size()
502                 << " curr par: " << d->cursor_.bottom().pit()
503                 << " default height " << defaultRowHeight());
504
505         size_t const parsize = t.paragraphs().size();
506         if (d->par_height_.size() != parsize) {
507                 d->par_height_.clear();
508                 // FIXME: We assume a default paragraph height of 2 rows. This
509                 // should probably be pondered with the screen width.
510                 d->par_height_.resize(parsize, defaultRowHeight() * 2);
511         }
512
513         // Look at paragraph heights on-screen
514         pair<pit_type, ParagraphMetrics const *> first = tm.first();
515         pair<pit_type, ParagraphMetrics const *> last = tm.last();
516         for (pit_type pit = first.first; pit <= last.first; ++pit) {
517                 d->par_height_[pit] = tm.parMetrics(pit).height();
518                 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
519                         << d->par_height_[pit]);
520         }
521
522         int top_pos = first.second->position() - first.second->ascent();
523         int bottom_pos = last.second->position() + last.second->descent();
524         bool first_visible = first.first == 0 && top_pos >= 0;
525         bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
526         if (first_visible && last_visible) {
527                 d->scrollbarParameters_.min = 0;
528                 d->scrollbarParameters_.max = 0;
529                 return;
530         }
531
532         d->scrollbarParameters_.min = top_pos;
533         for (size_t i = 0; i != size_t(first.first); ++i)
534                 d->scrollbarParameters_.min -= d->par_height_[i];
535         d->scrollbarParameters_.max = bottom_pos;
536         for (size_t i = last.first + 1; i != parsize; ++i)
537                 d->scrollbarParameters_.max += d->par_height_[i];
538
539         d->scrollbarParameters_.position = 0;
540         // The reference is the top position so we remove one page.
541         if (lyxrc.scroll_below_document)
542                 d->scrollbarParameters_.max -= minVisiblePart();
543         else
544                 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
545 }
546
547
548 ScrollbarParameters const & BufferView::scrollbarParameters() const
549 {
550         return d->scrollbarParameters_;
551 }
552
553
554 docstring BufferView::toolTip(int x, int y) const
555 {
556         // Get inset under mouse, if there is one.
557         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
558         if (!covering_inset)
559                 // No inset, no tooltip...
560                 return docstring();
561         return covering_inset->toolTip(*this, x, y);
562 }
563
564
565 docstring BufferView::contextMenu(int x, int y) const
566 {
567         //If there is a selection, return the containing inset menu
568         if (d->cursor_.selection())
569                 return d->cursor_.inset().contextMenu(*this, x, y);
570
571         // Get inset under mouse, if there is one.
572         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
573         if (covering_inset)
574                 return covering_inset->contextMenu(*this, x, y);
575
576         return buffer_.inset().contextMenu(*this, x, y);
577 }
578
579
580 void BufferView::scrollDocView(int value, bool update)
581 {
582         int const offset = value - d->scrollbarParameters_.position;
583
584         // No scrolling at all? No need to redraw anything
585         if (offset == 0)
586                 return;
587
588         // If the offset is less than 2 screen height, prefer to scroll instead.
589         if (abs(offset) <= 2 * height_) {
590                 d->anchor_ypos_ -= offset;
591                 buffer_.changed(true);
592                 updateHoveredInset();
593                 return;
594         }
595
596         // cut off at the top
597         if (value <= d->scrollbarParameters_.min) {
598                 DocIterator dit = doc_iterator_begin(&buffer_);
599                 showCursor(dit, false, update);
600                 LYXERR(Debug::SCROLLING, "scroll to top");
601                 return;
602         }
603
604         // cut off at the bottom
605         if (value >= d->scrollbarParameters_.max) {
606                 DocIterator dit = doc_iterator_end(&buffer_);
607                 dit.backwardPos();
608                 showCursor(dit, false, update);
609                 LYXERR(Debug::SCROLLING, "scroll to bottom");
610                 return;
611         }
612
613         // find paragraph at target position
614         int par_pos = d->scrollbarParameters_.min;
615         pit_type i = 0;
616         for (; i != int(d->par_height_.size()); ++i) {
617                 par_pos += d->par_height_[i];
618                 if (par_pos >= value)
619                         break;
620         }
621
622         if (par_pos < value) {
623                 // It seems we didn't find the correct pit so stay on the safe side and
624                 // scroll to bottom.
625                 LYXERR0("scrolling position not found!");
626                 scrollDocView(d->scrollbarParameters_.max, update);
627                 return;
628         }
629
630         DocIterator dit = doc_iterator_begin(&buffer_);
631         dit.pit() = i;
632         LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
633         showCursor(dit, false, update);
634 }
635
636
637 // FIXME: this method is not working well.
638 void BufferView::setCursorFromScrollbar()
639 {
640         TextMetrics & tm = d->text_metrics_[&buffer_.text()];
641
642         int const height = 2 * defaultRowHeight();
643         int const first = height;
644         int const last = height_ - height;
645         int newy = 0;
646         Cursor const & oldcur = d->cursor_;
647
648         switch (cursorStatus(oldcur)) {
649         case CUR_ABOVE:
650                 newy = first;
651                 break;
652         case CUR_BELOW:
653                 newy = last;
654                 break;
655         case CUR_INSIDE:
656                 int const y = getPos(oldcur).y_;
657                 newy = min(last, max(y, first));
658                 if (y == newy) 
659                         return;
660         }
661         // We reset the cursor because cursorStatus() does not
662         // work when the cursor is within mathed.
663         Cursor cur(*this);
664         cur.reset();
665         tm.setCursorFromCoordinates(cur, 0, newy);
666
667         // update the bufferview cursor and notify insets
668         // FIXME: Care about the d->cursor_ flags to redraw if needed
669         Cursor old = d->cursor_;
670         mouseSetCursor(cur);
671         // the DEPM call in mouseSetCursor() might have destroyed the
672         // paragraph the cursor is in.
673         bool badcursor = old.fixIfBroken();
674         badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
675         if (badcursor)
676                 d->cursor_.fixIfBroken();
677 }
678
679
680 Change const BufferView::getCurrentChange() const
681 {
682         if (!d->cursor_.selection())
683                 return Change(Change::UNCHANGED);
684
685         DocIterator dit = d->cursor_.selectionBegin();
686         return dit.paragraph().lookupChange(dit.pos());
687 }
688
689
690 // this could be used elsewhere as well?
691 // FIXME: This does not work within mathed!
692 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
693 {
694         Point const p = getPos(dit);
695         if (p.y_ < 0)
696                 return CUR_ABOVE;
697         if (p.y_ > workHeight())
698                 return CUR_BELOW;
699         return CUR_INSIDE;
700 }
701
702
703 void BufferView::bookmarkEditPosition()
704 {
705         // Don't eat cpu time for each keystroke
706         if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
707                 return;
708         saveBookmark(0);
709         d->bookmark_edit_position_ = d->cursor_.paragraph().id();
710 }
711
712
713 void BufferView::saveBookmark(unsigned int idx)
714 {
715         // tentatively save bookmark, id and pos will be used to
716         // acturately locate a bookmark in a 'live' lyx session.
717         // pit and pos will be updated with bottom level pit/pos
718         // when lyx exits.
719         if (!buffer_.isInternal()) {
720                 theSession().bookmarks().save(
721                         buffer_.fileName(),
722                         d->cursor_.bottom().pit(),
723                         d->cursor_.bottom().pos(),
724                         d->cursor_.paragraph().id(),
725                         d->cursor_.pos(),
726                         idx
727                         );
728                 if (idx)
729                         // emit message signal.
730                         message(_("Save bookmark"));
731         }
732 }
733
734
735 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
736         int top_id, pos_type top_pos)
737 {
738         bool success = false;
739         DocIterator dit;
740
741         d->cursor_.clearSelection();
742
743         // if a valid par_id is given, try it first
744         // This is the case for a 'live' bookmark when unique paragraph ID
745         // is used to track bookmarks.
746         if (top_id > 0) {
747                 dit = buffer_.getParFromID(top_id);
748                 if (!dit.atEnd()) {
749                         dit.pos() = min(dit.paragraph().size(), top_pos);
750                         // Some slices of the iterator may not be
751                         // reachable (e.g. closed collapsable inset)
752                         // so the dociterator may need to be
753                         // shortened. Otherwise, setCursor may crash
754                         // lyx when the cursor can not be set to these
755                         // insets.
756                         size_t const n = dit.depth();
757                         for (size_t i = 0; i < n; ++i)
758                                 if (!dit[i].inset().editable()) {
759                                         dit.resize(i);
760                                         break;
761                                 }
762                         success = true;
763                 }
764         }
765
766         // if top_id == 0, or searching through top_id failed
767         // This is the case for a 'restored' bookmark when only bottom
768         // (document level) pit was saved. Because of this, bookmark
769         // restoration is inaccurate. If a bookmark was within an inset,
770         // it will be restored to the left of the outmost inset that contains
771         // the bookmark.
772         if (bottom_pit < int(buffer_.paragraphs().size())) {
773                 dit = doc_iterator_begin(&buffer_);
774                                 
775                 dit.pit() = bottom_pit;
776                 dit.pos() = min(bottom_pos, dit.paragraph().size());
777                 success = true;
778         }
779
780         if (success) {
781                 // Note: only bottom (document) level pit is set.
782                 setCursor(dit);
783                 // set the current font.
784                 d->cursor_.setCurrentFont();
785                 // To center the screen on this new position we need the
786                 // paragraph position which is computed at draw() time.
787                 // So we need a redraw!
788                 buffer_.changed(false);
789                 if (fitCursor())
790                         showCursor();
791         }
792
793         return success;
794 }
795
796
797 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
798 {
799         if (lyxrc.rtl_support) {
800                 if (d->cursor_.real_current_font.isRightToLeft()) {
801                         if (d->intl_.keymap == Intl::PRIMARY)
802                                 d->intl_.keyMapSec();
803                 } else {
804                         if (d->intl_.keymap == Intl::SECONDARY)
805                                 d->intl_.keyMapPrim();
806                 }
807         }
808
809         d->intl_.getTransManager().translateAndInsert(c, t, cur);
810 }
811
812
813 int BufferView::workWidth() const
814 {
815         return width_;
816 }
817
818
819 void BufferView::recenter()
820 {
821         showCursor(d->cursor_, true, true);
822 }
823
824
825 void BufferView::showCursor()
826 {
827         showCursor(d->cursor_, false, true);
828 }
829
830
831 void BufferView::showCursor(DocIterator const & dit,
832         bool recenter, bool update)
833 {
834         if (scrollToCursor(dit, recenter) && update) {
835                 buffer_.changed(true);
836                 updateHoveredInset();
837         }
838 }
839
840
841 void BufferView::scrollToCursor()
842 {
843         if (scrollToCursor(d->cursor_, false)) {
844                 buffer_.changed(true);
845                 updateHoveredInset();
846         }
847 }
848
849
850 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
851 {
852         // We are not properly started yet, delay until resizing is
853         // done.
854         if (height_ == 0)
855                 return false;
856
857         LYXERR(Debug::SCROLLING, "recentering!");
858
859         CursorSlice const & bot = dit.bottom();
860         TextMetrics & tm = d->text_metrics_[bot.text()];
861
862         pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
863         int bot_pit = bot.pit();
864         if (bot_pit > max_pit) {
865                 // FIXME: Why does this happen?
866                 LYXERR0("bottom pit is greater that max pit: "
867                         << bot_pit << " > " << max_pit);
868                 bot_pit = max_pit;
869         }
870
871         if (bot_pit == tm.first().first - 1)
872                 tm.newParMetricsUp();
873         else if (bot_pit == tm.last().first + 1)
874                 tm.newParMetricsDown();
875
876         if (tm.contains(bot_pit)) {
877                 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
878                 LASSERT(!pm.rows().empty(), /**/);
879                 // FIXME: smooth scrolling doesn't work in mathed.
880                 CursorSlice const & cs = dit.innerTextSlice();
881                 int offset = coordOffset(dit).y_;
882                 int ypos = pm.position() + offset;
883                 Dimension const & row_dim =
884                         pm.getRow(cs.pos(), dit.boundary()).dimension();
885                 int scrolled = 0;
886                 if (recenter)
887                         scrolled = scroll(ypos - height_/2);
888
889                 // If the top part of the row falls of the screen, we scroll
890                 // up to align the top of the row with the top of the screen.
891                 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
892                         int ynew = row_dim.ascent();
893                         if (ynew > height_ - row_dim.descent())
894                                 // FIXME: Recursively find the rowheight of the row in the inset
895                                 // until we find a row which can be visualized completely.
896                                 ynew = height_ - defaultRowHeight();
897                         int const scroll = ynew - ypos;
898                         scrolled = scrollUp(scroll);
899                 }
900
901                 // If the bottom of the row falls of the screen, we scroll down.
902                 // However, we have to be careful not to scroll that much that
903                 // the top falls of the screen.
904                 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
905                         int ynew = height_ - row_dim.descent();
906                         if (ynew < row_dim.ascent())
907                                 // FIXME: Recursively find the rowheight of the row in the inset
908                                 // until we find a row which can be visualized completely.
909                                 ynew = defaultRowHeight();
910                         int const scroll = ypos - ynew;
911                         scrolled = scrollDown(scroll);
912                 }
913
914                 // else, nothing to do, the cursor is already visible so we just return.
915                 return scrolled != 0;
916         }
917
918         // fix inline completion position
919         if (d->inlineCompletionPos_.fixIfBroken())
920                 d->inlineCompletionPos_ = DocIterator();
921
922         tm.redoParagraph(bot_pit);
923         ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
924         int offset = coordOffset(dit).y_;
925
926         d->anchor_pit_ = bot_pit;
927         CursorSlice const & cs = dit.innerTextSlice();
928         Dimension const & row_dim =
929                 pm.getRow(cs.pos(), dit.boundary()).dimension();
930
931         if (recenter)
932                 d->anchor_ypos_ = height_/2;
933         else if (d->anchor_pit_ == 0)
934                 d->anchor_ypos_ = offset + pm.ascent();
935         else if (d->anchor_pit_ == max_pit)
936                 d->anchor_ypos_ = height_ - offset - row_dim.descent();
937         else if (offset > height_)
938                 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
939         else
940                 d->anchor_ypos_ = defaultRowHeight() * 2;
941
942         return true;
943 }
944
945
946 void BufferView::updateDocumentClass(DocumentClass const * const olddc)
947 {
948         message(_("Converting document to new document class..."));
949         
950         StableDocIterator backcur(d->cursor_);
951         ErrorList & el = buffer_.errorList("Class Switch");
952         cap::switchBetweenClasses(
953                         olddc, buffer_.params().documentClassPtr(),
954                         static_cast<InsetText &>(buffer_.inset()), el);
955
956         setCursor(backcur.asDocIterator(&buffer_));
957
958         buffer_.errors("Class Switch");
959 }
960
961 /** Return the change status at cursor position, taking in account the
962  * status at each level of the document iterator (a table in a deleted
963  * footnote is deleted).
964  * When \param outer is true, the top slice is not looked at.
965  */
966 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
967 {
968         size_t const depth = dit.depth() - (outer ? 1 : 0);
969
970         for (size_t i = 0 ; i < depth ; ++i) {
971                 CursorSlice const & slice = dit[i];
972                 if (!slice.inset().inMathed()
973                     && slice.pos() < slice.paragraph().size()) {
974                         Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
975                         if (ch != Change::UNCHANGED)
976                                 return ch;
977                 }
978         }
979         return Change::UNCHANGED;
980 }
981
982
983 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
984 {
985         FuncCode const act = cmd.action();
986
987         // Can we use a readonly buffer?
988         if (buffer_.isReadonly()
989             && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
990             && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
991                 flag.message(from_utf8(N_("Document is read-only")));
992                 flag.setEnabled(false);
993                 return true;
994         }
995
996         // Are we in a DELETED change-tracking region?
997         if (lookupChangeType(d->cursor_, true) == Change::DELETED
998             && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
999             && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1000                 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1001                 flag.setEnabled(false);
1002                 return true;
1003         }
1004
1005         Cursor & cur = d->cursor_;
1006
1007         if (cur.getStatus(cmd, flag))
1008                 return true;
1009
1010         switch (act) {
1011
1012         // FIXME: This is a bit problematic because we don't check if this is
1013         // a document BufferView or not for these LFUNs. We probably have to
1014         // dispatch both to currentBufferView() and, if that fails,
1015         // to documentBufferView(); same as we do now for current Buffer and
1016         // document Buffer. Ideally those LFUN should go to Buffer as they
1017         // operate on the full Buffer and the cursor is only needed either for
1018         // an Undo record or to restore a cursor position. But we don't know
1019         // how to do that inside Buffer of course.
1020         case LFUN_BUFFER_PARAMS_APPLY:
1021         case LFUN_LAYOUT_MODULES_CLEAR:
1022         case LFUN_LAYOUT_MODULE_ADD:
1023         case LFUN_LAYOUT_RELOAD:
1024         case LFUN_TEXTCLASS_APPLY:
1025         case LFUN_TEXTCLASS_LOAD:
1026                 flag.setEnabled(!buffer_.isReadonly());
1027                 break;
1028
1029         case LFUN_UNDO:
1030                 // We do not use the LyXAction flag for readonly because Undo sets the
1031                 // buffer clean/dirty status by itself.
1032                 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1033                 break;
1034         case LFUN_REDO:
1035                 // We do not use the LyXAction flag for readonly because Redo sets the
1036                 // buffer clean/dirty status by itself.
1037                 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1038                 break;
1039         case LFUN_FILE_INSERT:
1040         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1041         case LFUN_FILE_INSERT_PLAINTEXT:
1042         case LFUN_BOOKMARK_SAVE:
1043                 // FIXME: Actually, these LFUNS should be moved to Text
1044                 flag.setEnabled(cur.inTexted());
1045                 break;
1046
1047         case LFUN_FONT_STATE:
1048         case LFUN_LABEL_INSERT:
1049         case LFUN_INFO_INSERT:
1050         case LFUN_PARAGRAPH_GOTO:
1051         case LFUN_NOTE_NEXT:
1052         case LFUN_REFERENCE_NEXT:
1053         case LFUN_WORD_FIND:
1054         case LFUN_WORD_FIND_FORWARD:
1055         case LFUN_WORD_FIND_BACKWARD:
1056         case LFUN_WORD_FINDADV:
1057         case LFUN_WORD_REPLACE:
1058         case LFUN_MARK_OFF:
1059         case LFUN_MARK_ON:
1060         case LFUN_MARK_TOGGLE:
1061         case LFUN_SCREEN_RECENTER:
1062         case LFUN_SCREEN_SHOW_CURSOR:
1063         case LFUN_BIBTEX_DATABASE_ADD:
1064         case LFUN_BIBTEX_DATABASE_DEL:
1065         case LFUN_STATISTICS:
1066         case LFUN_BRANCH_ADD_INSERT:
1067         case LFUN_KEYMAP_OFF:
1068         case LFUN_KEYMAP_PRIMARY:
1069         case LFUN_KEYMAP_SECONDARY:
1070         case LFUN_KEYMAP_TOGGLE:
1071                 flag.setEnabled(true);
1072                 break;
1073
1074         case LFUN_LABEL_GOTO: {
1075                 flag.setEnabled(!cmd.argument().empty()
1076                     || getInsetByCode<InsetRef>(cur, REF_CODE));
1077                 break;
1078         }
1079
1080         case LFUN_CHANGES_TRACK:
1081                 flag.setEnabled(true);
1082                 flag.setOnOff(buffer_.params().trackChanges);
1083                 break;
1084
1085         case LFUN_CHANGES_OUTPUT:
1086                 flag.setEnabled(true);
1087                 flag.setOnOff(buffer_.params().outputChanges);
1088                 break;
1089
1090         case LFUN_CHANGES_MERGE:
1091         case LFUN_CHANGE_NEXT:
1092         case LFUN_CHANGE_PREVIOUS:
1093         case LFUN_ALL_CHANGES_ACCEPT:
1094         case LFUN_ALL_CHANGES_REJECT:
1095                 // TODO: context-sensitive enabling of LFUNs
1096                 // In principle, these command should only be enabled if there
1097                 // is a change in the document. However, without proper
1098                 // optimizations, this will inevitably result in poor performance.
1099                 flag.setEnabled(true);
1100                 break;
1101
1102         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1103                 flag.setOnOff(buffer_.params().compressed);
1104                 break;
1105         }
1106
1107         case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
1108                 flag.setOnOff(buffer_.params().output_sync);
1109                 break;
1110         }
1111
1112         case LFUN_SCREEN_UP:
1113         case LFUN_SCREEN_DOWN:
1114         case LFUN_SCROLL:
1115         case LFUN_SCREEN_UP_SELECT:
1116         case LFUN_SCREEN_DOWN_SELECT:
1117         case LFUN_INSET_FORALL:
1118                 flag.setEnabled(true);
1119                 break;
1120
1121         case LFUN_LAYOUT_TABULAR:
1122                 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1123                 break;
1124
1125         case LFUN_LAYOUT:
1126                 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1127                 break;
1128
1129         case LFUN_LAYOUT_PARAGRAPH:
1130                 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1131                 break;
1132
1133         case LFUN_DIALOG_SHOW_NEW_INSET:
1134                 // FIXME: this is wrong, but I do not understand the
1135                 // intent (JMarc)
1136                 if (cur.inset().lyxCode() == CAPTION_CODE)
1137                         return cur.inset().getStatus(cur, cmd, flag);
1138                 // FIXME we should consider passthru paragraphs too.
1139                 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1140                 break;
1141
1142         case LFUN_CITATION_INSERT: {
1143                 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1144                 // FIXME: This could turn in a recursive hell.
1145                 // Shouldn't we use Buffer::getStatus() instead?
1146                 flag.setEnabled(lyx::getStatus(fr).enabled());
1147                 break;
1148         }
1149         case LFUN_INSET_APPLY: {
1150                 string const name = cmd.getArg(0);
1151                 Inset * inset = editedInset(name);
1152                 if (inset) {
1153                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1154                         if (!inset->getStatus(cur, fr, flag)) {
1155                                 // Every inset is supposed to handle this
1156                                 LASSERT(false, break);
1157                         }
1158                 } else {
1159                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1160                         flag = lyx::getStatus(fr);
1161                 }
1162                 break;
1163         }
1164
1165         default:
1166                 return false;
1167         }
1168
1169         return true;
1170 }
1171
1172
1173 Inset * BufferView::editedInset(string const & name) const
1174 {
1175         map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1176         return it == d->edited_insets_.end() ? 0 : it->second;
1177 }
1178
1179
1180 void BufferView::editInset(string const & name, Inset * inset)
1181 {
1182         d->edited_insets_[name] = inset;
1183 }
1184
1185
1186 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1187 {
1188         //lyxerr << [ cmd = " << cmd << "]" << endl;
1189
1190         // Make sure that the cached BufferView is correct.
1191         LYXERR(Debug::ACTION, " action[" << cmd.action() << ']'
1192                 << " arg[" << to_utf8(cmd.argument()) << ']'
1193                 << " x[" << cmd.x() << ']'
1194                 << " y[" << cmd.y() << ']'
1195                 << " button[" << cmd.button() << ']');
1196
1197         string const argument = to_utf8(cmd.argument());
1198         Cursor & cur = d->cursor_;
1199
1200         // Don't dispatch function that does not apply to internal buffers.
1201         if (buffer_.isInternal() 
1202             && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1203                 return;
1204
1205         // We'll set this back to false if need be.
1206         bool dispatched = true;
1207         buffer_.undo().beginUndoGroup();
1208
1209         FuncCode const act = cmd.action();
1210         switch (act) {
1211
1212         case LFUN_BUFFER_PARAMS_APPLY: {
1213                 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1214                 cur.recordUndoFullDocument();
1215                 istringstream ss(to_utf8(cmd.argument()));
1216                 Lexer lex;
1217                 lex.setStream(ss);
1218                 int const unknown_tokens = buffer_.readHeader(lex);
1219                 if (unknown_tokens != 0) {
1220                         LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1221                                                 << unknown_tokens << " unknown token"
1222                                                 << (unknown_tokens == 1 ? "" : "s"));
1223                 }
1224                 updateDocumentClass(oldClass);
1225                         
1226                 // We are most certainly here because of a change in the document
1227                 // It is then better to make sure that all dialogs are in sync with
1228                 // current document settings.
1229                 dr.screenUpdate(Update::Force | Update::FitCursor);
1230                 dr.forceBufferUpdate();
1231                 break;
1232         }
1233                 
1234         case LFUN_LAYOUT_MODULES_CLEAR: {
1235                 DocumentClass const * const oldClass =
1236                         buffer_.params().documentClassPtr();
1237                 cur.recordUndoFullDocument();
1238                 buffer_.params().clearLayoutModules();
1239                 buffer_.params().makeDocumentClass();
1240                 updateDocumentClass(oldClass);
1241                 dr.screenUpdate(Update::Force);
1242                 dr.forceBufferUpdate();
1243                 break;
1244         }
1245
1246         case LFUN_LAYOUT_MODULE_ADD: {
1247                 BufferParams const & params = buffer_.params();
1248                 if (!params.moduleCanBeAdded(argument)) {
1249                         LYXERR0("Module `" << argument << 
1250                                 "' cannot be added due to failed requirements or "
1251                                 "conflicts with installed modules.");
1252                         break;
1253                 }
1254                 DocumentClass const * const oldClass = params.documentClassPtr();
1255                 cur.recordUndoFullDocument();
1256                 buffer_.params().addLayoutModule(argument);
1257                 buffer_.params().makeDocumentClass();
1258                 updateDocumentClass(oldClass);
1259                 dr.screenUpdate(Update::Force);
1260                 dr.forceBufferUpdate();
1261                 break;
1262         }
1263
1264         case LFUN_TEXTCLASS_APPLY: {
1265                 // since this shortcircuits, the second call is made only if 
1266                 // the first fails
1267                 bool const success = 
1268                         LayoutFileList::get().load(argument, buffer_.temppath()) ||
1269                         LayoutFileList::get().load(argument, buffer_.filePath());
1270                 if (!success) {
1271                         docstring s = bformat(_("The document class `%1$s' "
1272                                                  "could not be loaded."), from_utf8(argument));
1273                         frontend::Alert::error(_("Could not load class"), s);
1274                         break;
1275                 }
1276
1277                 LayoutFile const * old_layout = buffer_.params().baseClass();
1278                 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1279
1280                 if (old_layout == new_layout)
1281                         // nothing to do
1282                         break;
1283
1284                 // Save the old, possibly modular, layout for use in conversion.
1285                 DocumentClass const * const oldDocClass =
1286                         buffer_.params().documentClassPtr();
1287                 cur.recordUndoFullDocument();
1288                 buffer_.params().setBaseClass(argument);
1289                 buffer_.params().makeDocumentClass();
1290                 updateDocumentClass(oldDocClass);
1291                 dr.screenUpdate(Update::Force);
1292                 dr.forceBufferUpdate();
1293                 break;
1294         }
1295
1296         case LFUN_TEXTCLASS_LOAD: {
1297                 // since this shortcircuits, the second call is made only if 
1298                 // the first fails
1299                 bool const success = 
1300                         LayoutFileList::get().load(argument, buffer_.temppath()) ||
1301                         LayoutFileList::get().load(argument, buffer_.filePath());
1302                 if (!success) {                 
1303                         docstring s = bformat(_("The document class `%1$s' "
1304                                                  "could not be loaded."), from_utf8(argument));
1305                         frontend::Alert::error(_("Could not load class"), s);
1306                 }
1307                 break;
1308         }
1309
1310         case LFUN_LAYOUT_RELOAD: {
1311                 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1312                 LayoutFileIndex bc = buffer_.params().baseClassID();
1313                 LayoutFileList::get().reset(bc);
1314                 buffer_.params().setBaseClass(bc);
1315                 buffer_.params().makeDocumentClass();
1316                 updateDocumentClass(oldClass);
1317                 dr.screenUpdate(Update::Force);
1318                 dr.forceBufferUpdate();
1319                 break;
1320         }
1321
1322         case LFUN_UNDO:
1323                 dr.setMessage(_("Undo"));
1324                 cur.clearSelection();
1325                 if (!cur.textUndo())
1326                         dr.setMessage(_("No further undo information"));
1327                 else
1328                         dr.screenUpdate(Update::Force | Update::FitCursor);
1329                 dr.forceBufferUpdate();
1330                 break;
1331
1332         case LFUN_REDO:
1333                 dr.setMessage(_("Redo"));
1334                 cur.clearSelection();
1335                 if (!cur.textRedo())
1336                         dr.setMessage(_("No further redo information"));
1337                 else
1338                         dr.screenUpdate(Update::Force | Update::FitCursor);
1339                 dr.forceBufferUpdate();
1340                 break;
1341
1342         case LFUN_FONT_STATE:
1343                 dr.setMessage(cur.currentState());
1344                 break;
1345
1346         case LFUN_BOOKMARK_SAVE:
1347                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1348                 break;
1349
1350         case LFUN_LABEL_GOTO: {
1351                 docstring label = cmd.argument();
1352                 if (label.empty()) {
1353                         InsetRef * inset =
1354                                 getInsetByCode<InsetRef>(cur, REF_CODE);
1355                         if (inset) {
1356                                 label = inset->getParam("reference");
1357                                 // persistent=false: use temp_bookmark
1358                                 saveBookmark(0);
1359                         }
1360                 }
1361                 if (!label.empty()) {
1362                         gotoLabel(label);
1363                         // at the moment, this is redundant, since gotoLabel will
1364                         // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1365                         // to have it here.
1366                         dr.screenUpdate(Update::Force | Update::FitCursor);
1367                 }
1368                 break;
1369         }
1370         
1371         case LFUN_PARAGRAPH_GOTO: {
1372                 int const id = convert<int>(cmd.getArg(0));
1373                 int const pos = convert<int>(cmd.getArg(1));
1374                 int i = 0;
1375                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1376                         b = theBufferList().next(b)) {
1377
1378                         DocIterator dit = b->getParFromID(id);
1379                         if (dit.atEnd()) {
1380                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1381                                 ++i;
1382                                 continue;
1383                         }
1384                         LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1385                                 << " found in buffer `"
1386                                 << b->absFileName() << "'.");
1387
1388                         if (b == &buffer_) {
1389                                 // Set the cursor
1390                                 dit.pos() = pos;
1391                                 setCursor(dit);
1392                                 dr.screenUpdate(Update::Force | Update::FitCursor);
1393                         } else {
1394                                 // Switch to other buffer view and resend cmd
1395                                 lyx::dispatch(FuncRequest(
1396                                         LFUN_BUFFER_SWITCH, b->absFileName()));
1397                                 lyx::dispatch(cmd);
1398                         }
1399                         break;
1400                 }
1401                 break;
1402         }
1403
1404         case LFUN_NOTE_NEXT:
1405                 gotoInset(this, NOTE_CODE, false);
1406                 break;
1407
1408         case LFUN_REFERENCE_NEXT: {
1409                 vector<InsetCode> tmp;
1410                 tmp.push_back(LABEL_CODE);
1411                 tmp.push_back(REF_CODE);
1412                 gotoInset(this, tmp, true);
1413                 break;
1414         }
1415
1416         case LFUN_CHANGES_TRACK:
1417                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1418                 break;
1419
1420         case LFUN_CHANGES_OUTPUT:
1421                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1422                 if (buffer_.params().outputChanges) {
1423                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1424                         bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1425                                           LaTeXFeatures::isAvailable("xcolor");
1426
1427                         if (!dvipost && !xcolorulem) {
1428                                 Alert::warning(_("Changes not shown in LaTeX output"),
1429                                                _("Changes will not be highlighted in LaTeX output, "
1430                                                  "because neither dvipost nor xcolor/ulem are installed.\n"
1431                                                  "Please install these packages or redefine "
1432                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1433                         } else if (!xcolorulem) {
1434                                 Alert::warning(_("Changes not shown in LaTeX output"),
1435                                                _("Changes will not be highlighted in LaTeX output "
1436                                                  "when using pdflatex, because xcolor and ulem are not installed.\n"
1437                                                  "Please install both packages or redefine "
1438                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1439                         }
1440                 }
1441                 break;
1442
1443         case LFUN_CHANGE_NEXT:
1444                 findNextChange(this);
1445                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1446                 dr.screenUpdate(Update::Force | Update::FitCursor);
1447                 break;
1448         
1449         case LFUN_CHANGE_PREVIOUS:
1450                 findPreviousChange(this);
1451                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1452                 dr.screenUpdate(Update::Force | Update::FitCursor);
1453                 break;
1454
1455         case LFUN_CHANGES_MERGE:
1456                 if (findNextChange(this) || findPreviousChange(this)) {
1457                         dr.screenUpdate(Update::Force | Update::FitCursor);
1458                         dr.forceBufferUpdate();
1459                         showDialog("changes");
1460                 }
1461                 break;
1462
1463         case LFUN_ALL_CHANGES_ACCEPT:
1464                 // select complete document
1465                 cur.reset();
1466                 cur.selHandle(true);
1467                 buffer_.text().cursorBottom(cur);
1468                 // accept everything in a single step to support atomic undo
1469                 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1470                 cur.resetAnchor();
1471                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1472                 dr.screenUpdate(Update::Force | Update::FitCursor);
1473                 dr.forceBufferUpdate();
1474                 break;
1475
1476         case LFUN_ALL_CHANGES_REJECT:
1477                 // select complete document
1478                 cur.reset();
1479                 cur.selHandle(true);
1480                 buffer_.text().cursorBottom(cur);
1481                 // reject everything in a single step to support atomic undo
1482                 // Note: reject does not work recursively; the user may have to repeat the operation
1483                 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1484                 cur.resetAnchor();
1485                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1486                 dr.screenUpdate(Update::Force | Update::FitCursor);
1487                 dr.forceBufferUpdate();
1488                 break;
1489
1490         case LFUN_WORD_FIND_FORWARD:
1491         case LFUN_WORD_FIND_BACKWARD: {
1492                 static docstring last_search;
1493                 docstring searched_string;
1494
1495                 if (!cmd.argument().empty()) {
1496                         last_search = cmd.argument();
1497                         searched_string = cmd.argument();
1498                 } else {
1499                         searched_string = last_search;
1500                 }
1501
1502                 if (searched_string.empty())
1503                         break;
1504
1505                 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1506                 docstring const data =
1507                         find2string(searched_string, true, false, fw);
1508                 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1509                 if (found)
1510                         dr.screenUpdate(Update::Force | Update::FitCursor);
1511                 break;
1512         }
1513
1514         case LFUN_WORD_FIND: {
1515                 FuncRequest req = cmd;
1516                 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1517                         req = d->search_request_cache_;
1518                 if (req.argument().empty()) {
1519                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1520                         break;
1521                 }
1522                 if (lyxfind(this, req))
1523                         dr.screenUpdate(Update::Force | Update::FitCursor);
1524                 else
1525                         message(_("String not found!"));
1526                 d->search_request_cache_ = req;
1527                 break;
1528         }
1529
1530         case LFUN_WORD_REPLACE: {
1531                 bool has_deleted = false;
1532                 if (cur.selection()) {
1533                         DocIterator beg = cur.selectionBegin();
1534                         DocIterator end = cur.selectionEnd();
1535                         if (beg.pit() == end.pit()) {
1536                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1537                                         if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1538                                                 has_deleted = true;
1539                                                 break;
1540                                         }
1541                                 }
1542                         }
1543                 }
1544                 if (lyxreplace(this, cmd, has_deleted)) {
1545                         dr.forceBufferUpdate();
1546                         dr.screenUpdate(Update::Force | Update::FitCursor);
1547                 }
1548                 break;
1549         }
1550
1551         case LFUN_WORD_FINDADV: {
1552                 FindAndReplaceOptions opt;
1553                 istringstream iss(to_utf8(cmd.argument()));
1554                 iss >> opt;
1555                 if (findAdv(this, opt)) {
1556                         dr.screenUpdate(Update::Force | Update::FitCursor);
1557                         cur.dispatched();
1558                         dispatched = true;
1559                 } else {
1560                         cur.undispatched();
1561                         dispatched = false;
1562                 }
1563                 break;
1564         }
1565
1566         case LFUN_MARK_OFF:
1567                 cur.clearSelection();
1568                 dr.setMessage(from_utf8(N_("Mark off")));
1569                 break;
1570
1571         case LFUN_MARK_ON:
1572                 cur.clearSelection();
1573                 cur.setMark(true);
1574                 dr.setMessage(from_utf8(N_("Mark on")));
1575                 break;
1576
1577         case LFUN_MARK_TOGGLE:
1578                 cur.setSelection(false);
1579                 if (cur.mark()) {
1580                         cur.setMark(false);
1581                         dr.setMessage(from_utf8(N_("Mark removed")));
1582                 } else {
1583                         cur.setMark(true);
1584                         dr.setMessage(from_utf8(N_("Mark set")));
1585                 }
1586                 cur.resetAnchor();
1587                 break;
1588
1589         case LFUN_SCREEN_SHOW_CURSOR:
1590                 showCursor();
1591                 break;
1592         
1593         case LFUN_SCREEN_RECENTER:
1594                 recenter();
1595                 break;
1596
1597         case LFUN_BIBTEX_DATABASE_ADD: {
1598                 Cursor tmpcur = cur;
1599                 findInset(tmpcur, BIBTEX_CODE, false);
1600                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1601                                                 BIBTEX_CODE);
1602                 if (inset) {
1603                         if (inset->addDatabase(cmd.argument())) {
1604                                 buffer_.invalidateBibfileCache();
1605                                 dr.forceBufferUpdate();
1606                         }
1607                 }
1608                 break;
1609         }
1610
1611         case LFUN_BIBTEX_DATABASE_DEL: {
1612                 Cursor tmpcur = cur;
1613                 findInset(tmpcur, BIBTEX_CODE, false);
1614                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1615                                                 BIBTEX_CODE);
1616                 if (inset) {
1617                         if (inset->delDatabase(cmd.argument())) {
1618                                 buffer_.invalidateBibfileCache();
1619                                 dr.forceBufferUpdate();
1620                         }                               
1621                 }
1622                 break;
1623         }
1624
1625         case LFUN_STATISTICS: {
1626                 DocIterator from, to;
1627                 if (cur.selection()) {
1628                         from = cur.selectionBegin();
1629                         to = cur.selectionEnd();
1630                 } else {
1631                         from = doc_iterator_begin(&buffer_);
1632                         to = doc_iterator_end(&buffer_);
1633                 }
1634                 int const words = countWords(from, to);
1635                 int const chars = countChars(from, to, false);
1636                 int const chars_blanks = countChars(from, to, true);
1637                 docstring message;
1638                 if (cur.selection())
1639                         message = _("Statistics for the selection:");
1640                 else
1641                         message = _("Statistics for the document:");
1642                 message += "\n\n";
1643                 if (words != 1)
1644                         message += bformat(_("%1$d words"), words);
1645                 else
1646                         message += _("One word");
1647                 message += "\n";
1648                 if (chars_blanks != 1)
1649                         message += bformat(_("%1$d characters (including blanks)"),
1650                                           chars_blanks);
1651                 else
1652                         message += _("One character (including blanks)");
1653                 message += "\n";
1654                 if (chars != 1)
1655                         message += bformat(_("%1$d characters (excluding blanks)"),
1656                                           chars);
1657                 else
1658                         message += _("One character (excluding blanks)");
1659
1660                 Alert::information(_("Statistics"), message);
1661         }
1662                 break;
1663
1664         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1665                 // turn compression on/off
1666                 buffer_.params().compressed = !buffer_.params().compressed;
1667                 break;
1668
1669         case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
1670                 buffer_.params().output_sync = !buffer_.params().output_sync;
1671                 break;
1672
1673         case LFUN_SCREEN_UP:
1674         case LFUN_SCREEN_DOWN: {
1675                 Point p = getPos(cur);
1676                 // This code has been commented out to enable to scroll down a
1677                 // document, even if there are large insets in it (see bug #5465).
1678                 /*if (p.y_ < 0 || p.y_ > height_) {
1679                         // The cursor is off-screen so recenter before proceeding.
1680                         showCursor();
1681                         p = getPos(cur);
1682                 }*/
1683                 int const scrolled = scroll(act == LFUN_SCREEN_UP
1684                         ? -height_ : height_);
1685                 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1686                         p = Point(0, 0);
1687                 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1688                         p = Point(width_, height_);
1689                 Cursor old = cur;
1690                 bool const in_texted = cur.inTexted();
1691                 cur.reset();
1692                 buffer_.changed(true);
1693                 updateHoveredInset();
1694
1695                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1696                         true, act == LFUN_SCREEN_UP); 
1697                 cur.resetAnchor();
1698                 //FIXME: what to do with cur.x_target()?
1699                 bool update = in_texted && cur.bv().checkDepm(cur, old);
1700                 cur.finishUndo();
1701                 if (update) {
1702                         dr.screenUpdate(Update::Force | Update::FitCursor);
1703                         dr.forceBufferUpdate();
1704                 }
1705                 break;
1706         }
1707
1708         case LFUN_SCROLL:
1709                 lfunScroll(cmd);
1710                 dr.forceBufferUpdate();
1711                 break;
1712
1713         case LFUN_SCREEN_UP_SELECT: {
1714                 cur.selHandle(true);
1715                 if (isTopScreen()) {
1716                         lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1717                         cur.finishUndo();
1718                         break;
1719                 }
1720                 int y = getPos(cur).y_;
1721                 int const ymin = y - height_ + defaultRowHeight();
1722                 while (y > ymin && cur.up())
1723                         y = getPos(cur).y_;
1724
1725                 cur.finishUndo();
1726                 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1727                 break;
1728         }
1729
1730         case LFUN_SCREEN_DOWN_SELECT: {
1731                 cur.selHandle(true);
1732                 if (isBottomScreen()) {
1733                         lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1734                         cur.finishUndo();
1735                         break;
1736                 }
1737                 int y = getPos(cur).y_;
1738                 int const ymax = y + height_ - defaultRowHeight();
1739                 while (y < ymax && cur.down())
1740                         y = getPos(cur).y_;
1741
1742                 cur.finishUndo();
1743                 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1744                 break;
1745         }
1746
1747
1748         // This would be in Buffer class if only Cursor did not
1749         // require a bufferview
1750         case LFUN_INSET_FORALL: {
1751                 docstring const name = from_utf8(cmd.getArg(0));
1752                 string const commandstr = cmd.getLongArg(1);
1753                 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1754
1755                 // an arbitrary number to limit number of iterations
1756                 const int max_iter = 10000;
1757                 int iterations = 0;
1758                 Cursor & cur = d->cursor_;
1759                 Cursor const savecur = cur;
1760                 cur.reset();
1761                 if (!cur.nextInset())
1762                         cur.forwardInset();
1763                 cur.beginUndoGroup();
1764                 while(cur && iterations < max_iter) {
1765                         Inset * ins = cur.nextInset();
1766                         if (!ins)
1767                                 break;
1768                         docstring insname = ins->layoutName();
1769                         while (!insname.empty()) {
1770                                 if (insname == name || name == from_utf8("*")) {
1771                                         cur.recordUndo();
1772                                         lyx::dispatch(fr, dr);
1773                                         ++iterations;
1774                                         break;
1775                                 }
1776                                 size_t const i = insname.rfind(':');
1777                                 if (i == string::npos)
1778                                         break;
1779                                 insname = insname.substr(0, i);
1780                         }
1781                         cur.forwardInset();
1782                 }
1783                 cur.endUndoGroup();
1784                 cur = savecur;
1785                 cur.fixIfBroken();
1786                 dr.screenUpdate(Update::Force);
1787                 dr.forceBufferUpdate();
1788
1789                 if (iterations >= max_iter) {
1790                         dr.setError(true);
1791                         dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1792                 } else
1793                         dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1794                 break;
1795         }
1796
1797
1798         case LFUN_BRANCH_ADD_INSERT: {
1799                 docstring branch_name = from_utf8(cmd.getArg(0));
1800                 if (branch_name.empty())
1801                         if (!Alert::askForText(branch_name, _("Branch name")) ||
1802                                                 branch_name.empty())
1803                                 break;
1804
1805                 DispatchResult drtmp;
1806                 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1807                 if (drtmp.error()) {
1808                         Alert::warning(_("Branch already exists"), drtmp.message());
1809                         break;
1810                 }
1811                 BranchList & branch_list = buffer_.params().branchlist();
1812                 vector<docstring> const branches =
1813                         getVectorFromString(branch_name, branch_list.separator());
1814                 for (vector<docstring>::const_iterator it = branches.begin();
1815                      it != branches.end(); ++it) {
1816                         branch_name = *it;
1817                         lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1818                 }
1819                 break;
1820         }
1821
1822         case LFUN_KEYMAP_OFF:
1823                 getIntl().keyMapOn(false);
1824                 break;
1825
1826         case LFUN_KEYMAP_PRIMARY:
1827                 getIntl().keyMapPrim();
1828                 break;
1829
1830         case LFUN_KEYMAP_SECONDARY:
1831                 getIntl().keyMapSec();
1832                 break;
1833
1834         case LFUN_KEYMAP_TOGGLE:
1835                 getIntl().toggleKeyMap();
1836                 break;
1837
1838         case LFUN_DIALOG_SHOW_NEW_INSET: {
1839                 string const name = cmd.getArg(0);
1840                 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1841                 if (decodeInsetParam(name, data, buffer_))
1842                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1843                 else
1844                         lyxerr << "Inset type '" << name << 
1845                         "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" <<  endl;
1846                 break;
1847         }
1848
1849         case LFUN_CITATION_INSERT: {
1850                 if (argument.empty()) {
1851                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1852                         break;
1853                 }
1854                 // we can have one optional argument, delimited by '|'
1855                 // citation-insert <key>|<text_before>
1856                 // this should be enhanced to also support text_after
1857                 // and citation style
1858                 string arg = argument;
1859                 string opt1;
1860                 if (contains(argument, "|")) {
1861                         arg = token(argument, '|', 0);
1862                         opt1 = token(argument, '|', 1);
1863                 }
1864                 InsetCommandParams icp(CITE_CODE);
1865                 icp["key"] = from_utf8(arg);
1866                 if (!opt1.empty())
1867                         icp["before"] = from_utf8(opt1);
1868                 string icstr = InsetCommand::params2string(icp);
1869                 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1870                 lyx::dispatch(fr);
1871                 break;
1872         }
1873
1874         case LFUN_INSET_APPLY: {
1875                 string const name = cmd.getArg(0);
1876                 Inset * inset = editedInset(name);
1877                 if (!inset) {
1878                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1879                         lyx::dispatch(fr);
1880                         break;
1881                 }
1882                 // put cursor in front of inset.
1883                 if (!setCursorFromInset(inset)) {
1884                         LASSERT(false, break);
1885                 }
1886                 cur.recordUndo();
1887                 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1888                 inset->dispatch(cur, fr);
1889                 dr.screenUpdate(cur.result().screenUpdate());
1890                 if (cur.result().needBufferUpdate())
1891                         dr.forceBufferUpdate();
1892                 break;
1893         }
1894
1895         // FIXME:
1896         // The change of language of buffer belongs to the Buffer class.
1897         // We have to do it here because we need a cursor for Undo.
1898         // When Undo::recordUndoBufferParams() is implemented someday
1899         // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
1900         case LFUN_BUFFER_LANGUAGE: {
1901                 Language const * oldL = buffer_.params().language;
1902                 Language const * newL = languages.getLanguage(argument);
1903                 if (!newL || oldL == newL)
1904                         break;
1905                 if (oldL->rightToLeft() == newL->rightToLeft() && !buffer_.isMultiLingual()) {
1906                         cur.recordUndoFullDocument();
1907                         buffer_.changeLanguage(oldL, newL);
1908                         cur.setCurrentFont();
1909                         dr.forceBufferUpdate();
1910                 }
1911                 break;
1912         }
1913
1914         default:
1915                 // OK, so try the Buffer itself...
1916                 buffer_.dispatch(cmd, dr);
1917                 dispatched = dr.dispatched();
1918                 break;
1919         }
1920
1921         buffer_.undo().endUndoGroup();
1922         dr.dispatched(dispatched);
1923 }
1924
1925
1926 docstring const BufferView::requestSelection()
1927 {
1928         Cursor & cur = d->cursor_;
1929
1930         LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1931         if (!cur.selection()) {
1932                 d->xsel_cache_.set = false;
1933                 return docstring();
1934         }
1935
1936         LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1937         if (!d->xsel_cache_.set ||
1938             cur.top() != d->xsel_cache_.cursor ||
1939             cur.realAnchor().top() != d->xsel_cache_.anchor)
1940         {
1941                 d->xsel_cache_.cursor = cur.top();
1942                 d->xsel_cache_.anchor = cur.realAnchor().top();
1943                 d->xsel_cache_.set = cur.selection();
1944                 return cur.selectionAsString(false);
1945         }
1946         return docstring();
1947 }
1948
1949
1950 void BufferView::clearSelection()
1951 {
1952         d->cursor_.clearSelection();
1953         // Clear the selection buffer. Otherwise a subsequent
1954         // middle-mouse-button paste would use the selection buffer,
1955         // not the more current external selection.
1956         cap::clearSelection();
1957         d->xsel_cache_.set = false;
1958         // The buffer did not really change, but this causes the
1959         // redraw we need because we cleared the selection above.
1960         buffer_.changed(false);
1961 }
1962
1963
1964 void BufferView::resize(int width, int height)
1965 {
1966         // Update from work area
1967         width_ = width;
1968         height_ = height;
1969
1970         // Clear the paragraph height cache.
1971         d->par_height_.clear();
1972         // Redo the metrics.
1973         updateMetrics();
1974 }
1975
1976
1977 Inset const * BufferView::getCoveringInset(Text const & text,
1978                 int x, int y) const
1979 {
1980         TextMetrics & tm = d->text_metrics_[&text];
1981         Inset * inset = tm.checkInsetHit(x, y);
1982         if (!inset)
1983                 return 0;
1984
1985         if (!inset->descendable(*this))
1986                 // No need to go further down if the inset is not
1987                 // descendable.
1988                 return inset;
1989
1990         size_t cell_number = inset->nargs();
1991         // Check all the inner cell.
1992         for (size_t i = 0; i != cell_number; ++i) {
1993                 Text const * inner_text = inset->getText(i);
1994                 if (inner_text) {
1995                         // Try deeper.
1996                         Inset const * inset_deeper =
1997                                 getCoveringInset(*inner_text, x, y);
1998                         if (inset_deeper)
1999                                 return inset_deeper;
2000                 }
2001         }
2002
2003         return inset;
2004 }
2005
2006
2007 void BufferView::updateHoveredInset() const
2008 {
2009         // Get inset under mouse, if there is one.
2010         int const x = d->mouse_position_cache_.x_;
2011         int const y = d->mouse_position_cache_.y_;
2012         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2013
2014         d->clickable_inset_ = covering_inset && covering_inset->clickable(x, y);
2015
2016         if (covering_inset == d->last_inset_)
2017                 // Same inset, no need to do anything...
2018                 return;
2019
2020         bool need_redraw = false;
2021         if (d->last_inset_) {
2022                 // Remove the hint on the last hovered inset (if any).
2023                 need_redraw |= d->last_inset_->setMouseHover(this, false);
2024                 d->last_inset_ = 0;
2025         }
2026         
2027         if (covering_inset && covering_inset->setMouseHover(this, true)) {
2028                 need_redraw = true;
2029                 // Only the insets that accept the hover state, do 
2030                 // clear the last_inset_, so only set the last_inset_
2031                 // member if the hovered setting is accepted.
2032                 d->last_inset_ = covering_inset;
2033         }
2034
2035         if (need_redraw) {
2036                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2037                                 << d->mouse_position_cache_.x_ << ", " 
2038                                 << d->mouse_position_cache_.y_ << ")");
2039         
2040                 d->update_strategy_ = DecorationUpdate;
2041
2042                 // This event (moving without mouse click) is not passed further.
2043                 // This should be changed if it is further utilized.
2044                 buffer_.changed(false);
2045         }
2046 }
2047
2048
2049 void BufferView::clearLastInset(Inset * inset) const
2050 {
2051         if (d->last_inset_ != inset) {
2052                 LYXERR0("Wrong last_inset!");
2053                 LASSERT(false, /**/);
2054         }
2055         d->last_inset_ = 0;
2056 }
2057
2058
2059 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2060 {
2061         //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2062
2063         // This is only called for mouse related events including
2064         // LFUN_FILE_OPEN generated by drag-and-drop.
2065         FuncRequest cmd = cmd0;
2066
2067         Cursor old = cursor();
2068         Cursor cur(*this);
2069         cur.push(buffer_.inset());
2070         cur.setSelection(d->cursor_.selection());
2071
2072         // Either the inset under the cursor or the
2073         // surrounding Text will handle this event.
2074
2075         // make sure we stay within the screen...
2076         cmd.set_y(min(max(cmd.y(), -1), height_));
2077
2078         d->mouse_position_cache_.x_ = cmd.x();
2079         d->mouse_position_cache_.y_ = cmd.y();
2080
2081         if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2082                 updateHoveredInset();
2083                 return;
2084         }
2085
2086         // Build temporary cursor.
2087         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2088
2089         // Put anchor at the same position.
2090         cur.resetAnchor();
2091
2092         cur.beginUndoGroup();
2093
2094         // Try to dispatch to an non-editable inset near this position
2095         // via the temp cursor. If the inset wishes to change the real
2096         // cursor it has to do so explicitly by using
2097         //  cur.bv().cursor() = cur;  (or similar)
2098         if (inset)
2099                 inset->dispatch(cur, cmd);
2100
2101         // Now dispatch to the temporary cursor. If the real cursor should
2102         // be modified, the inset's dispatch has to do so explicitly.
2103         if (!inset || !cur.result().dispatched())
2104                 cur.dispatch(cmd);
2105
2106         cur.endUndoGroup();
2107
2108         // Notify left insets
2109         if (cur != old) {
2110                 old.fixIfBroken();
2111                 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
2112                 if (badcursor)
2113                         cursor().fixIfBroken();
2114         }
2115         
2116         // Do we have a selection?
2117         theSelection().haveSelection(cursor().selection());
2118
2119         if (cur.needBufferUpdate()) {
2120                 cur.clearBufferUpdate();
2121                 buffer().updateBuffer();
2122         }
2123
2124         // If the command has been dispatched,
2125         if (cur.result().dispatched() || cur.result().screenUpdate())
2126                 processUpdateFlags(cur.result().screenUpdate());
2127 }
2128
2129
2130 void BufferView::lfunScroll(FuncRequest const & cmd)
2131 {
2132         string const scroll_type = cmd.getArg(0);
2133         int scroll_step = 0;
2134         if (scroll_type == "line")
2135                 scroll_step = d->scrollbarParameters_.single_step;
2136         else if (scroll_type == "page")
2137                 scroll_step = d->scrollbarParameters_.page_step;
2138         else
2139                 return;
2140         string const scroll_quantity = cmd.getArg(1);
2141         if (scroll_quantity == "up")
2142                 scrollUp(scroll_step);
2143         else if (scroll_quantity == "down")
2144                 scrollDown(scroll_step);
2145         else {
2146                 int const scroll_value = convert<int>(scroll_quantity);
2147                 if (scroll_value)
2148                         scroll(scroll_step * scroll_value);
2149         }
2150         buffer_.changed(true);
2151         updateHoveredInset();
2152 }
2153
2154
2155 int BufferView::minVisiblePart()
2156 {
2157         return 2 * defaultRowHeight();
2158 }
2159
2160
2161 int BufferView::scroll(int y)
2162 {
2163         if (y > 0)
2164                 return scrollDown(y);
2165         if (y < 0)
2166                 return scrollUp(-y);
2167         return 0;
2168 }
2169
2170
2171 int BufferView::scrollDown(int offset)
2172 {
2173         Text * text = &buffer_.text();
2174         TextMetrics & tm = d->text_metrics_[text];
2175         int const ymax = height_ + offset;
2176         while (true) {
2177                 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2178                 int bottom_pos = last.second->position() + last.second->descent();
2179                 if (lyxrc.scroll_below_document)
2180                         bottom_pos += height_ - minVisiblePart();
2181                 if (last.first + 1 == int(text->paragraphs().size())) {
2182                         if (bottom_pos <= height_)
2183                                 return 0;
2184                         offset = min(offset, bottom_pos - height_);
2185                         break;
2186                 }
2187                 if (bottom_pos > ymax)
2188                         break;
2189                 tm.newParMetricsDown();
2190         }
2191         d->anchor_ypos_ -= offset;
2192         return -offset;
2193 }
2194
2195
2196 int BufferView::scrollUp(int offset)
2197 {
2198         Text * text = &buffer_.text();
2199         TextMetrics & tm = d->text_metrics_[text];
2200         int ymin = - offset;
2201         while (true) {
2202                 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2203                 int top_pos = first.second->position() - first.second->ascent();
2204                 if (first.first == 0) {
2205                         if (top_pos >= 0)
2206                                 return 0;
2207                         offset = min(offset, - top_pos);
2208                         break;
2209                 }
2210                 if (top_pos < ymin)
2211                         break;
2212                 tm.newParMetricsUp();
2213         }
2214         d->anchor_ypos_ += offset;
2215         return offset;
2216 }
2217
2218
2219 void BufferView::setCursorFromRow(int row)
2220 {
2221         int tmpid;
2222         int tmppos;
2223         pit_type newpit = 0;
2224         pos_type newpos = 0;
2225
2226         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
2227
2228         bool posvalid = (tmpid != -1);
2229         if (posvalid) {
2230                 // we need to make sure that the row and position
2231                 // we got back are valid, because the buffer may well
2232                 // have changed since we last generated the LaTeX.
2233                 DocIterator const dit = buffer_.getParFromID(tmpid);
2234                 if (dit == doc_iterator_end(&buffer_))
2235                         posvalid = false;
2236                 else {
2237                         newpit = dit.pit();
2238                         // now have to check pos.
2239                         newpos = tmppos;
2240                         Paragraph const & par = buffer_.text().getPar(newpit);
2241                         if (newpos > par.size()) {
2242                                 LYXERR0("Requested position no longer valid.");
2243                                 newpos = par.size() - 1;
2244                         }
2245                 }
2246         }
2247         if (!posvalid) {
2248                 frontend::Alert::error(_("Inverse Search Failed"),
2249                         _("Invalid position requested by inverse search.\n"
2250                     "You need to update the viewed document."));
2251                 return;
2252         }
2253         d->cursor_.reset();
2254         buffer_.text().setCursor(d->cursor_, newpit, newpos);
2255         d->cursor_.setSelection(false);
2256         d->cursor_.resetAnchor();
2257         recenter();
2258 }
2259
2260
2261 bool BufferView::setCursorFromInset(Inset const * inset)
2262 {
2263         // are we already there?
2264         if (cursor().nextInset() == inset)
2265                 return true;
2266
2267         // Inset is not at cursor position. Find it in the document.
2268         Cursor cur(*this);
2269         cur.reset();
2270         while (cur && cur.nextInset() != inset)
2271                 cur.forwardInset();
2272
2273         if (cur) {
2274                 setCursor(cur);
2275                 return true;
2276         }
2277         return false;
2278 }
2279
2280
2281 void BufferView::gotoLabel(docstring const & label)
2282 {
2283         ListOfBuffers bufs = buffer().allRelatives();
2284         ListOfBuffers::iterator it = bufs.begin();
2285         for (; it != bufs.end(); ++it) {
2286                 Buffer const * buf = *it;
2287
2288                 // find label
2289                 Toc & toc = buf->tocBackend().toc("label");
2290                 TocIterator toc_it = toc.begin();
2291                 TocIterator end = toc.end();
2292                 for (; toc_it != end; ++toc_it) {
2293                         if (label == toc_it->str()) {
2294                                 lyx::dispatch(toc_it->action());
2295                                 return;
2296                         }
2297                 }
2298         }
2299 }
2300
2301
2302 TextMetrics const & BufferView::textMetrics(Text const * t) const
2303 {
2304         return const_cast<BufferView *>(this)->textMetrics(t);
2305 }
2306
2307
2308 TextMetrics & BufferView::textMetrics(Text const * t)
2309 {
2310         LASSERT(t, /**/);
2311         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
2312         if (tmc_it == d->text_metrics_.end()) {
2313                 tmc_it = d->text_metrics_.insert(
2314                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2315         }
2316         return tmc_it->second;
2317 }
2318
2319
2320 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2321                 pit_type pit) const
2322 {
2323         return textMetrics(t).parMetrics(pit);
2324 }
2325
2326
2327 int BufferView::workHeight() const
2328 {
2329         return height_;
2330 }
2331
2332
2333 void BufferView::setCursor(DocIterator const & dit)
2334 {
2335         d->cursor_.reset();
2336         size_t const n = dit.depth();
2337         for (size_t i = 0; i < n; ++i)
2338                 dit[i].inset().edit(d->cursor_, true);
2339
2340         d->cursor_.setCursor(dit);
2341         d->cursor_.setSelection(false);
2342         // FIXME
2343         // It seems on general grounds as if this is probably needed, but
2344         // it is not yet clear.
2345         // See bug #7394 and r38388.
2346         // d->cursor.resetAnchor();
2347 }
2348
2349
2350 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2351 {
2352         // Would be wrong to delete anything if we have a selection.
2353         if (cur.selection())
2354                 return false;
2355
2356         bool need_anchor_change = false;
2357         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2358                 need_anchor_change);
2359
2360         if (need_anchor_change)
2361                 cur.resetAnchor();
2362
2363         if (!changed)
2364                 return false;
2365
2366         d->cursor_ = cur;
2367
2368         cur.forceBufferUpdate();
2369         buffer_.changed(true);
2370         return true;
2371 }
2372
2373
2374 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2375 {
2376         LASSERT(&cur.bv() == this, /**/);
2377
2378         if (!select)
2379                 // this event will clear selection so we save selection for
2380                 // persistent selection
2381                 cap::saveSelection(cursor());
2382
2383         d->cursor_.macroModeClose();
2384
2385         // Has the cursor just left the inset?
2386         bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2387         if (leftinset)
2388                 d->cursor_.fixIfBroken();
2389
2390         // FIXME: shift-mouse selection doesn't work well across insets.
2391         bool const do_selection = 
2392                         select && &d->cursor_.normalAnchor().inset() == &cur.inset();
2393
2394         // do the dEPM magic if needed
2395         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2396         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2397         // the leftinset bool would not be necessary (badcursor instead).
2398         bool update = leftinset;
2399         if (!do_selection && d->cursor_.inTexted())
2400                 update |= checkDepm(cur, d->cursor_);
2401
2402         if (!do_selection)
2403                 d->cursor_.resetAnchor();
2404         d->cursor_.setCursor(cur);
2405         d->cursor_.boundary(cur.boundary());
2406         if (do_selection)
2407                 d->cursor_.setSelection();
2408         else
2409                 d->cursor_.clearSelection();
2410
2411         d->cursor_.finishUndo();
2412         d->cursor_.setCurrentFont();
2413         if (update)
2414                 cur.forceBufferUpdate();
2415         return update;
2416 }
2417
2418
2419 void BufferView::putSelectionAt(DocIterator const & cur,
2420                                 int length, bool backwards)
2421 {
2422         d->cursor_.clearSelection();
2423
2424         setCursor(cur);
2425
2426         if (length) {
2427                 if (backwards) {
2428                         d->cursor_.pos() += length;
2429                         d->cursor_.setSelection(d->cursor_, -length);
2430                 } else
2431                         d->cursor_.setSelection(d->cursor_, length);
2432         }
2433 }
2434
2435
2436 bool BufferView::selectIfEmpty(DocIterator & cur)
2437 {
2438         if (!cur.paragraph().empty())
2439                 return false;
2440
2441         pit_type const beg_pit = cur.pit();
2442         if (beg_pit > 0) {
2443                 // The paragraph associated to this item isn't
2444                 // the first one, so it can be selected
2445                 cur.backwardPos();
2446         } else {
2447                 // We have to resort to select the space between the
2448                 // end of this item and the begin of the next one
2449                 cur.forwardPos();
2450         }
2451         if (cur.empty()) {
2452                 // If it is the only item in the document,
2453                 // nothing can be selected
2454                 return false;
2455         }
2456         pit_type const end_pit = cur.pit();
2457         pos_type const end_pos = cur.pos();
2458         d->cursor_.clearSelection();
2459         d->cursor_.reset();
2460         d->cursor_.setCursor(cur);
2461         d->cursor_.pit() = beg_pit;
2462         d->cursor_.pos() = 0;
2463         d->cursor_.setSelection(false);
2464         d->cursor_.resetAnchor();
2465         d->cursor_.pit() = end_pit;
2466         d->cursor_.pos() = end_pos;
2467         d->cursor_.setSelection();
2468         return true;
2469 }
2470
2471
2472 Cursor & BufferView::cursor()
2473 {
2474         return d->cursor_;
2475 }
2476
2477
2478 Cursor const & BufferView::cursor() const
2479 {
2480         return d->cursor_;
2481 }
2482
2483
2484 pit_type BufferView::anchor_ref() const
2485 {
2486         return d->anchor_pit_;
2487 }
2488
2489
2490 bool BufferView::singleParUpdate()
2491 {
2492         Text & buftext = buffer_.text();
2493         pit_type const bottom_pit = d->cursor_.bottom().pit();
2494         TextMetrics & tm = textMetrics(&buftext);
2495         int old_height = tm.parMetrics(bottom_pit).height();
2496
2497         // make sure inline completion pointer is ok
2498         if (d->inlineCompletionPos_.fixIfBroken())
2499                 d->inlineCompletionPos_ = DocIterator();
2500
2501         // In Single Paragraph mode, rebreak only
2502         // the (main text, not inset!) paragraph containing the cursor.
2503         // (if this paragraph contains insets etc., rebreaking will
2504         // recursively descend)
2505         tm.redoParagraph(bottom_pit);
2506         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
2507         if (pm.height() != old_height)
2508                 // Paragraph height has changed so we cannot proceed to
2509                 // the singlePar optimisation.
2510                 return false;
2511
2512         d->update_strategy_ = SingleParUpdate;
2513
2514         LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2515                 << " y2: " << pm.position() + pm.descent()
2516                 << " pit: " << bottom_pit
2517                 << " singlepar: 1");
2518         return true;
2519 }
2520
2521
2522 void BufferView::updateMetrics()
2523 {
2524         if (height_ == 0 || width_ == 0)
2525                 return;
2526
2527         Text & buftext = buffer_.text();
2528         pit_type const npit = int(buftext.paragraphs().size());
2529
2530         // Clear out the position cache in case of full screen redraw,
2531         d->coord_cache_.clear();
2532
2533         // Clear out paragraph metrics to avoid having invalid metrics
2534         // in the cache from paragraphs not relayouted below
2535         // The complete text metrics will be redone.
2536         d->text_metrics_.clear();
2537
2538         TextMetrics & tm = textMetrics(&buftext);
2539
2540         // make sure inline completion pointer is ok
2541         if (d->inlineCompletionPos_.fixIfBroken())
2542                 d->inlineCompletionPos_ = DocIterator();
2543         
2544         if (d->anchor_pit_ >= npit)
2545                 // The anchor pit must have been deleted...
2546                 d->anchor_pit_ = npit - 1;
2547
2548         // Rebreak anchor paragraph.
2549         tm.redoParagraph(d->anchor_pit_);
2550         ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2551         
2552         // position anchor
2553         if (d->anchor_pit_ == 0) {
2554                 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2555                 
2556                 // Complete buffer visible? Then it's easy.
2557                 if (scrollRange == 0)
2558                         d->anchor_ypos_ = anchor_pm.ascent();
2559         
2560                 // FIXME: Some clever handling needed to show
2561                 // the _first_ paragraph up to the top if the cursor is
2562                 // in the first line.
2563         }               
2564         anchor_pm.setPosition(d->anchor_ypos_);
2565
2566         LYXERR(Debug::PAINTING, "metrics: "
2567                 << " anchor pit = " << d->anchor_pit_
2568                 << " anchor ypos = " << d->anchor_ypos_);
2569
2570         // Redo paragraphs above anchor if necessary.
2571         int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2572         // We are now just above the anchor paragraph.
2573         pit_type pit1 = d->anchor_pit_ - 1;
2574         for (; pit1 >= 0 && y1 >= 0; --pit1) {
2575                 tm.redoParagraph(pit1);
2576                 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2577                 y1 -= pm.descent();
2578                 // Save the paragraph position in the cache.
2579                 pm.setPosition(y1);
2580                 y1 -= pm.ascent();
2581         }
2582
2583         // Redo paragraphs below the anchor if necessary.
2584         int y2 = d->anchor_ypos_ + anchor_pm.descent();
2585         // We are now just below the anchor paragraph.
2586         pit_type pit2 = d->anchor_pit_ + 1;
2587         for (; pit2 < npit && y2 <= height_; ++pit2) {
2588                 tm.redoParagraph(pit2);
2589                 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2590                 y2 += pm.ascent();
2591                 // Save the paragraph position in the cache.
2592                 pm.setPosition(y2);
2593                 y2 += pm.descent();
2594         }
2595
2596         LYXERR(Debug::PAINTING, "Metrics: "
2597                 << " anchor pit = " << d->anchor_pit_
2598                 << " anchor ypos = " << d->anchor_ypos_
2599                 << " y1 = " << y1
2600                 << " y2 = " << y2
2601                 << " pit1 = " << pit1
2602                 << " pit2 = " << pit2);
2603
2604         d->update_strategy_ = FullScreenUpdate;
2605
2606         if (lyxerr.debugging(Debug::WORKAREA)) {
2607                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2608                 d->coord_cache_.dump();
2609         }
2610 }
2611
2612
2613 void BufferView::insertLyXFile(FileName const & fname)
2614 {
2615         LASSERT(d->cursor_.inTexted(), /**/);
2616
2617         // Get absolute path of file and add ".lyx"
2618         // to the filename if necessary
2619         FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2620
2621         docstring const disp_fn = makeDisplayPath(filename.absFileName());
2622         // emit message signal.
2623         message(bformat(_("Inserting document %1$s..."), disp_fn));
2624
2625         docstring res;
2626         Buffer buf(filename.absFileName(), false);
2627         if (buf.loadLyXFile() == Buffer::ReadSuccess) {
2628                 ErrorList & el = buffer_.errorList("Parse");
2629                 // Copy the inserted document error list into the current buffer one.
2630                 el = buf.errorList("Parse");
2631                 buffer_.undo().recordUndo(d->cursor_);
2632                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2633                                              buf.params().documentClassPtr(), el);
2634                 res = _("Document %1$s inserted.");
2635         } else {
2636                 res = _("Could not insert document %1$s");
2637         }
2638
2639         buffer_.changed(true);
2640         // emit message signal.
2641         message(bformat(res, disp_fn));
2642 }
2643
2644
2645 Point BufferView::coordOffset(DocIterator const & dit) const
2646 {
2647         int x = 0;
2648         int y = 0;
2649         int lastw = 0;
2650
2651         // Addup contribution of nested insets, from inside to outside,
2652         // keeping the outer paragraph for a special handling below
2653         for (size_t i = dit.depth() - 1; i >= 1; --i) {
2654                 CursorSlice const & sl = dit[i];
2655                 int xx = 0;
2656                 int yy = 0;
2657                 
2658                 // get relative position inside sl.inset()
2659                 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2660                 
2661                 // Make relative position inside of the edited inset relative to sl.inset()
2662                 x += xx;
2663                 y += yy;
2664                 
2665                 // In case of an RTL inset, the edited inset will be positioned to the left
2666                 // of xx:yy
2667                 if (sl.text()) {
2668                         bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2669                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2670                         if (rtl)
2671                                 x -= lastw;
2672                 }
2673
2674                 // remember width for the case that sl.inset() is positioned in an RTL inset
2675                 if (i && dit[i - 1].text()) {
2676                         // If this Inset is inside a Text Inset, retrieve the Dimension
2677                         // from the containing text instead of using Inset::dimension() which
2678                         // might not be implemented.
2679                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2680                         // elimination of Inset::dim_ cache. This coordOffset() method needs
2681                         // to be rewritten in light of the new design.
2682                         Dimension const & dim = parMetrics(dit[i - 1].text(),
2683                                 dit[i - 1].pit()).insetDimension(&sl.inset());
2684                         lastw = dim.wid;
2685                 } else {
2686                         Dimension const dim = sl.inset().dimension(*this);
2687                         lastw = dim.wid;
2688                 }
2689                 
2690                 //lyxerr << "Cursor::getPos, i: "
2691                 // << i << " x: " << xx << " y: " << y << endl;
2692         }
2693
2694         // Add contribution of initial rows of outermost paragraph
2695         CursorSlice const & sl = dit[0];
2696         TextMetrics const & tm = textMetrics(sl.text());
2697         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2698         LASSERT(!pm.rows().empty(), /**/);
2699         y -= pm.rows()[0].ascent();
2700 #if 1
2701         // FIXME: document this mess
2702         size_t rend;
2703         if (sl.pos() > 0 && dit.depth() == 1) {
2704                 int pos = sl.pos();
2705                 if (pos && dit.boundary())
2706                         --pos;
2707 //              lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2708                 rend = pm.pos2row(pos);
2709         } else
2710                 rend = pm.pos2row(sl.pos());
2711 #else
2712         size_t rend = pm.pos2row(sl.pos());
2713 #endif
2714         for (size_t rit = 0; rit != rend; ++rit)
2715                 y += pm.rows()[rit].height();
2716         y += pm.rows()[rend].ascent();
2717         
2718         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2719         
2720         // Make relative position from the nested inset now bufferview absolute.
2721         int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2722         x += xx;
2723         
2724         // In the RTL case place the nested inset at the left of the cursor in 
2725         // the outer paragraph
2726         bool boundary_1 = dit.boundary() && 1 == dit.depth();
2727         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2728         if (rtl)
2729                 x -= lastw;
2730         
2731         return Point(x, y);
2732 }
2733
2734
2735 Point BufferView::getPos(DocIterator const & dit) const
2736 {
2737         if (!paragraphVisible(dit))
2738                 return Point(-1, -1);
2739
2740         CursorSlice const & bot = dit.bottom();
2741         TextMetrics const & tm = textMetrics(bot.text());
2742
2743         // offset from outer paragraph
2744         Point p = coordOffset(dit); 
2745         p.y_ += tm.parMetrics(bot.pit()).position();
2746         return p;
2747 }
2748
2749
2750 bool BufferView::paragraphVisible(DocIterator const & dit) const
2751 {
2752         CursorSlice const & bot = dit.bottom();
2753         TextMetrics const & tm = textMetrics(bot.text());
2754
2755         return tm.contains(bot.pit());
2756 }
2757
2758
2759 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2760 {
2761         Cursor const & cur = cursor();
2762         Font const font = cur.getFont();
2763         frontend::FontMetrics const & fm = theFontMetrics(font);
2764         int const asc = fm.maxAscent();
2765         int const des = fm.maxDescent();
2766         h = asc + des;
2767         p = getPos(cur);
2768         p.y_ -= asc;
2769 }
2770
2771
2772 bool BufferView::cursorInView(Point const & p, int h) const
2773 {
2774         Cursor const & cur = cursor();
2775         // does the cursor touch the screen ?
2776         if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2777                 return false;
2778         return true;
2779 }
2780
2781
2782 void BufferView::draw(frontend::Painter & pain)
2783 {
2784         if (height_ == 0 || width_ == 0)
2785                 return;
2786         LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2787
2788         Text & text = buffer_.text();
2789         TextMetrics const & tm = d->text_metrics_[&text];
2790         int const y = tm.first().second->position();
2791         PainterInfo pi(this, pain);
2792
2793         switch (d->update_strategy_) {
2794
2795         case NoScreenUpdate:
2796                 // If no screen painting is actually needed, only some the different
2797                 // coordinates of insets and paragraphs needs to be updated.
2798                 pi.full_repaint = true;
2799                 pi.pain.setDrawingEnabled(false);
2800                 tm.draw(pi, 0, y);
2801                 break;
2802
2803         case SingleParUpdate:
2804                 pi.full_repaint = false;
2805                 // In general, only the current row of the outermost paragraph
2806                 // will be redrawn. Particular cases where selection spans
2807                 // multiple paragraph are correctly detected in TextMetrics.
2808                 tm.draw(pi, 0, y);
2809                 break;
2810
2811         case DecorationUpdate:
2812                 // FIXME: We should also distinguish DecorationUpdate to avoid text
2813                 // drawing if possible. This is not possible to do easily right now
2814                 // because of the single backing pixmap.
2815
2816         case FullScreenUpdate:
2817                 // The whole screen, including insets, will be refreshed.
2818                 pi.full_repaint = true;
2819
2820                 // Clear background.
2821                 pain.fillRectangle(0, 0, width_, height_,
2822                         pi.backgroundColor(&buffer_.inset()));
2823
2824                 // Draw everything.
2825                 tm.draw(pi, 0, y);
2826
2827                 // and possibly grey out below
2828                 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2829                 int const y2 = lastpm.second->position() + lastpm.second->descent();
2830                 
2831                 if (y2 < height_) {
2832                         Color color = buffer().isInternal() 
2833                                 ? Color_background : Color_bottomarea;
2834                         pain.fillRectangle(0, y2, width_, height_ - y2, color);
2835                 }
2836                 break;
2837         }
2838         LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING  ***");
2839
2840         // The scrollbar needs an update.
2841         updateScrollbar();
2842
2843         // Normalize anchor for next time
2844         pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2845         pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2846         for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2847                 ParagraphMetrics const & pm = tm.parMetrics(pit);
2848                 if (pm.position() + pm.descent() > 0) {
2849                         d->anchor_pit_ = pit;
2850                         d->anchor_ypos_ = pm.position();
2851                         break;
2852                 }
2853         }
2854         LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2855                 << "  anchor ypos = " << d->anchor_ypos_);
2856 }
2857
2858
2859 void BufferView::message(docstring const & msg)
2860 {
2861         if (d->gui_)
2862                 d->gui_->message(msg);
2863 }
2864
2865
2866 void BufferView::showDialog(string const & name)
2867 {
2868         if (d->gui_)
2869                 d->gui_->showDialog(name, string());
2870 }
2871
2872
2873 void BufferView::showDialog(string const & name,
2874         string const & data, Inset * inset)
2875 {
2876         if (d->gui_)
2877                 d->gui_->showDialog(name, data, inset);
2878 }
2879
2880
2881 void BufferView::updateDialog(string const & name, string const & data)
2882 {
2883         if (d->gui_)
2884                 d->gui_->updateDialog(name, data);
2885 }
2886
2887
2888 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2889 {
2890         d->gui_ = gui;
2891 }
2892
2893
2894 // FIXME: Move this out of BufferView again
2895 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2896 {
2897         if (!fname.isReadableFile()) {
2898                 docstring const error = from_ascii(strerror(errno));
2899                 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2900                 docstring const text =
2901                   bformat(_("Could not read the specified document\n"
2902                             "%1$s\ndue to the error: %2$s"), file, error);
2903                 Alert::error(_("Could not read file"), text);
2904                 return docstring();
2905         }
2906
2907         if (!fname.isReadableFile()) {
2908                 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2909                 docstring const text =
2910                   bformat(_("%1$s\n is not readable."), file);
2911                 Alert::error(_("Could not open file"), text);
2912                 return docstring();
2913         }
2914
2915         // FIXME UNICODE: We don't know the encoding of the file
2916         docstring file_content = fname.fileContents("UTF-8");
2917         if (file_content.empty()) {
2918                 Alert::error(_("Reading not UTF-8 encoded file"),
2919                              _("The file is not UTF-8 encoded.\n"
2920                                "It will be read as local 8Bit-encoded.\n"
2921                                "If this does not give the correct result\n"
2922                                "then please change the encoding of the file\n"
2923                                "to UTF-8 with a program other than LyX.\n"));
2924                 file_content = fname.fileContents("local8bit");
2925         }
2926
2927         return normalize_c(file_content);
2928 }
2929
2930
2931 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2932 {
2933         docstring const tmpstr = contentsOfPlaintextFile(f);
2934
2935         if (tmpstr.empty())
2936                 return;
2937
2938         Cursor & cur = cursor();
2939         cap::replaceSelection(cur);
2940         buffer_.undo().recordUndo(cur);
2941         if (asParagraph)
2942                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2943         else
2944                 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2945
2946         buffer_.changed(true);
2947 }
2948
2949
2950 docstring const & BufferView::inlineCompletion() const
2951 {
2952         return d->inlineCompletion_;
2953 }
2954
2955
2956 size_t const & BufferView::inlineCompletionUniqueChars() const
2957 {
2958         return d->inlineCompletionUniqueChars_;
2959 }
2960
2961
2962 DocIterator const & BufferView::inlineCompletionPos() const
2963 {
2964         return d->inlineCompletionPos_;
2965 }
2966
2967
2968 void BufferView::resetInlineCompletionPos()
2969 {
2970         d->inlineCompletionPos_ = DocIterator();
2971 }
2972
2973
2974 bool samePar(DocIterator const & a, DocIterator const & b)
2975 {
2976         if (a.empty() && b.empty())
2977                 return true;
2978         if (a.empty() || b.empty())
2979                 return false;
2980         if (a.depth() != b.depth())
2981                 return false;
2982         return &a.innerParagraph() == &b.innerParagraph();
2983 }
2984
2985
2986 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos, 
2987         docstring const & completion, size_t uniqueChars)
2988 {
2989         uniqueChars = min(completion.size(), uniqueChars);
2990         bool changed = d->inlineCompletion_ != completion
2991                 || d->inlineCompletionUniqueChars_ != uniqueChars;
2992         bool singlePar = true;
2993         d->inlineCompletion_ = completion;
2994         d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2995         
2996         //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2997         
2998         // at new position?
2999         DocIterator const & old = d->inlineCompletionPos_;
3000         if (old != pos) {
3001                 //lyxerr << "inlineCompletionPos changed" << std::endl;
3002                 // old or pos are in another paragraph?
3003                 if ((!samePar(cur, pos) && !pos.empty())
3004                     || (!samePar(cur, old) && !old.empty())) {
3005                         singlePar = false;
3006                         //lyxerr << "different paragraph" << std::endl;
3007                 }
3008                 d->inlineCompletionPos_ = pos;
3009         }
3010         
3011         // set update flags
3012         if (changed) {
3013                 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3014                         cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3015                 else
3016                         cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3017         }
3018 }
3019
3020
3021 bool BufferView::clickableInset() const
3022
3023         return d->clickable_inset_; 
3024 }
3025
3026 } // namespace lyx