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