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