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