]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
- UI support for the LaTeX-package undertilde, fileformat change, fixed the remaining...
[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)
892                         scrolled = scrollUp(-ypos + row_dim.ascent());
893
894                 // If the bottom of the row falls of the screen, we scroll down.
895                 // However, we have to be careful not to scroll that much that
896                 // the top falls of the screen.
897                 else if (ypos + row_dim.descent() > height_) {
898                         int ynew = height_ - row_dim.descent();
899                         if (ynew < row_dim.ascent())
900                                 ynew = row_dim.ascent();
901                         int const scroll = ypos - ynew;
902                         scrolled = scrollDown(scroll);
903                 }
904
905                 // else, nothing to do, the cursor is already visible so we just return.
906                 return scrolled != 0;
907         }
908
909         // fix inline completion position
910         if (d->inlineCompletionPos_.fixIfBroken())
911                 d->inlineCompletionPos_ = DocIterator();
912
913         tm.redoParagraph(bot_pit);
914         ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
915         int offset = coordOffset(dit).y_;
916
917         d->anchor_pit_ = bot_pit;
918         CursorSlice const & cs = dit.innerTextSlice();
919         Dimension const & row_dim =
920                 pm.getRow(cs.pos(), dit.boundary()).dimension();
921
922         if (recenter)
923                 d->anchor_ypos_ = height_/2;
924         else if (d->anchor_pit_ == 0)
925                 d->anchor_ypos_ = offset + pm.ascent();
926         else if (d->anchor_pit_ == max_pit)
927                 d->anchor_ypos_ = height_ - offset - row_dim.descent();
928         else if (offset > height_)
929                 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
930         else
931                 d->anchor_ypos_ = defaultRowHeight() * 2;
932
933         return true;
934 }
935
936
937 void BufferView::updateDocumentClass(DocumentClass const * const olddc)
938 {
939         message(_("Converting document to new document class..."));
940         
941         StableDocIterator backcur(d->cursor_);
942         ErrorList & el = buffer_.errorList("Class Switch");
943         cap::switchBetweenClasses(
944                         olddc, buffer_.params().documentClassPtr(),
945                         static_cast<InsetText &>(buffer_.inset()), el);
946
947         setCursor(backcur.asDocIterator(&buffer_));
948
949         buffer_.errors("Class Switch");
950 }
951
952 /** Return the change status at cursor position, taking in account the
953  * status at each level of the document iterator (a table in a deleted
954  * footnote is deleted).
955  * When \param outer is true, the top slice is not looked at.
956  */
957 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
958 {
959         size_t const depth = dit.depth() - (outer ? 1 : 0);
960
961         for (size_t i = 0 ; i < depth ; ++i) {
962                 CursorSlice const & slice = dit[i];
963                 if (!slice.inset().inMathed()
964                     && slice.pos() < slice.paragraph().size()) {
965                         Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
966                         if (ch != Change::UNCHANGED)
967                                 return ch;
968                 }
969         }
970         return Change::UNCHANGED;
971 }
972
973
974 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
975 {
976         FuncCode const act = cmd.action();
977
978         // Can we use a readonly buffer?
979         if (buffer_.isReadonly()
980             && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
981             && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
982                 flag.message(from_utf8(N_("Document is read-only")));
983                 flag.setEnabled(false);
984                 return true;
985         }
986
987         // Are we in a DELETED change-tracking region?
988         if (lookupChangeType(d->cursor_, true) == Change::DELETED
989             && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
990             && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
991                 flag.message(from_utf8(N_("This portion of the document is deleted.")));
992                 flag.setEnabled(false);
993                 return true;
994         }
995
996         Cursor & cur = d->cursor_;
997
998         if (cur.getStatus(cmd, flag))
999                 return true;
1000
1001         switch (act) {
1002
1003         // FIXME: This is a bit problematic because we don't check if this is
1004         // a document BufferView or not for these LFUNs. We probably have to
1005         // dispatch both to currentBufferView() and, if that fails,
1006         // to documentBufferView(); same as we do now for current Buffer and
1007         // document Buffer. Ideally those LFUN should go to Buffer as they
1008         // operate on the full Buffer and the cursor is only needed either for
1009         // an Undo record or to restore a cursor position. But we don't know
1010         // how to do that inside Buffer of course.
1011         case LFUN_BUFFER_PARAMS_APPLY:
1012         case LFUN_LAYOUT_MODULES_CLEAR:
1013         case LFUN_LAYOUT_MODULE_ADD:
1014         case LFUN_LAYOUT_RELOAD:
1015         case LFUN_TEXTCLASS_APPLY:
1016         case LFUN_TEXTCLASS_LOAD:
1017                 flag.setEnabled(!buffer_.isReadonly());
1018                 break;
1019
1020         case LFUN_UNDO:
1021                 // We do not use the LyXAction flag for readonly because Undo sets the
1022                 // buffer clean/dirty status by itself.
1023                 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1024                 break;
1025         case LFUN_REDO:
1026                 // We do not use the LyXAction flag for readonly because Redo sets the
1027                 // buffer clean/dirty status by itself.
1028                 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1029                 break;
1030         case LFUN_FILE_INSERT:
1031         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1032         case LFUN_FILE_INSERT_PLAINTEXT:
1033         case LFUN_BOOKMARK_SAVE:
1034                 // FIXME: Actually, these LFUNS should be moved to Text
1035                 flag.setEnabled(cur.inTexted());
1036                 break;
1037
1038         case LFUN_FONT_STATE:
1039         case LFUN_LABEL_INSERT:
1040         case LFUN_INFO_INSERT:
1041         case LFUN_PARAGRAPH_GOTO:
1042         case LFUN_NOTE_NEXT:
1043         case LFUN_REFERENCE_NEXT:
1044         case LFUN_WORD_FIND:
1045         case LFUN_WORD_FIND_FORWARD:
1046         case LFUN_WORD_FIND_BACKWARD:
1047         case LFUN_WORD_FINDADV:
1048         case LFUN_WORD_REPLACE:
1049         case LFUN_MARK_OFF:
1050         case LFUN_MARK_ON:
1051         case LFUN_MARK_TOGGLE:
1052         case LFUN_SCREEN_RECENTER:
1053         case LFUN_SCREEN_SHOW_CURSOR:
1054         case LFUN_BIBTEX_DATABASE_ADD:
1055         case LFUN_BIBTEX_DATABASE_DEL:
1056         case LFUN_STATISTICS:
1057         case LFUN_BRANCH_ADD_INSERT:
1058         case LFUN_KEYMAP_OFF:
1059         case LFUN_KEYMAP_PRIMARY:
1060         case LFUN_KEYMAP_SECONDARY:
1061         case LFUN_KEYMAP_TOGGLE:
1062                 flag.setEnabled(true);
1063                 break;
1064
1065         case LFUN_LABEL_GOTO: {
1066                 flag.setEnabled(!cmd.argument().empty()
1067                     || getInsetByCode<InsetRef>(cur, REF_CODE));
1068                 break;
1069         }
1070
1071         case LFUN_CHANGES_TRACK:
1072                 flag.setEnabled(true);
1073                 flag.setOnOff(buffer_.params().trackChanges);
1074                 break;
1075
1076         case LFUN_CHANGES_OUTPUT:
1077                 flag.setEnabled(true);
1078                 flag.setOnOff(buffer_.params().outputChanges);
1079                 break;
1080
1081         case LFUN_CHANGES_MERGE:
1082         case LFUN_CHANGE_NEXT:
1083         case LFUN_CHANGE_PREVIOUS:
1084         case LFUN_ALL_CHANGES_ACCEPT:
1085         case LFUN_ALL_CHANGES_REJECT:
1086                 // TODO: context-sensitive enabling of LFUNs
1087                 // In principle, these command should only be enabled if there
1088                 // is a change in the document. However, without proper
1089                 // optimizations, this will inevitably result in poor performance.
1090                 flag.setEnabled(true);
1091                 break;
1092
1093         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1094                 flag.setOnOff(buffer_.params().compressed);
1095                 break;
1096         }
1097
1098         case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
1099                 flag.setOnOff(buffer_.params().output_sync);
1100                 break;
1101         }
1102
1103         case LFUN_SCREEN_UP:
1104         case LFUN_SCREEN_DOWN:
1105         case LFUN_SCROLL:
1106         case LFUN_SCREEN_UP_SELECT:
1107         case LFUN_SCREEN_DOWN_SELECT:
1108         case LFUN_INSET_FORALL:
1109                 flag.setEnabled(true);
1110                 break;
1111
1112         case LFUN_LAYOUT_TABULAR:
1113                 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1114                 break;
1115
1116         case LFUN_LAYOUT:
1117                 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1118                 break;
1119
1120         case LFUN_LAYOUT_PARAGRAPH:
1121                 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1122                 break;
1123
1124         case LFUN_DIALOG_SHOW_NEW_INSET:
1125                 // FIXME: this is wrong, but I do not understand the
1126                 // intent (JMarc)
1127                 if (cur.inset().lyxCode() == CAPTION_CODE)
1128                         return cur.inset().getStatus(cur, cmd, flag);
1129                 // FIXME we should consider passthru paragraphs too.
1130                 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1131                 break;
1132
1133         case LFUN_CITATION_INSERT: {
1134                 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1135                 // FIXME: This could turn in a recursive hell.
1136                 // Shouldn't we use Buffer::getStatus() instead?
1137                 flag.setEnabled(lyx::getStatus(fr).enabled());
1138                 break;
1139         }
1140         case LFUN_INSET_APPLY: {
1141                 string const name = cmd.getArg(0);
1142                 Inset * inset = editedInset(name);
1143                 if (inset) {
1144                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1145                         if (!inset->getStatus(cur, fr, flag)) {
1146                                 // Every inset is supposed to handle this
1147                                 LASSERT(false, break);
1148                         }
1149                 } else {
1150                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1151                         flag = lyx::getStatus(fr);
1152                 }
1153                 break;
1154         }
1155
1156         default:
1157                 return false;
1158         }
1159
1160         return true;
1161 }
1162
1163
1164 Inset * BufferView::editedInset(string const & name) const
1165 {
1166         map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1167         return it == d->edited_insets_.end() ? 0 : it->second;
1168 }
1169
1170
1171 void BufferView::editInset(string const & name, Inset * inset)
1172 {
1173         d->edited_insets_[name] = inset;
1174 }
1175
1176
1177 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1178 {
1179         //lyxerr << [ cmd = " << cmd << "]" << endl;
1180
1181         // Make sure that the cached BufferView is correct.
1182         LYXERR(Debug::ACTION, " action[" << cmd.action() << ']'
1183                 << " arg[" << to_utf8(cmd.argument()) << ']'
1184                 << " x[" << cmd.x() << ']'
1185                 << " y[" << cmd.y() << ']'
1186                 << " button[" << cmd.button() << ']');
1187
1188         string const argument = to_utf8(cmd.argument());
1189         Cursor & cur = d->cursor_;
1190
1191         // Don't dispatch function that does not apply to internal buffers.
1192         if (buffer_.isInternal() 
1193             && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1194                 return;
1195
1196         // We'll set this back to false if need be.
1197         bool dispatched = true;
1198         buffer_.undo().beginUndoGroup();
1199
1200         FuncCode const act = cmd.action();
1201         switch (act) {
1202
1203         case LFUN_BUFFER_PARAMS_APPLY: {
1204                 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1205                 cur.recordUndoFullDocument();
1206                 istringstream ss(to_utf8(cmd.argument()));
1207                 Lexer lex;
1208                 lex.setStream(ss);
1209                 int const unknown_tokens = buffer_.readHeader(lex);
1210                 if (unknown_tokens != 0) {
1211                         LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1212                                                 << unknown_tokens << " unknown token"
1213                                                 << (unknown_tokens == 1 ? "" : "s"));
1214                 }
1215                 updateDocumentClass(oldClass);
1216                         
1217                 // We are most certainly here because of a change in the document
1218                 // It is then better to make sure that all dialogs are in sync with
1219                 // current document settings.
1220                 dr.screenUpdate(Update::Force | Update::FitCursor);
1221                 dr.forceBufferUpdate();
1222                 break;
1223         }
1224                 
1225         case LFUN_LAYOUT_MODULES_CLEAR: {
1226                 DocumentClass const * const oldClass =
1227                         buffer_.params().documentClassPtr();
1228                 cur.recordUndoFullDocument();
1229                 buffer_.params().clearLayoutModules();
1230                 buffer_.params().makeDocumentClass();
1231                 updateDocumentClass(oldClass);
1232                 dr.screenUpdate(Update::Force);
1233                 dr.forceBufferUpdate();
1234                 break;
1235         }
1236
1237         case LFUN_LAYOUT_MODULE_ADD: {
1238                 BufferParams const & params = buffer_.params();
1239                 if (!params.moduleCanBeAdded(argument)) {
1240                         LYXERR0("Module `" << argument << 
1241                                 "' cannot be added due to failed requirements or "
1242                                 "conflicts with installed modules.");
1243                         break;
1244                 }
1245                 DocumentClass const * const oldClass = params.documentClassPtr();
1246                 cur.recordUndoFullDocument();
1247                 buffer_.params().addLayoutModule(argument);
1248                 buffer_.params().makeDocumentClass();
1249                 updateDocumentClass(oldClass);
1250                 dr.screenUpdate(Update::Force);
1251                 dr.forceBufferUpdate();
1252                 break;
1253         }
1254
1255         case LFUN_TEXTCLASS_APPLY: {
1256                 // since this shortcircuits, the second call is made only if 
1257                 // the first fails
1258                 bool const success = 
1259                         LayoutFileList::get().load(argument, buffer_.temppath()) ||
1260                         LayoutFileList::get().load(argument, buffer_.filePath());
1261                 if (!success) {
1262                         docstring s = bformat(_("The document class `%1$s' "
1263                                                  "could not be loaded."), from_utf8(argument));
1264                         frontend::Alert::error(_("Could not load class"), s);
1265                         break;
1266                 }
1267
1268                 LayoutFile const * old_layout = buffer_.params().baseClass();
1269                 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1270
1271                 if (old_layout == new_layout)
1272                         // nothing to do
1273                         break;
1274
1275                 // Save the old, possibly modular, layout for use in conversion.
1276                 DocumentClass const * const oldDocClass =
1277                         buffer_.params().documentClassPtr();
1278                 cur.recordUndoFullDocument();
1279                 buffer_.params().setBaseClass(argument);
1280                 buffer_.params().makeDocumentClass();
1281                 updateDocumentClass(oldDocClass);
1282                 dr.screenUpdate(Update::Force);
1283                 dr.forceBufferUpdate();
1284                 break;
1285         }
1286
1287         case LFUN_TEXTCLASS_LOAD: {
1288                 // since this shortcircuits, the second call is made only if 
1289                 // the first fails
1290                 bool const success = 
1291                         LayoutFileList::get().load(argument, buffer_.temppath()) ||
1292                         LayoutFileList::get().load(argument, buffer_.filePath());
1293                 if (!success) {                 
1294                         docstring s = bformat(_("The document class `%1$s' "
1295                                                  "could not be loaded."), from_utf8(argument));
1296                         frontend::Alert::error(_("Could not load class"), s);
1297                 }
1298                 break;
1299         }
1300
1301         case LFUN_LAYOUT_RELOAD: {
1302                 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1303                 LayoutFileIndex bc = buffer_.params().baseClassID();
1304                 LayoutFileList::get().reset(bc);
1305                 buffer_.params().setBaseClass(bc);
1306                 buffer_.params().makeDocumentClass();
1307                 updateDocumentClass(oldClass);
1308                 dr.screenUpdate(Update::Force);
1309                 dr.forceBufferUpdate();
1310                 break;
1311         }
1312
1313         case LFUN_UNDO:
1314                 dr.setMessage(_("Undo"));
1315                 cur.clearSelection();
1316                 if (!cur.textUndo())
1317                         dr.setMessage(_("No further undo information"));
1318                 else
1319                         dr.screenUpdate(Update::Force | Update::FitCursor);
1320                 dr.forceBufferUpdate();
1321                 break;
1322
1323         case LFUN_REDO:
1324                 dr.setMessage(_("Redo"));
1325                 cur.clearSelection();
1326                 if (!cur.textRedo())
1327                         dr.setMessage(_("No further redo information"));
1328                 else
1329                         dr.screenUpdate(Update::Force | Update::FitCursor);
1330                 dr.forceBufferUpdate();
1331                 break;
1332
1333         case LFUN_FONT_STATE:
1334                 dr.setMessage(cur.currentState());
1335                 break;
1336
1337         case LFUN_BOOKMARK_SAVE:
1338                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1339                 break;
1340
1341         case LFUN_LABEL_GOTO: {
1342                 docstring label = cmd.argument();
1343                 if (label.empty()) {
1344                         InsetRef * inset =
1345                                 getInsetByCode<InsetRef>(cur, REF_CODE);
1346                         if (inset) {
1347                                 label = inset->getParam("reference");
1348                                 // persistent=false: use temp_bookmark
1349                                 saveBookmark(0);
1350                         }
1351                 }
1352                 if (!label.empty()) {
1353                         gotoLabel(label);
1354                         // at the moment, this is redundant, since gotoLabel will
1355                         // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1356                         // to have it here.
1357                         dr.screenUpdate(Update::Force | Update::FitCursor);
1358                 }
1359                 break;
1360         }
1361         
1362         case LFUN_PARAGRAPH_GOTO: {
1363                 int const id = convert<int>(cmd.getArg(0));
1364                 int const pos = convert<int>(cmd.getArg(1));
1365                 int i = 0;
1366                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1367                         b = theBufferList().next(b)) {
1368
1369                         DocIterator dit = b->getParFromID(id);
1370                         if (dit.atEnd()) {
1371                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1372                                 ++i;
1373                                 continue;
1374                         }
1375                         LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1376                                 << " found in buffer `"
1377                                 << b->absFileName() << "'.");
1378
1379                         if (b == &buffer_) {
1380                                 // Set the cursor
1381                                 dit.pos() = pos;
1382                                 setCursor(dit);
1383                                 dr.screenUpdate(Update::Force | Update::FitCursor);
1384                         } else {
1385                                 // Switch to other buffer view and resend cmd
1386                                 lyx::dispatch(FuncRequest(
1387                                         LFUN_BUFFER_SWITCH, b->absFileName()));
1388                                 lyx::dispatch(cmd);
1389                         }
1390                         break;
1391                 }
1392                 break;
1393         }
1394
1395         case LFUN_NOTE_NEXT:
1396                 gotoInset(this, NOTE_CODE, false);
1397                 break;
1398
1399         case LFUN_REFERENCE_NEXT: {
1400                 vector<InsetCode> tmp;
1401                 tmp.push_back(LABEL_CODE);
1402                 tmp.push_back(REF_CODE);
1403                 gotoInset(this, tmp, true);
1404                 break;
1405         }
1406
1407         case LFUN_CHANGES_TRACK:
1408                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1409                 break;
1410
1411         case LFUN_CHANGES_OUTPUT:
1412                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1413                 if (buffer_.params().outputChanges) {
1414                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1415                         bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1416                                           LaTeXFeatures::isAvailable("xcolor");
1417
1418                         if (!dvipost && !xcolorulem) {
1419                                 Alert::warning(_("Changes not shown in LaTeX output"),
1420                                                _("Changes will not be highlighted in LaTeX output, "
1421                                                  "because neither dvipost nor xcolor/ulem are installed.\n"
1422                                                  "Please install these packages or redefine "
1423                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1424                         } else if (!xcolorulem) {
1425                                 Alert::warning(_("Changes not shown in LaTeX output"),
1426                                                _("Changes will not be highlighted in LaTeX output "
1427                                                  "when using pdflatex, because xcolor and ulem are not installed.\n"
1428                                                  "Please install both packages or redefine "
1429                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1430                         }
1431                 }
1432                 break;
1433
1434         case LFUN_CHANGE_NEXT:
1435                 findNextChange(this);
1436                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1437                 dr.screenUpdate(Update::Force | Update::FitCursor);
1438                 break;
1439         
1440         case LFUN_CHANGE_PREVIOUS:
1441                 findPreviousChange(this);
1442                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1443                 dr.screenUpdate(Update::Force | Update::FitCursor);
1444                 break;
1445
1446         case LFUN_CHANGES_MERGE:
1447                 if (findNextChange(this) || findPreviousChange(this)) {
1448                         dr.screenUpdate(Update::Force | Update::FitCursor);
1449                         dr.forceBufferUpdate();
1450                         showDialog("changes");
1451                 }
1452                 break;
1453
1454         case LFUN_ALL_CHANGES_ACCEPT:
1455                 // select complete document
1456                 cur.reset();
1457                 cur.selHandle(true);
1458                 buffer_.text().cursorBottom(cur);
1459                 // accept everything in a single step to support atomic undo
1460                 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1461                 cur.resetAnchor();
1462                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1463                 dr.screenUpdate(Update::Force | Update::FitCursor);
1464                 dr.forceBufferUpdate();
1465                 break;
1466
1467         case LFUN_ALL_CHANGES_REJECT:
1468                 // select complete document
1469                 cur.reset();
1470                 cur.selHandle(true);
1471                 buffer_.text().cursorBottom(cur);
1472                 // reject everything in a single step to support atomic undo
1473                 // Note: reject does not work recursively; the user may have to repeat the operation
1474                 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1475                 cur.resetAnchor();
1476                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1477                 dr.screenUpdate(Update::Force | Update::FitCursor);
1478                 dr.forceBufferUpdate();
1479                 break;
1480
1481         case LFUN_WORD_FIND_FORWARD:
1482         case LFUN_WORD_FIND_BACKWARD: {
1483                 static docstring last_search;
1484                 docstring searched_string;
1485
1486                 if (!cmd.argument().empty()) {
1487                         last_search = cmd.argument();
1488                         searched_string = cmd.argument();
1489                 } else {
1490                         searched_string = last_search;
1491                 }
1492
1493                 if (searched_string.empty())
1494                         break;
1495
1496                 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1497                 docstring const data =
1498                         find2string(searched_string, true, false, fw);
1499                 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1500                 if (found)
1501                         dr.screenUpdate(Update::Force | Update::FitCursor);
1502                 break;
1503         }
1504
1505         case LFUN_WORD_FIND: {
1506                 FuncRequest req = cmd;
1507                 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1508                         req = d->search_request_cache_;
1509                 if (req.argument().empty()) {
1510                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1511                         break;
1512                 }
1513                 if (lyxfind(this, req))
1514                         dr.screenUpdate(Update::Force | Update::FitCursor);
1515                 else
1516                         message(_("String not found!"));
1517                 d->search_request_cache_ = req;
1518                 break;
1519         }
1520
1521         case LFUN_WORD_REPLACE: {
1522                 bool has_deleted = false;
1523                 if (cur.selection()) {
1524                         DocIterator beg = cur.selectionBegin();
1525                         DocIterator end = cur.selectionEnd();
1526                         if (beg.pit() == end.pit()) {
1527                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1528                                         if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1529                                                 has_deleted = true;
1530                                                 break;
1531                                         }
1532                                 }
1533                         }
1534                 }
1535                 if (lyxreplace(this, cmd, has_deleted)) {
1536                         dr.forceBufferUpdate();
1537                         dr.screenUpdate(Update::Force | Update::FitCursor);
1538                 }
1539                 break;
1540         }
1541
1542         case LFUN_WORD_FINDADV: {
1543                 FindAndReplaceOptions opt;
1544                 istringstream iss(to_utf8(cmd.argument()));
1545                 iss >> opt;
1546                 if (findAdv(this, opt)) {
1547                         dr.screenUpdate(Update::Force | Update::FitCursor);
1548                         cur.dispatched();
1549                         dispatched = true;
1550                 } else {
1551                         cur.undispatched();
1552                         dispatched = false;
1553                 }
1554                 break;
1555         }
1556
1557         case LFUN_MARK_OFF:
1558                 cur.clearSelection();
1559                 dr.setMessage(from_utf8(N_("Mark off")));
1560                 break;
1561
1562         case LFUN_MARK_ON:
1563                 cur.clearSelection();
1564                 cur.setMark(true);
1565                 dr.setMessage(from_utf8(N_("Mark on")));
1566                 break;
1567
1568         case LFUN_MARK_TOGGLE:
1569                 cur.setSelection(false);
1570                 if (cur.mark()) {
1571                         cur.setMark(false);
1572                         dr.setMessage(from_utf8(N_("Mark removed")));
1573                 } else {
1574                         cur.setMark(true);
1575                         dr.setMessage(from_utf8(N_("Mark set")));
1576                 }
1577                 cur.resetAnchor();
1578                 break;
1579
1580         case LFUN_SCREEN_SHOW_CURSOR:
1581                 showCursor();
1582                 break;
1583         
1584         case LFUN_SCREEN_RECENTER:
1585                 recenter();
1586                 break;
1587
1588         case LFUN_BIBTEX_DATABASE_ADD: {
1589                 Cursor tmpcur = cur;
1590                 findInset(tmpcur, BIBTEX_CODE, false);
1591                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1592                                                 BIBTEX_CODE);
1593                 if (inset) {
1594                         if (inset->addDatabase(cmd.argument())) {
1595                                 buffer_.invalidateBibfileCache();
1596                                 dr.forceBufferUpdate();
1597                         }
1598                 }
1599                 break;
1600         }
1601
1602         case LFUN_BIBTEX_DATABASE_DEL: {
1603                 Cursor tmpcur = cur;
1604                 findInset(tmpcur, BIBTEX_CODE, false);
1605                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1606                                                 BIBTEX_CODE);
1607                 if (inset) {
1608                         if (inset->delDatabase(cmd.argument())) {
1609                                 buffer_.invalidateBibfileCache();
1610                                 dr.forceBufferUpdate();
1611                         }                               
1612                 }
1613                 break;
1614         }
1615
1616         case LFUN_STATISTICS: {
1617                 DocIterator from, to;
1618                 if (cur.selection()) {
1619                         from = cur.selectionBegin();
1620                         to = cur.selectionEnd();
1621                 } else {
1622                         from = doc_iterator_begin(&buffer_);
1623                         to = doc_iterator_end(&buffer_);
1624                 }
1625                 int const words = countWords(from, to);
1626                 int const chars = countChars(from, to, false);
1627                 int const chars_blanks = countChars(from, to, true);
1628                 docstring message;
1629                 if (cur.selection())
1630                         message = _("Statistics for the selection:");
1631                 else
1632                         message = _("Statistics for the document:");
1633                 message += "\n\n";
1634                 if (words != 1)
1635                         message += bformat(_("%1$d words"), words);
1636                 else
1637                         message += _("One word");
1638                 message += "\n";
1639                 if (chars_blanks != 1)
1640                         message += bformat(_("%1$d characters (including blanks)"),
1641                                           chars_blanks);
1642                 else
1643                         message += _("One character (including blanks)");
1644                 message += "\n";
1645                 if (chars != 1)
1646                         message += bformat(_("%1$d characters (excluding blanks)"),
1647                                           chars);
1648                 else
1649                         message += _("One character (excluding blanks)");
1650
1651                 Alert::information(_("Statistics"), message);
1652         }
1653                 break;
1654
1655         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1656                 // turn compression on/off
1657                 buffer_.params().compressed = !buffer_.params().compressed;
1658                 break;
1659
1660         case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
1661                 buffer_.params().output_sync = !buffer_.params().output_sync;
1662                 break;
1663
1664         case LFUN_SCREEN_UP:
1665         case LFUN_SCREEN_DOWN: {
1666                 Point p = getPos(cur);
1667                 // This code has been commented out to enable to scroll down a
1668                 // document, even if there are large insets in it (see bug #5465).
1669                 /*if (p.y_ < 0 || p.y_ > height_) {
1670                         // The cursor is off-screen so recenter before proceeding.
1671                         showCursor();
1672                         p = getPos(cur);
1673                 }*/
1674                 int const scrolled = scroll(act == LFUN_SCREEN_UP
1675                         ? -height_ : height_);
1676                 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1677                         p = Point(0, 0);
1678                 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1679                         p = Point(width_, height_);
1680                 Cursor old = cur;
1681                 bool const in_texted = cur.inTexted();
1682                 cur.reset();
1683                 buffer_.changed(true);
1684                 updateHoveredInset();
1685
1686                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1687                         true, act == LFUN_SCREEN_UP); 
1688                 cur.resetAnchor();
1689                 //FIXME: what to do with cur.x_target()?
1690                 bool update = in_texted && cur.bv().checkDepm(cur, old);
1691                 cur.finishUndo();
1692                 if (update) {
1693                         dr.screenUpdate(Update::Force | Update::FitCursor);
1694                         dr.forceBufferUpdate();
1695                 }
1696                 break;
1697         }
1698
1699         case LFUN_SCROLL:
1700                 lfunScroll(cmd);
1701                 dr.forceBufferUpdate();
1702                 break;
1703
1704         case LFUN_SCREEN_UP_SELECT: {
1705                 cur.selHandle(true);
1706                 if (isTopScreen()) {
1707                         lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1708                         cur.finishUndo();
1709                         break;
1710                 }
1711                 int y = getPos(cur).y_;
1712                 int const ymin = y - height_ + defaultRowHeight();
1713                 while (y > ymin && cur.up())
1714                         y = getPos(cur).y_;
1715
1716                 cur.finishUndo();
1717                 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1718                 break;
1719         }
1720
1721         case LFUN_SCREEN_DOWN_SELECT: {
1722                 cur.selHandle(true);
1723                 if (isBottomScreen()) {
1724                         lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1725                         cur.finishUndo();
1726                         break;
1727                 }
1728                 int y = getPos(cur).y_;
1729                 int const ymax = y + height_ - defaultRowHeight();
1730                 while (y < ymax && cur.down())
1731                         y = getPos(cur).y_;
1732
1733                 cur.finishUndo();
1734                 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1735                 break;
1736         }
1737
1738
1739         // This would be in Buffer class if only Cursor did not
1740         // require a bufferview
1741         case LFUN_INSET_FORALL: {
1742                 docstring const name = from_utf8(cmd.getArg(0));
1743                 string const commandstr = cmd.getLongArg(1);
1744                 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1745
1746                 // an arbitrary number to limit number of iterations
1747                 const int max_iter = 10000;
1748                 int iterations = 0;
1749                 Cursor & cur = d->cursor_;
1750                 Cursor const savecur = cur;
1751                 cur.reset();
1752                 if (!cur.nextInset())
1753                         cur.forwardInset();
1754                 cur.beginUndoGroup();
1755                 while(cur && iterations < max_iter) {
1756                         Inset * ins = cur.nextInset();
1757                         if (!ins)
1758                                 break;
1759                         docstring insname = ins->layoutName();
1760                         while (!insname.empty()) {
1761                                 if (insname == name || name == from_utf8("*")) {
1762                                         cur.recordUndo();
1763                                         lyx::dispatch(fr, dr);
1764                                         ++iterations;
1765                                         break;
1766                                 }
1767                                 size_t const i = insname.rfind(':');
1768                                 if (i == string::npos)
1769                                         break;
1770                                 insname = insname.substr(0, i);
1771                         }
1772                         cur.forwardInset();
1773                 }
1774                 cur.endUndoGroup();
1775                 cur = savecur;
1776                 cur.fixIfBroken();
1777                 dr.screenUpdate(Update::Force);
1778                 dr.forceBufferUpdate();
1779
1780                 if (iterations >= max_iter) {
1781                         dr.setError(true);
1782                         dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1783                 } else
1784                         dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1785                 break;
1786         }
1787
1788
1789         case LFUN_BRANCH_ADD_INSERT: {
1790                 docstring branch_name = from_utf8(cmd.getArg(0));
1791                 if (branch_name.empty())
1792                         if (!Alert::askForText(branch_name, _("Branch name")) ||
1793                                                 branch_name.empty())
1794                                 break;
1795
1796                 DispatchResult drtmp;
1797                 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1798                 if (drtmp.error()) {
1799                         Alert::warning(_("Branch already exists"), drtmp.message());
1800                         break;
1801                 }
1802                 BranchList & branch_list = buffer_.params().branchlist();
1803                 vector<docstring> const branches =
1804                         getVectorFromString(branch_name, branch_list.separator());
1805                 for (vector<docstring>::const_iterator it = branches.begin();
1806                      it != branches.end(); ++it) {
1807                         branch_name = *it;
1808                         lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1809                 }
1810                 break;
1811         }
1812
1813         case LFUN_KEYMAP_OFF:
1814                 getIntl().keyMapOn(false);
1815                 break;
1816
1817         case LFUN_KEYMAP_PRIMARY:
1818                 getIntl().keyMapPrim();
1819                 break;
1820
1821         case LFUN_KEYMAP_SECONDARY:
1822                 getIntl().keyMapSec();
1823                 break;
1824
1825         case LFUN_KEYMAP_TOGGLE:
1826                 getIntl().toggleKeyMap();
1827                 break;
1828
1829         case LFUN_DIALOG_SHOW_NEW_INSET: {
1830                 string const name = cmd.getArg(0);
1831                 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1832                 if (decodeInsetParam(name, data, buffer_))
1833                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1834                 else
1835                         lyxerr << "Inset type '" << name << 
1836                         "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" <<  endl;
1837                 break;
1838         }
1839
1840         case LFUN_CITATION_INSERT: {
1841                 if (argument.empty()) {
1842                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1843                         break;
1844                 }
1845                 // we can have one optional argument, delimited by '|'
1846                 // citation-insert <key>|<text_before>
1847                 // this should be enhanced to also support text_after
1848                 // and citation style
1849                 string arg = argument;
1850                 string opt1;
1851                 if (contains(argument, "|")) {
1852                         arg = token(argument, '|', 0);
1853                         opt1 = token(argument, '|', 1);
1854                 }
1855                 InsetCommandParams icp(CITE_CODE);
1856                 icp["key"] = from_utf8(arg);
1857                 if (!opt1.empty())
1858                         icp["before"] = from_utf8(opt1);
1859                 string icstr = InsetCommand::params2string(icp);
1860                 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1861                 lyx::dispatch(fr);
1862                 break;
1863         }
1864
1865         case LFUN_INSET_APPLY: {
1866                 string const name = cmd.getArg(0);
1867                 Inset * inset = editedInset(name);
1868                 if (!inset) {
1869                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1870                         lyx::dispatch(fr);
1871                         break;
1872                 }
1873                 // put cursor in front of inset.
1874                 if (!setCursorFromInset(inset)) {
1875                         LASSERT(false, break);
1876                 }
1877                 cur.recordUndo();
1878                 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1879                 inset->dispatch(cur, fr);
1880                 dr.screenUpdate(cur.result().screenUpdate());
1881                 if (cur.result().needBufferUpdate())
1882                         dr.forceBufferUpdate();
1883                 break;
1884         }
1885
1886         default:
1887                 // OK, so try the Buffer itself...
1888                 buffer_.dispatch(cmd, dr);
1889                 dispatched = dr.dispatched();
1890                 break;
1891         }
1892
1893         buffer_.undo().endUndoGroup();
1894         dr.dispatched(dispatched);
1895 }
1896
1897
1898 docstring const BufferView::requestSelection()
1899 {
1900         Cursor & cur = d->cursor_;
1901
1902         LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1903         if (!cur.selection()) {
1904                 d->xsel_cache_.set = false;
1905                 return docstring();
1906         }
1907
1908         LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1909         if (!d->xsel_cache_.set ||
1910             cur.top() != d->xsel_cache_.cursor ||
1911             cur.realAnchor().top() != d->xsel_cache_.anchor)
1912         {
1913                 d->xsel_cache_.cursor = cur.top();
1914                 d->xsel_cache_.anchor = cur.realAnchor().top();
1915                 d->xsel_cache_.set = cur.selection();
1916                 return cur.selectionAsString(false);
1917         }
1918         return docstring();
1919 }
1920
1921
1922 void BufferView::clearSelection()
1923 {
1924         d->cursor_.clearSelection();
1925         // Clear the selection buffer. Otherwise a subsequent
1926         // middle-mouse-button paste would use the selection buffer,
1927         // not the more current external selection.
1928         cap::clearSelection();
1929         d->xsel_cache_.set = false;
1930         // The buffer did not really change, but this causes the
1931         // redraw we need because we cleared the selection above.
1932         buffer_.changed(false);
1933 }
1934
1935
1936 void BufferView::resize(int width, int height)
1937 {
1938         // Update from work area
1939         width_ = width;
1940         height_ = height;
1941
1942         // Clear the paragraph height cache.
1943         d->par_height_.clear();
1944         // Redo the metrics.
1945         updateMetrics();
1946 }
1947
1948
1949 Inset const * BufferView::getCoveringInset(Text const & text,
1950                 int x, int y) const
1951 {
1952         TextMetrics & tm = d->text_metrics_[&text];
1953         Inset * inset = tm.checkInsetHit(x, y);
1954         if (!inset)
1955                 return 0;
1956
1957         if (!inset->descendable(*this))
1958                 // No need to go further down if the inset is not
1959                 // descendable.
1960                 return inset;
1961
1962         size_t cell_number = inset->nargs();
1963         // Check all the inner cell.
1964         for (size_t i = 0; i != cell_number; ++i) {
1965                 Text const * inner_text = inset->getText(i);
1966                 if (inner_text) {
1967                         // Try deeper.
1968                         Inset const * inset_deeper =
1969                                 getCoveringInset(*inner_text, x, y);
1970                         if (inset_deeper)
1971                                 return inset_deeper;
1972                 }
1973         }
1974
1975         return inset;
1976 }
1977
1978
1979 void BufferView::updateHoveredInset() const
1980 {
1981         // Get inset under mouse, if there is one.
1982         int const x = d->mouse_position_cache_.x_;
1983         int const y = d->mouse_position_cache_.y_;
1984         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
1985
1986         d->clickable_inset_ = covering_inset && covering_inset->clickable(x, y);
1987
1988         if (covering_inset == d->last_inset_)
1989                 // Same inset, no need to do anything...
1990                 return;
1991
1992         bool need_redraw = false;
1993         if (d->last_inset_) {
1994                 // Remove the hint on the last hovered inset (if any).
1995                 need_redraw |= d->last_inset_->setMouseHover(this, false);
1996                 d->last_inset_ = 0;
1997         }
1998         
1999         if (covering_inset && covering_inset->setMouseHover(this, true)) {
2000                 need_redraw = true;
2001                 // Only the insets that accept the hover state, do 
2002                 // clear the last_inset_, so only set the last_inset_
2003                 // member if the hovered setting is accepted.
2004                 d->last_inset_ = covering_inset;
2005         }
2006
2007         if (need_redraw) {
2008                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2009                                 << d->mouse_position_cache_.x_ << ", " 
2010                                 << d->mouse_position_cache_.y_ << ")");
2011         
2012                 d->update_strategy_ = DecorationUpdate;
2013
2014                 // This event (moving without mouse click) is not passed further.
2015                 // This should be changed if it is further utilized.
2016                 buffer_.changed(false);
2017         }
2018 }
2019
2020
2021 void BufferView::clearLastInset(Inset * inset) const
2022 {
2023         if (d->last_inset_ != inset) {
2024                 LYXERR0("Wrong last_inset!");
2025                 LASSERT(false, /**/);
2026         }
2027         d->last_inset_ = 0;
2028 }
2029
2030
2031 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2032 {
2033         //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2034
2035         // This is only called for mouse related events including
2036         // LFUN_FILE_OPEN generated by drag-and-drop.
2037         FuncRequest cmd = cmd0;
2038
2039         Cursor old = cursor();
2040         Cursor cur(*this);
2041         cur.push(buffer_.inset());
2042         cur.setSelection(d->cursor_.selection());
2043
2044         // Either the inset under the cursor or the
2045         // surrounding Text will handle this event.
2046
2047         // make sure we stay within the screen...
2048         cmd.set_y(min(max(cmd.y(), -1), height_));
2049
2050         d->mouse_position_cache_.x_ = cmd.x();
2051         d->mouse_position_cache_.y_ = cmd.y();
2052
2053         if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2054                 updateHoveredInset();
2055                 return;
2056         }
2057
2058         // Build temporary cursor.
2059         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2060
2061         // Put anchor at the same position.
2062         cur.resetAnchor();
2063
2064         cur.beginUndoGroup();
2065
2066         // Try to dispatch to an non-editable inset near this position
2067         // via the temp cursor. If the inset wishes to change the real
2068         // cursor it has to do so explicitly by using
2069         //  cur.bv().cursor() = cur;  (or similar)
2070         if (inset)
2071                 inset->dispatch(cur, cmd);
2072
2073         // Now dispatch to the temporary cursor. If the real cursor should
2074         // be modified, the inset's dispatch has to do so explicitly.
2075         if (!inset || !cur.result().dispatched())
2076                 cur.dispatch(cmd);
2077
2078         cur.endUndoGroup();
2079
2080         // Notify left insets
2081         if (cur != old) {
2082                 old.fixIfBroken();
2083                 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
2084                 if (badcursor)
2085                         cursor().fixIfBroken();
2086         }
2087         
2088         // Do we have a selection?
2089         theSelection().haveSelection(cursor().selection());
2090
2091         if (cur.needBufferUpdate()) {
2092                 cur.clearBufferUpdate();
2093                 buffer().updateBuffer();
2094         }
2095
2096         // If the command has been dispatched,
2097         if (cur.result().dispatched() || cur.result().screenUpdate())
2098                 processUpdateFlags(cur.result().screenUpdate());
2099 }
2100
2101
2102 void BufferView::lfunScroll(FuncRequest const & cmd)
2103 {
2104         string const scroll_type = cmd.getArg(0);
2105         int scroll_step = 0;
2106         if (scroll_type == "line")
2107                 scroll_step = d->scrollbarParameters_.single_step;
2108         else if (scroll_type == "page")
2109                 scroll_step = d->scrollbarParameters_.page_step;
2110         else
2111                 return;
2112         string const scroll_quantity = cmd.getArg(1);
2113         if (scroll_quantity == "up")
2114                 scrollUp(scroll_step);
2115         else if (scroll_quantity == "down")
2116                 scrollDown(scroll_step);
2117         else {
2118                 int const scroll_value = convert<int>(scroll_quantity);
2119                 if (scroll_value)
2120                         scroll(scroll_step * scroll_value);
2121         }
2122         buffer_.changed(true);
2123         updateHoveredInset();
2124 }
2125
2126
2127 int BufferView::minVisiblePart()
2128 {
2129         return 2 * defaultRowHeight();
2130 }
2131
2132
2133 int BufferView::scroll(int y)
2134 {
2135         if (y > 0)
2136                 return scrollDown(y);
2137         if (y < 0)
2138                 return scrollUp(-y);
2139         return 0;
2140 }
2141
2142
2143 int BufferView::scrollDown(int offset)
2144 {
2145         Text * text = &buffer_.text();
2146         TextMetrics & tm = d->text_metrics_[text];
2147         int const ymax = height_ + offset;
2148         while (true) {
2149                 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2150                 int bottom_pos = last.second->position() + last.second->descent();
2151                 if (lyxrc.scroll_below_document)
2152                         bottom_pos += height_ - minVisiblePart();
2153                 if (last.first + 1 == int(text->paragraphs().size())) {
2154                         if (bottom_pos <= height_)
2155                                 return 0;
2156                         offset = min(offset, bottom_pos - height_);
2157                         break;
2158                 }
2159                 if (bottom_pos > ymax)
2160                         break;
2161                 tm.newParMetricsDown();
2162         }
2163         d->anchor_ypos_ -= offset;
2164         return -offset;
2165 }
2166
2167
2168 int BufferView::scrollUp(int offset)
2169 {
2170         Text * text = &buffer_.text();
2171         TextMetrics & tm = d->text_metrics_[text];
2172         int ymin = - offset;
2173         while (true) {
2174                 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2175                 int top_pos = first.second->position() - first.second->ascent();
2176                 if (first.first == 0) {
2177                         if (top_pos >= 0)
2178                                 return 0;
2179                         offset = min(offset, - top_pos);
2180                         break;
2181                 }
2182                 if (top_pos < ymin)
2183                         break;
2184                 tm.newParMetricsUp();
2185         }
2186         d->anchor_ypos_ += offset;
2187         return offset;
2188 }
2189
2190
2191 void BufferView::setCursorFromRow(int row)
2192 {
2193         int tmpid;
2194         int tmppos;
2195         pit_type newpit = 0;
2196         pos_type newpos = 0;
2197
2198         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
2199
2200         bool posvalid = (tmpid != -1);
2201         if (posvalid) {
2202                 // we need to make sure that the row and position
2203                 // we got back are valid, because the buffer may well
2204                 // have changed since we last generated the LaTeX.
2205                 DocIterator const dit = buffer_.getParFromID(tmpid);
2206                 if (dit == doc_iterator_end(&buffer_))
2207                         posvalid = false;
2208                 else {
2209                         newpit = dit.pit();
2210                         // now have to check pos.
2211                         newpos = tmppos;
2212                         Paragraph const & par = buffer_.text().getPar(newpit);
2213                         if (newpos > par.size()) {
2214                                 LYXERR0("Requested position no longer valid.");
2215                                 newpos = par.size() - 1;
2216                         }
2217                 }
2218         }
2219         if (!posvalid) {
2220                 frontend::Alert::error(_("Inverse Search Failed"),
2221                         _("Invalid position requested by inverse search.\n"
2222                     "You need to update the viewed document."));
2223                 return;
2224         }
2225         d->cursor_.reset();
2226         buffer_.text().setCursor(d->cursor_, newpit, newpos);
2227         d->cursor_.setSelection(false);
2228         d->cursor_.resetAnchor();
2229         recenter();
2230 }
2231
2232
2233 bool BufferView::setCursorFromInset(Inset const * inset)
2234 {
2235         // are we already there?
2236         if (cursor().nextInset() == inset)
2237                 return true;
2238
2239         // Inset is not at cursor position. Find it in the document.
2240         Cursor cur(*this);
2241         cur.reset();
2242         while (cur && cur.nextInset() != inset)
2243                 cur.forwardInset();
2244
2245         if (cur) {
2246                 setCursor(cur);
2247                 return true;
2248         }
2249         return false;
2250 }
2251
2252
2253 void BufferView::gotoLabel(docstring const & label)
2254 {
2255         ListOfBuffers bufs = buffer().allRelatives();
2256         ListOfBuffers::iterator it = bufs.begin();
2257         for (; it != bufs.end(); ++it) {
2258                 Buffer const * buf = *it;
2259
2260                 // find label
2261                 Toc & toc = buf->tocBackend().toc("label");
2262                 TocIterator toc_it = toc.begin();
2263                 TocIterator end = toc.end();
2264                 for (; toc_it != end; ++toc_it) {
2265                         if (label == toc_it->str()) {
2266                                 lyx::dispatch(toc_it->action());
2267                                 return;
2268                         }
2269                 }
2270         }
2271 }
2272
2273
2274 TextMetrics const & BufferView::textMetrics(Text const * t) const
2275 {
2276         return const_cast<BufferView *>(this)->textMetrics(t);
2277 }
2278
2279
2280 TextMetrics & BufferView::textMetrics(Text const * t)
2281 {
2282         LASSERT(t, /**/);
2283         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
2284         if (tmc_it == d->text_metrics_.end()) {
2285                 tmc_it = d->text_metrics_.insert(
2286                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2287         }
2288         return tmc_it->second;
2289 }
2290
2291
2292 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2293                 pit_type pit) const
2294 {
2295         return textMetrics(t).parMetrics(pit);
2296 }
2297
2298
2299 int BufferView::workHeight() const
2300 {
2301         return height_;
2302 }
2303
2304
2305 void BufferView::setCursor(DocIterator const & dit)
2306 {
2307         d->cursor_.reset();
2308         size_t const n = dit.depth();
2309         for (size_t i = 0; i < n; ++i)
2310                 dit[i].inset().edit(d->cursor_, true);
2311
2312         d->cursor_.setCursor(dit);
2313         d->cursor_.setSelection(false);
2314         // FIXME
2315         // It seems on general grounds as if this is probably needed, but
2316         // it is not yet clear.
2317         // See bug #7394 and r38388.
2318         // d->cursor.resetAnchor();
2319 }
2320
2321
2322 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2323 {
2324         // Would be wrong to delete anything if we have a selection.
2325         if (cur.selection())
2326                 return false;
2327
2328         bool need_anchor_change = false;
2329         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2330                 need_anchor_change);
2331
2332         if (need_anchor_change)
2333                 cur.resetAnchor();
2334
2335         if (!changed)
2336                 return false;
2337
2338         d->cursor_ = cur;
2339
2340         cur.forceBufferUpdate();
2341         buffer_.changed(true);
2342         return true;
2343 }
2344
2345
2346 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2347 {
2348         LASSERT(&cur.bv() == this, /**/);
2349
2350         if (!select)
2351                 // this event will clear selection so we save selection for
2352                 // persistent selection
2353                 cap::saveSelection(cursor());
2354
2355         d->cursor_.macroModeClose();
2356
2357         // Has the cursor just left the inset?
2358         bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2359         if (leftinset)
2360                 d->cursor_.fixIfBroken();
2361
2362         // FIXME: shift-mouse selection doesn't work well across insets.
2363         bool const do_selection = 
2364                         select && &d->cursor_.normalAnchor().inset() == &cur.inset();
2365
2366         // do the dEPM magic if needed
2367         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2368         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2369         // the leftinset bool would not be necessary (badcursor instead).
2370         bool update = leftinset;
2371         if (!do_selection && d->cursor_.inTexted())
2372                 update |= checkDepm(cur, d->cursor_);
2373
2374         if (!do_selection)
2375                 d->cursor_.resetAnchor();
2376         d->cursor_.setCursor(cur);
2377         d->cursor_.boundary(cur.boundary());
2378         if (do_selection)
2379                 d->cursor_.setSelection();
2380         else
2381                 d->cursor_.clearSelection();
2382
2383         d->cursor_.finishUndo();
2384         d->cursor_.setCurrentFont();
2385         if (update)
2386                 cur.forceBufferUpdate();
2387         return update;
2388 }
2389
2390
2391 void BufferView::putSelectionAt(DocIterator const & cur,
2392                                 int length, bool backwards)
2393 {
2394         d->cursor_.clearSelection();
2395
2396         setCursor(cur);
2397
2398         if (length) {
2399                 if (backwards) {
2400                         d->cursor_.pos() += length;
2401                         d->cursor_.setSelection(d->cursor_, -length);
2402                 } else
2403                         d->cursor_.setSelection(d->cursor_, length);
2404         }
2405 }
2406
2407
2408 bool BufferView::selectIfEmpty(DocIterator & cur)
2409 {
2410         if (!cur.paragraph().empty())
2411                 return false;
2412
2413         pit_type const beg_pit = cur.pit();
2414         if (beg_pit > 0) {
2415                 // The paragraph associated to this item isn't
2416                 // the first one, so it can be selected
2417                 cur.backwardPos();
2418         } else {
2419                 // We have to resort to select the space between the
2420                 // end of this item and the begin of the next one
2421                 cur.forwardPos();
2422         }
2423         if (cur.empty()) {
2424                 // If it is the only item in the document,
2425                 // nothing can be selected
2426                 return false;
2427         }
2428         pit_type const end_pit = cur.pit();
2429         pos_type const end_pos = cur.pos();
2430         d->cursor_.clearSelection();
2431         d->cursor_.reset();
2432         d->cursor_.setCursor(cur);
2433         d->cursor_.pit() = beg_pit;
2434         d->cursor_.pos() = 0;
2435         d->cursor_.setSelection(false);
2436         d->cursor_.resetAnchor();
2437         d->cursor_.pit() = end_pit;
2438         d->cursor_.pos() = end_pos;
2439         d->cursor_.setSelection();
2440         return true;
2441 }
2442
2443
2444 Cursor & BufferView::cursor()
2445 {
2446         return d->cursor_;
2447 }
2448
2449
2450 Cursor const & BufferView::cursor() const
2451 {
2452         return d->cursor_;
2453 }
2454
2455
2456 pit_type BufferView::anchor_ref() const
2457 {
2458         return d->anchor_pit_;
2459 }
2460
2461
2462 bool BufferView::singleParUpdate()
2463 {
2464         Text & buftext = buffer_.text();
2465         pit_type const bottom_pit = d->cursor_.bottom().pit();
2466         TextMetrics & tm = textMetrics(&buftext);
2467         int old_height = tm.parMetrics(bottom_pit).height();
2468
2469         // make sure inline completion pointer is ok
2470         if (d->inlineCompletionPos_.fixIfBroken())
2471                 d->inlineCompletionPos_ = DocIterator();
2472
2473         // In Single Paragraph mode, rebreak only
2474         // the (main text, not inset!) paragraph containing the cursor.
2475         // (if this paragraph contains insets etc., rebreaking will
2476         // recursively descend)
2477         tm.redoParagraph(bottom_pit);
2478         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
2479         if (pm.height() != old_height)
2480                 // Paragraph height has changed so we cannot proceed to
2481                 // the singlePar optimisation.
2482                 return false;
2483
2484         d->update_strategy_ = SingleParUpdate;
2485
2486         LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2487                 << " y2: " << pm.position() + pm.descent()
2488                 << " pit: " << bottom_pit
2489                 << " singlepar: 1");
2490         return true;
2491 }
2492
2493
2494 void BufferView::updateMetrics()
2495 {
2496         if (height_ == 0 || width_ == 0)
2497                 return;
2498
2499         Text & buftext = buffer_.text();
2500         pit_type const npit = int(buftext.paragraphs().size());
2501
2502         // Clear out the position cache in case of full screen redraw,
2503         d->coord_cache_.clear();
2504
2505         // Clear out paragraph metrics to avoid having invalid metrics
2506         // in the cache from paragraphs not relayouted below
2507         // The complete text metrics will be redone.
2508         d->text_metrics_.clear();
2509
2510         TextMetrics & tm = textMetrics(&buftext);
2511
2512         // make sure inline completion pointer is ok
2513         if (d->inlineCompletionPos_.fixIfBroken())
2514                 d->inlineCompletionPos_ = DocIterator();
2515         
2516         if (d->anchor_pit_ >= npit)
2517                 // The anchor pit must have been deleted...
2518                 d->anchor_pit_ = npit - 1;
2519
2520         // Rebreak anchor paragraph.
2521         tm.redoParagraph(d->anchor_pit_);
2522         ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2523         
2524         // position anchor
2525         if (d->anchor_pit_ == 0) {
2526                 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2527                 
2528                 // Complete buffer visible? Then it's easy.
2529                 if (scrollRange == 0)
2530                         d->anchor_ypos_ = anchor_pm.ascent();
2531         
2532                 // FIXME: Some clever handling needed to show
2533                 // the _first_ paragraph up to the top if the cursor is
2534                 // in the first line.
2535         }               
2536         anchor_pm.setPosition(d->anchor_ypos_);
2537
2538         LYXERR(Debug::PAINTING, "metrics: "
2539                 << " anchor pit = " << d->anchor_pit_
2540                 << " anchor ypos = " << d->anchor_ypos_);
2541
2542         // Redo paragraphs above anchor if necessary.
2543         int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2544         // We are now just above the anchor paragraph.
2545         pit_type pit1 = d->anchor_pit_ - 1;
2546         for (; pit1 >= 0 && y1 >= 0; --pit1) {
2547                 tm.redoParagraph(pit1);
2548                 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2549                 y1 -= pm.descent();
2550                 // Save the paragraph position in the cache.
2551                 pm.setPosition(y1);
2552                 y1 -= pm.ascent();
2553         }
2554
2555         // Redo paragraphs below the anchor if necessary.
2556         int y2 = d->anchor_ypos_ + anchor_pm.descent();
2557         // We are now just below the anchor paragraph.
2558         pit_type pit2 = d->anchor_pit_ + 1;
2559         for (; pit2 < npit && y2 <= height_; ++pit2) {
2560                 tm.redoParagraph(pit2);
2561                 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2562                 y2 += pm.ascent();
2563                 // Save the paragraph position in the cache.
2564                 pm.setPosition(y2);
2565                 y2 += pm.descent();
2566         }
2567
2568         LYXERR(Debug::PAINTING, "Metrics: "
2569                 << " anchor pit = " << d->anchor_pit_
2570                 << " anchor ypos = " << d->anchor_ypos_
2571                 << " y1 = " << y1
2572                 << " y2 = " << y2
2573                 << " pit1 = " << pit1
2574                 << " pit2 = " << pit2);
2575
2576         d->update_strategy_ = FullScreenUpdate;
2577
2578         if (lyxerr.debugging(Debug::WORKAREA)) {
2579                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2580                 d->coord_cache_.dump();
2581         }
2582 }
2583
2584
2585 void BufferView::insertLyXFile(FileName const & fname)
2586 {
2587         LASSERT(d->cursor_.inTexted(), /**/);
2588
2589         // Get absolute path of file and add ".lyx"
2590         // to the filename if necessary
2591         FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2592
2593         docstring const disp_fn = makeDisplayPath(filename.absFileName());
2594         // emit message signal.
2595         message(bformat(_("Inserting document %1$s..."), disp_fn));
2596
2597         docstring res;
2598         Buffer buf(filename.absFileName(), false);
2599         if (buf.loadLyXFile() == Buffer::ReadSuccess) {
2600                 ErrorList & el = buffer_.errorList("Parse");
2601                 // Copy the inserted document error list into the current buffer one.
2602                 el = buf.errorList("Parse");
2603                 buffer_.undo().recordUndo(d->cursor_);
2604                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2605                                              buf.params().documentClassPtr(), el);
2606                 res = _("Document %1$s inserted.");
2607         } else {
2608                 res = _("Could not insert document %1$s");
2609         }
2610
2611         buffer_.changed(true);
2612         // emit message signal.
2613         message(bformat(res, disp_fn));
2614 }
2615
2616
2617 Point BufferView::coordOffset(DocIterator const & dit) const
2618 {
2619         int x = 0;
2620         int y = 0;
2621         int lastw = 0;
2622
2623         // Addup contribution of nested insets, from inside to outside,
2624         // keeping the outer paragraph for a special handling below
2625         for (size_t i = dit.depth() - 1; i >= 1; --i) {
2626                 CursorSlice const & sl = dit[i];
2627                 int xx = 0;
2628                 int yy = 0;
2629                 
2630                 // get relative position inside sl.inset()
2631                 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2632                 
2633                 // Make relative position inside of the edited inset relative to sl.inset()
2634                 x += xx;
2635                 y += yy;
2636                 
2637                 // In case of an RTL inset, the edited inset will be positioned to the left
2638                 // of xx:yy
2639                 if (sl.text()) {
2640                         bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2641                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2642                         if (rtl)
2643                                 x -= lastw;
2644                 }
2645
2646                 // remember width for the case that sl.inset() is positioned in an RTL inset
2647                 if (i && dit[i - 1].text()) {
2648                         // If this Inset is inside a Text Inset, retrieve the Dimension
2649                         // from the containing text instead of using Inset::dimension() which
2650                         // might not be implemented.
2651                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2652                         // elimination of Inset::dim_ cache. This coordOffset() method needs
2653                         // to be rewritten in light of the new design.
2654                         Dimension const & dim = parMetrics(dit[i - 1].text(),
2655                                 dit[i - 1].pit()).insetDimension(&sl.inset());
2656                         lastw = dim.wid;
2657                 } else {
2658                         Dimension const dim = sl.inset().dimension(*this);
2659                         lastw = dim.wid;
2660                 }
2661                 
2662                 //lyxerr << "Cursor::getPos, i: "
2663                 // << i << " x: " << xx << " y: " << y << endl;
2664         }
2665
2666         // Add contribution of initial rows of outermost paragraph
2667         CursorSlice const & sl = dit[0];
2668         TextMetrics const & tm = textMetrics(sl.text());
2669         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2670         LASSERT(!pm.rows().empty(), /**/);
2671         y -= pm.rows()[0].ascent();
2672 #if 1
2673         // FIXME: document this mess
2674         size_t rend;
2675         if (sl.pos() > 0 && dit.depth() == 1) {
2676                 int pos = sl.pos();
2677                 if (pos && dit.boundary())
2678                         --pos;
2679 //              lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2680                 rend = pm.pos2row(pos);
2681         } else
2682                 rend = pm.pos2row(sl.pos());
2683 #else
2684         size_t rend = pm.pos2row(sl.pos());
2685 #endif
2686         for (size_t rit = 0; rit != rend; ++rit)
2687                 y += pm.rows()[rit].height();
2688         y += pm.rows()[rend].ascent();
2689         
2690         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2691         
2692         // Make relative position from the nested inset now bufferview absolute.
2693         int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2694         x += xx;
2695         
2696         // In the RTL case place the nested inset at the left of the cursor in 
2697         // the outer paragraph
2698         bool boundary_1 = dit.boundary() && 1 == dit.depth();
2699         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2700         if (rtl)
2701                 x -= lastw;
2702         
2703         return Point(x, y);
2704 }
2705
2706
2707 Point BufferView::getPos(DocIterator const & dit) const
2708 {
2709         if (!paragraphVisible(dit))
2710                 return Point(-1, -1);
2711
2712         CursorSlice const & bot = dit.bottom();
2713         TextMetrics const & tm = textMetrics(bot.text());
2714
2715         // offset from outer paragraph
2716         Point p = coordOffset(dit); 
2717         p.y_ += tm.parMetrics(bot.pit()).position();
2718         return p;
2719 }
2720
2721
2722 bool BufferView::paragraphVisible(DocIterator const & dit) const
2723 {
2724         CursorSlice const & bot = dit.bottom();
2725         TextMetrics const & tm = textMetrics(bot.text());
2726
2727         return tm.contains(bot.pit());
2728 }
2729
2730
2731 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2732 {
2733         Cursor const & cur = cursor();
2734         Font const font = cur.getFont();
2735         frontend::FontMetrics const & fm = theFontMetrics(font);
2736         int const asc = fm.maxAscent();
2737         int const des = fm.maxDescent();
2738         h = asc + des;
2739         p = getPos(cur);
2740         p.y_ -= asc;
2741 }
2742
2743
2744 bool BufferView::cursorInView(Point const & p, int h) const
2745 {
2746         Cursor const & cur = cursor();
2747         // does the cursor touch the screen ?
2748         if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2749                 return false;
2750         return true;
2751 }
2752
2753
2754 void BufferView::draw(frontend::Painter & pain)
2755 {
2756         if (height_ == 0 || width_ == 0)
2757                 return;
2758         LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2759
2760         Text & text = buffer_.text();
2761         TextMetrics const & tm = d->text_metrics_[&text];
2762         int const y = tm.first().second->position();
2763         PainterInfo pi(this, pain);
2764
2765         switch (d->update_strategy_) {
2766
2767         case NoScreenUpdate:
2768                 // If no screen painting is actually needed, only some the different
2769                 // coordinates of insets and paragraphs needs to be updated.
2770                 pi.full_repaint = true;
2771                 pi.pain.setDrawingEnabled(false);
2772                 tm.draw(pi, 0, y);
2773                 break;
2774
2775         case SingleParUpdate:
2776                 pi.full_repaint = false;
2777                 // In general, only the current row of the outermost paragraph
2778                 // will be redrawn. Particular cases where selection spans
2779                 // multiple paragraph are correctly detected in TextMetrics.
2780                 tm.draw(pi, 0, y);
2781                 break;
2782
2783         case DecorationUpdate:
2784                 // FIXME: We should also distinguish DecorationUpdate to avoid text
2785                 // drawing if possible. This is not possible to do easily right now
2786                 // because of the single backing pixmap.
2787
2788         case FullScreenUpdate:
2789                 // The whole screen, including insets, will be refreshed.
2790                 pi.full_repaint = true;
2791
2792                 // Clear background.
2793                 pain.fillRectangle(0, 0, width_, height_,
2794                         pi.backgroundColor(&buffer_.inset()));
2795
2796                 // Draw everything.
2797                 tm.draw(pi, 0, y);
2798
2799                 // and possibly grey out below
2800                 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2801                 int const y2 = lastpm.second->position() + lastpm.second->descent();
2802                 
2803                 if (y2 < height_) {
2804                         Color color = buffer().isInternal() 
2805                                 ? Color_background : Color_bottomarea;
2806                         pain.fillRectangle(0, y2, width_, height_ - y2, color);
2807                 }
2808                 break;
2809         }
2810         LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING  ***");
2811
2812         // The scrollbar needs an update.
2813         updateScrollbar();
2814
2815         // Normalize anchor for next time
2816         pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2817         pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2818         for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2819                 ParagraphMetrics const & pm = tm.parMetrics(pit);
2820                 if (pm.position() + pm.descent() > 0) {
2821                         d->anchor_pit_ = pit;
2822                         d->anchor_ypos_ = pm.position();
2823                         break;
2824                 }
2825         }
2826         LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2827                 << "  anchor ypos = " << d->anchor_ypos_);
2828 }
2829
2830
2831 void BufferView::message(docstring const & msg)
2832 {
2833         if (d->gui_)
2834                 d->gui_->message(msg);
2835 }
2836
2837
2838 void BufferView::showDialog(string const & name)
2839 {
2840         if (d->gui_)
2841                 d->gui_->showDialog(name, string());
2842 }
2843
2844
2845 void BufferView::showDialog(string const & name,
2846         string const & data, Inset * inset)
2847 {
2848         if (d->gui_)
2849                 d->gui_->showDialog(name, data, inset);
2850 }
2851
2852
2853 void BufferView::updateDialog(string const & name, string const & data)
2854 {
2855         if (d->gui_)
2856                 d->gui_->updateDialog(name, data);
2857 }
2858
2859
2860 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2861 {
2862         d->gui_ = gui;
2863 }
2864
2865
2866 // FIXME: Move this out of BufferView again
2867 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2868 {
2869         if (!fname.isReadableFile()) {
2870                 docstring const error = from_ascii(strerror(errno));
2871                 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2872                 docstring const text =
2873                   bformat(_("Could not read the specified document\n"
2874                             "%1$s\ndue to the error: %2$s"), file, error);
2875                 Alert::error(_("Could not read file"), text);
2876                 return docstring();
2877         }
2878
2879         if (!fname.isReadableFile()) {
2880                 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2881                 docstring const text =
2882                   bformat(_("%1$s\n is not readable."), file);
2883                 Alert::error(_("Could not open file"), text);
2884                 return docstring();
2885         }
2886
2887         // FIXME UNICODE: We don't know the encoding of the file
2888         docstring file_content = fname.fileContents("UTF-8");
2889         if (file_content.empty()) {
2890                 Alert::error(_("Reading not UTF-8 encoded file"),
2891                              _("The file is not UTF-8 encoded.\n"
2892                                "It will be read as local 8Bit-encoded.\n"
2893                                "If this does not give the correct result\n"
2894                                "then please change the encoding of the file\n"
2895                                "to UTF-8 with a program other than LyX.\n"));
2896                 file_content = fname.fileContents("local8bit");
2897         }
2898
2899         return normalize_c(file_content);
2900 }
2901
2902
2903 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2904 {
2905         docstring const tmpstr = contentsOfPlaintextFile(f);
2906
2907         if (tmpstr.empty())
2908                 return;
2909
2910         Cursor & cur = cursor();
2911         cap::replaceSelection(cur);
2912         buffer_.undo().recordUndo(cur);
2913         if (asParagraph)
2914                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2915         else
2916                 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2917
2918         buffer_.changed(true);
2919 }
2920
2921
2922 docstring const & BufferView::inlineCompletion() const
2923 {
2924         return d->inlineCompletion_;
2925 }
2926
2927
2928 size_t const & BufferView::inlineCompletionUniqueChars() const
2929 {
2930         return d->inlineCompletionUniqueChars_;
2931 }
2932
2933
2934 DocIterator const & BufferView::inlineCompletionPos() const
2935 {
2936         return d->inlineCompletionPos_;
2937 }
2938
2939
2940 void BufferView::resetInlineCompletionPos()
2941 {
2942         d->inlineCompletionPos_ = DocIterator();
2943 }
2944
2945
2946 bool samePar(DocIterator const & a, DocIterator const & b)
2947 {
2948         if (a.empty() && b.empty())
2949                 return true;
2950         if (a.empty() || b.empty())
2951                 return false;
2952         if (a.depth() != b.depth())
2953                 return false;
2954         return &a.innerParagraph() == &b.innerParagraph();
2955 }
2956
2957
2958 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos, 
2959         docstring const & completion, size_t uniqueChars)
2960 {
2961         uniqueChars = min(completion.size(), uniqueChars);
2962         bool changed = d->inlineCompletion_ != completion
2963                 || d->inlineCompletionUniqueChars_ != uniqueChars;
2964         bool singlePar = true;
2965         d->inlineCompletion_ = completion;
2966         d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2967         
2968         //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2969         
2970         // at new position?
2971         DocIterator const & old = d->inlineCompletionPos_;
2972         if (old != pos) {
2973                 //lyxerr << "inlineCompletionPos changed" << std::endl;
2974                 // old or pos are in another paragraph?
2975                 if ((!samePar(cur, pos) && !pos.empty())
2976                     || (!samePar(cur, old) && !old.empty())) {
2977                         singlePar = false;
2978                         //lyxerr << "different paragraph" << std::endl;
2979                 }
2980                 d->inlineCompletionPos_ = pos;
2981         }
2982         
2983         // set update flags
2984         if (changed) {
2985                 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
2986                         cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
2987                 else
2988                         cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
2989         }
2990 }
2991
2992
2993 bool BufferView::clickableInset() const
2994
2995         return d->clickable_inset_; 
2996 }
2997
2998 } // namespace lyx