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