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