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