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