]> git.lyx.org Git - features.git/blob - src/BufferView.cpp
Unify graphics-groups inside marked block functionality.
[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 "Length.h"
39 #include "Lexer.h"
40 #include "LyX.h"
41 #include "LyXAction.h"
42 #include "lyxfind.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 "RowPainter.h"
50 #include "Session.h"
51 #include "Text.h"
52 #include "TextClass.h"
53 #include "TextMetrics.h"
54 #include "TexRow.h"
55 #include "TocBackend.h"
56 #include "WordLangTuple.h"
57
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCitation.h"
60 #include "insets/InsetCommand.h" // ChangeRefs
61 #include "insets/InsetExternal.h"
62 #include "insets/InsetGraphics.h"
63 #include "insets/InsetNote.h"
64 #include "insets/InsetRef.h"
65 #include "insets/InsetText.h"
66
67 #include "mathed/MathData.h"
68
69 #include "frontends/alert.h"
70 #include "frontends/Application.h"
71 #include "frontends/Delegates.h"
72 #include "frontends/FontMetrics.h"
73 #include "frontends/NullPainter.h"
74 #include "frontends/Painter.h"
75 #include "frontends/Selection.h"
76
77 #include "support/convert.h"
78 #include "support/debug.h"
79 #include "support/ExceptionMessage.h"
80 #include "support/filetools.h"
81 #include "support/gettext.h"
82 #include "support/lassert.h"
83 #include "support/lstrings.h"
84 #include "support/lyxlib.h"
85 #include "support/Package.h"
86 #include "support/types.h"
87
88 #include <cerrno>
89 #include <fstream>
90 #include <functional>
91 #include <iterator>
92 #include <sstream>
93 #include <vector>
94
95 using namespace std;
96 using namespace lyx::support;
97
98 namespace lyx {
99
100 namespace Alert = frontend::Alert;
101
102 namespace {
103
104 /// Return an inset of this class if it exists at the current cursor position
105 template <class T>
106 T * getInsetByCode(Cursor const & cur, InsetCode code)
107 {
108         DocIterator it = cur;
109         Inset * inset = it.nextInset();
110         if (inset && inset->lyxCode() == code)
111                 return static_cast<T*>(inset);
112         return 0;
113 }
114
115
116 /// Note that comparing contents can only be used for InsetCommand
117 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
118         docstring const & contents)
119 {
120         DocIterator tmpdit = dit;
121
122         while (tmpdit) {
123                 Inset const * inset = tmpdit.nextInset();
124                 if (inset) {
125                         bool const valid_code = std::find(codes.begin(), codes.end(),
126                                 inset->lyxCode()) != codes.end();
127                         InsetCommand const * ic = inset->asInsetCommand();
128                         bool const same_or_no_contents =  contents.empty()
129                                 || (ic && (ic->getFirstNonOptParam() == contents));
130
131                         if (valid_code && same_or_no_contents) {
132                                 dit = tmpdit;
133                                 return true;
134                         }
135                 }
136                 tmpdit.forwardInset();
137         }
138
139         return false;
140 }
141
142
143 /// Looks for next inset with one of the given codes.
144 /// Note that same_content can only be used for InsetCommand
145 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
146         bool same_content)
147 {
148         docstring contents;
149         DocIterator tmpdit = dit;
150         tmpdit.forwardInset();
151         if (!tmpdit)
152                 return false;
153
154         Inset const * inset = tmpdit.nextInset();
155         if (same_content && inset) {
156                 InsetCommand const * ic = inset->asInsetCommand();
157                 if (ic) {
158                         bool const valid_code = std::find(codes.begin(), codes.end(),
159                                 ic->lyxCode()) != codes.end();
160                         if (valid_code)
161                                 contents = ic->getFirstNonOptParam();
162                 }
163         }
164
165         if (!findNextInset(tmpdit, codes, contents)) {
166                 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
167                         Inset * inset = &tmpdit.bottom().inset();
168                         tmpdit = doc_iterator_begin(&inset->buffer(), inset);
169                         if (!findNextInset(tmpdit, codes, contents))
170                                 return false;
171                 } else {
172                         return false;
173                 }
174         }
175
176         dit = tmpdit;
177         return true;
178 }
179
180
181 /// Looks for next inset with the given code
182 void findInset(DocIterator & dit, InsetCode code, bool same_content)
183 {
184         findInset(dit, vector<InsetCode>(1, code), same_content);
185 }
186
187
188 /// Moves cursor to the next inset with one of the given codes.
189 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
190                bool same_content)
191 {
192         Cursor tmpcur = bv->cursor();
193         if (!findInset(tmpcur, codes, same_content)) {
194                 bv->cursor().message(_("No more insets"));
195                 return;
196         }
197
198         tmpcur.clearSelection();
199         bv->setCursor(tmpcur);
200         bv->showCursor();
201 }
202
203
204 /// Moves cursor to the next inset with given code.
205 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
206 {
207         gotoInset(bv, vector<InsetCode>(1, code), same_content);
208 }
209
210
211 /// A map from a Text to the associated text metrics
212 typedef map<Text const *, TextMetrics> TextMetricsCache;
213
214 enum ScreenUpdateStrategy {
215         NoScreenUpdate,
216         SingleParUpdate,
217         FullScreenUpdate,
218         DecorationUpdate
219 };
220
221 } // namespace
222
223
224 /////////////////////////////////////////////////////////////////////
225 //
226 // BufferView
227 //
228 /////////////////////////////////////////////////////////////////////
229
230 struct BufferView::Private
231 {
232         Private(BufferView & bv) : update_strategy_(FullScreenUpdate),
233                 update_flags_(Update::Force),
234                 wh_(0), cursor_(bv),
235                 anchor_pit_(0), anchor_ypos_(0),
236                 inlineCompletionUniqueChars_(0),
237                 last_inset_(0), clickable_inset_(false),
238                 mouse_position_cache_(),
239                 bookmark_edit_position_(-1), gui_(0),
240                 horiz_scroll_offset_(0), repaint_caret_row_(false)
241         {
242                 xsel_cache_.set = false;
243         }
244
245         ///
246         ScrollbarParameters scrollbarParameters_;
247         ///
248         ScreenUpdateStrategy update_strategy_;
249         ///
250         Update::flags update_flags_;
251         ///
252         CoordCache coord_cache_;
253
254         /// Estimated average par height for scrollbar.
255         int wh_;
256         /// this is used to handle XSelection events in the right manner.
257         struct {
258                 CursorSlice cursor;
259                 CursorSlice anchor;
260                 bool set;
261         } xsel_cache_;
262         ///
263         Cursor cursor_;
264         ///
265         pit_type anchor_pit_;
266         ///
267         int anchor_ypos_;
268         ///
269         vector<int> par_height_;
270
271         ///
272         DocIterator inlineCompletionPos_;
273         ///
274         docstring inlineCompletion_;
275         ///
276         size_t inlineCompletionUniqueChars_;
277
278         /// keyboard mapping object.
279         Intl intl_;
280
281         /// last visited inset.
282         /** kept to send setMouseHover(false).
283           * Not owned, so don't delete.
284           */
285         Inset const * last_inset_;
286         /// are we hovering something that we can click
287         bool clickable_inset_;
288
289         /// position of the mouse at the time of the last mouse move
290         /// This is used to update the hovering status of inset in
291         /// cases where the buffer is scrolled, but the mouse didn't move.
292         Point mouse_position_cache_;
293
294         // cache for id of the paragraph which was edited the last time
295         int bookmark_edit_position_;
296
297         mutable TextMetricsCache text_metrics_;
298
299         /// Whom to notify.
300         /** Not owned, so don't delete.
301           */
302         frontend::GuiBufferViewDelegate * gui_;
303
304         /// Cache for Find Next
305         FuncRequest search_request_cache_;
306
307         ///
308         map<string, Inset *> edited_insets_;
309
310         /// When the row where the cursor lies is scrolled, this
311         /// contains the scroll offset
312         int horiz_scroll_offset_;
313         /// a slice pointing to the start of the row where the cursor
314         /// is (at last draw time)
315         CursorSlice current_row_slice_;
316         /// a slice pointing to the start of the row where cursor was
317         /// at previous draw event
318         CursorSlice last_row_slice_;
319
320         /// a slice pointing to where the cursor has been drawn after the current
321         /// draw() call.
322         CursorSlice caret_slice_;
323         /// indicates whether the caret slice needs to be repainted in this draw() run.
324         bool repaint_caret_row_;
325 };
326
327
328 BufferView::BufferView(Buffer & buf)
329         : width_(0), height_(0), full_screen_(false), buffer_(buf),
330       d(new Private(*this))
331 {
332         d->xsel_cache_.set = false;
333         d->intl_.initKeyMapper(lyxrc.use_kbmap);
334
335         d->cursor_.setBuffer(&buf);
336         d->cursor_.push(buffer_.inset());
337         d->cursor_.resetAnchor();
338         d->cursor_.setCurrentFont();
339
340         buffer_.updatePreviews();
341 }
342
343
344 BufferView::~BufferView()
345 {
346         // current buffer is going to be switched-off, save cursor pos
347         // Ideally, the whole cursor stack should be saved, but session
348         // currently can only handle bottom (whole document) level pit and pos.
349         // That is to say, if a cursor is in a nested inset, it will be
350         // restore to the left of the top level inset.
351         LastFilePosSection::FilePos fp;
352         fp.pit = d->cursor_.bottom().pit();
353         fp.pos = d->cursor_.bottom().pos();
354         theSession().lastFilePos().save(buffer_.fileName(), fp);
355
356         if (d->last_inset_)
357                 d->last_inset_->setMouseHover(this, false);
358
359         delete d;
360 }
361
362
363 int BufferView::rightMargin() const
364 {
365         // The value used to be hardcoded to 10
366         int const default_margin = zoomedPixels(10);
367         // The additional test for the case the outliner is opened.
368         if (!full_screen_ || !lyxrc.full_screen_limit
369             || width_ < lyxrc.full_screen_width + 2 * default_margin)
370                 return default_margin;
371
372         return (width_ - lyxrc.full_screen_width) / 2;
373 }
374
375
376 int BufferView::leftMargin() const
377 {
378         return rightMargin();
379 }
380
381
382 int BufferView::inPixels(Length const & len) const
383 {
384         Font const font = buffer().params().getFont();
385         return len.inPixels(workWidth(), theFontMetrics(font).em());
386 }
387
388
389 int BufferView::zoomedPixels(int pix) const
390 {
391         // FIXME: the dpi setting should really depend on the BufferView
392         // (think different monitors).
393
394         // Zoom factor specified by user in percent
395         double const zoom = lyxrc.currentZoom / 100.0; // [percent]
396
397         // DPI setting for monitor relative to 100dpi
398         double const dpizoom = lyxrc.dpi / 100.0; // [per 100dpi]
399
400         return support::iround(pix * zoom * dpizoom);
401 }
402
403
404 bool BufferView::isTopScreen() const
405 {
406         return 0 == d->scrollbarParameters_.min;
407 }
408
409
410 bool BufferView::isBottomScreen() const
411 {
412         return 0 == d->scrollbarParameters_.max;
413 }
414
415
416 Intl & BufferView::getIntl()
417 {
418         return d->intl_;
419 }
420
421
422 Intl const & BufferView::getIntl() const
423 {
424         return d->intl_;
425 }
426
427
428 CoordCache & BufferView::coordCache()
429 {
430         return d->coord_cache_;
431 }
432
433
434 CoordCache const & BufferView::coordCache() const
435 {
436         return d->coord_cache_;
437 }
438
439
440 Buffer & BufferView::buffer()
441 {
442         return buffer_;
443 }
444
445
446 Buffer const & BufferView::buffer() const
447 {
448         return buffer_;
449 }
450
451
452 bool BufferView::needsFitCursor() const
453 {
454         if (cursorStatus(d->cursor_) == CUR_INSIDE) {
455                 frontend::FontMetrics const & fm =
456                         theFontMetrics(d->cursor_.getFont().fontInfo());
457                 int const asc = fm.maxAscent();
458                 int const des = fm.maxDescent();
459                 Point const p = getPos(d->cursor_);
460                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
461                         return false;
462         }
463         return true;
464 }
465
466
467 namespace {
468
469 // this is for debugging only.
470 string flagsAsString(Update::flags flags)
471 {
472         if (flags == Update::None)
473                 return "None ";
474         return string((flags & Update::FitCursor) ? "FitCursor " : "")
475                 + ((flags & Update::Force) ? "Force " : "")
476                 + ((flags & Update::ForceDraw) ? "ForceDraw " : "")
477                 + ((flags & Update::SinglePar) ? "SinglePar " : "");
478 }
479
480 }
481
482 void BufferView::processUpdateFlags(Update::flags flags)
483 {
484         LYXERR(Debug::PAINTING, "BufferView::processUpdateFlags( "
485                    << flagsAsString(flags) << ")  buffer: " << &buffer_);
486
487         // Case when no explicit update is requested.
488         if (flags == Update::None)
489                 return;
490
491         // SinglePar is ignored for now (this should probably change). We
492         // set it ourselves below, at the price of always rebreaking the
493         // paragraph at cursor. This can be expensive for large tables.
494         flags = flags & ~Update::SinglePar;
495
496         // First check whether the metrics and inset positions should be updated
497         if (flags & Update::Force) {
498                 // This will update the CoordCache items and replace Force
499                 // with ForceDraw in flags.
500                 updateMetrics(flags);
501         }
502
503         // Then make sure that the screen contains the cursor if needed
504         if (flags & Update::FitCursor) {
505                 if (needsFitCursor()) {
506                         scrollToCursor(d->cursor_, false);
507                         // Metrics have to be recomputed (maybe again)
508                         updateMetrics(flags);
509                 }
510                 flags = flags & ~Update::FitCursor;
511         }
512
513         // Finally detect whether we can only repaint a single paragraph
514         if (!(flags & Update::ForceDraw)) {
515                 if (singleParUpdate())
516                         flags = flags | Update::SinglePar;
517                 else
518                         updateMetrics(flags);
519         }
520
521         // Add flags to the the update flags. These will be reset to None
522         // after the redraw is actually done
523         d->update_flags_ = d->update_flags_ | flags;
524         LYXERR(Debug::PAINTING, "Cumulative flags: " << flagsAsString(flags));
525
526         // Now compute the update strategy
527         // Possibly values in flag are None, Decoration, ForceDraw
528         LATTEST((d->update_flags_ & ~(Update::None | Update::SinglePar
529                                       | Update::Decoration | Update::ForceDraw)) == 0);
530
531         if (d->update_flags_ & Update::ForceDraw)
532                 d->update_strategy_ = FullScreenUpdate;
533         else if (d->update_flags_ & Update::Decoration)
534                 d->update_strategy_ = DecorationUpdate;
535         else if (d->update_flags_ & Update::SinglePar)
536                 d->update_strategy_ = SingleParUpdate;
537         else {
538                 // no need to redraw anything.
539                 d->update_strategy_ = NoScreenUpdate;
540         }
541
542         updateHoveredInset();
543
544         // Trigger a redraw.
545         buffer_.changed(false);
546 }
547
548
549 void BufferView::updateScrollbar()
550 {
551         if (height_ == 0 && width_ == 0)
552                 return;
553
554         // We prefer fixed size line scrolling.
555         d->scrollbarParameters_.single_step = defaultRowHeight();
556         // We prefer full screen page scrolling.
557         d->scrollbarParameters_.page_step = height_;
558
559         Text & t = buffer_.text();
560         TextMetrics & tm = d->text_metrics_[&t];
561
562         LYXERR(Debug::GUI, " Updating scrollbar: height: "
563                 << t.paragraphs().size()
564                 << " curr par: " << d->cursor_.bottom().pit()
565                 << " default height " << defaultRowHeight());
566
567         size_t const parsize = t.paragraphs().size();
568         if (d->par_height_.size() != parsize) {
569                 d->par_height_.clear();
570                 // FIXME: We assume a default paragraph height of 2 rows. This
571                 // should probably be pondered with the screen width.
572                 d->par_height_.resize(parsize, defaultRowHeight() * 2);
573         }
574
575         // Look at paragraph heights on-screen
576         pair<pit_type, ParagraphMetrics const *> first = tm.first();
577         pair<pit_type, ParagraphMetrics const *> last = tm.last();
578         for (pit_type pit = first.first; pit <= last.first; ++pit) {
579                 d->par_height_[pit] = tm.parMetrics(pit).height();
580                 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
581                         << d->par_height_[pit]);
582         }
583
584         int top_pos = first.second->position() - first.second->ascent();
585         int bottom_pos = last.second->position() + last.second->descent();
586         bool first_visible = first.first == 0 && top_pos >= 0;
587         bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
588         if (first_visible && last_visible) {
589                 d->scrollbarParameters_.min = 0;
590                 d->scrollbarParameters_.max = 0;
591                 return;
592         }
593
594         d->scrollbarParameters_.min = top_pos;
595         for (size_t i = 0; i != size_t(first.first); ++i)
596                 d->scrollbarParameters_.min -= d->par_height_[i];
597         d->scrollbarParameters_.max = bottom_pos;
598         for (size_t i = last.first + 1; i != parsize; ++i)
599                 d->scrollbarParameters_.max += d->par_height_[i];
600
601         // The reference is the top position so we remove one page.
602         if (lyxrc.scroll_below_document)
603                 d->scrollbarParameters_.max -= minVisiblePart();
604         else
605                 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
606
607         // 0 must be inside the range as it denotes the current position
608         if (d->scrollbarParameters_.max < 0)
609                 d->scrollbarParameters_.max = 0;
610         if (d->scrollbarParameters_.min > 0)
611                 d->scrollbarParameters_.min = 0;
612 }
613
614
615 ScrollbarParameters const & BufferView::scrollbarParameters() const
616 {
617         return d->scrollbarParameters_;
618 }
619
620
621 docstring BufferView::toolTip(int x, int y) const
622 {
623         // Get inset under mouse, if there is one.
624         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
625         if (!covering_inset)
626                 // No inset, no tooltip...
627                 return docstring();
628         return covering_inset->toolTip(*this, x, y);
629 }
630
631
632 string BufferView::contextMenu(int x, int y) const
633 {
634         //If there is a selection, return the containing inset menu
635         if (d->cursor_.selection())
636                 return d->cursor_.inset().contextMenu(*this, x, y);
637
638         // Get inset under mouse, if there is one.
639         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
640         if (covering_inset)
641                 return covering_inset->contextMenu(*this, x, y);
642
643         return buffer_.inset().contextMenu(*this, x, y);
644 }
645
646
647
648 void BufferView::scrollDocView(int const value, bool update)
649 {
650         // The scrollbar values are relative to the top of the screen, therefore the
651         // offset is equal to the target value.
652
653         // No scrolling at all? No need to redraw anything
654         if (value == 0)
655                 return;
656
657         // If the offset is less than 2 screen height, prefer to scroll instead.
658         if (abs(value) <= 2 * height_) {
659                 d->anchor_ypos_ -= value;
660                 processUpdateFlags(Update::Force);
661                 return;
662         }
663
664         // cut off at the top
665         if (value <= d->scrollbarParameters_.min) {
666                 DocIterator dit = doc_iterator_begin(&buffer_);
667                 showCursor(dit, false, update);
668                 LYXERR(Debug::SCROLLING, "scroll to top");
669                 return;
670         }
671
672         // cut off at the bottom
673         if (value >= d->scrollbarParameters_.max) {
674                 DocIterator dit = doc_iterator_end(&buffer_);
675                 dit.backwardPos();
676                 showCursor(dit, false, update);
677                 LYXERR(Debug::SCROLLING, "scroll to bottom");
678                 return;
679         }
680
681         // find paragraph at target position
682         int par_pos = d->scrollbarParameters_.min;
683         pit_type i = 0;
684         for (; i != int(d->par_height_.size()); ++i) {
685                 par_pos += d->par_height_[i];
686                 if (par_pos >= value)
687                         break;
688         }
689
690         if (par_pos < value) {
691                 // It seems we didn't find the correct pit so stay on the safe side and
692                 // scroll to bottom.
693                 LYXERR0("scrolling position not found!");
694                 scrollDocView(d->scrollbarParameters_.max, update);
695                 return;
696         }
697
698         DocIterator dit = doc_iterator_begin(&buffer_);
699         dit.pit() = i;
700         LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
701         showCursor(dit, false, update);
702 }
703
704
705 // FIXME: this method is not working well.
706 void BufferView::setCursorFromScrollbar()
707 {
708         TextMetrics & tm = d->text_metrics_[&buffer_.text()];
709
710         int const height = 2 * defaultRowHeight();
711         int const first = height;
712         int const last = height_ - height;
713         int newy = 0;
714         Cursor const & oldcur = d->cursor_;
715
716         switch (cursorStatus(oldcur)) {
717         case CUR_ABOVE:
718                 newy = first;
719                 break;
720         case CUR_BELOW:
721                 newy = last;
722                 break;
723         case CUR_INSIDE:
724                 int const y = getPos(oldcur).y_;
725                 newy = min(last, max(y, first));
726                 if (y == newy)
727                         return;
728         }
729         // We reset the cursor because cursorStatus() does not
730         // work when the cursor is within mathed.
731         Cursor cur(*this);
732         cur.reset();
733         tm.setCursorFromCoordinates(cur, 0, newy);
734
735         // update the bufferview cursor and notify insets
736         // FIXME: Care about the d->cursor_ flags to redraw if needed
737         Cursor old = d->cursor_;
738         mouseSetCursor(cur);
739         // the DEPM call in mouseSetCursor() might have destroyed the
740         // paragraph the cursor is in.
741         bool badcursor = old.fixIfBroken();
742         badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
743         if (badcursor)
744                 d->cursor_.fixIfBroken();
745 }
746
747
748 Change const BufferView::getCurrentChange() const
749 {
750         if (!d->cursor_.selection())
751                 return Change(Change::UNCHANGED);
752
753         DocIterator dit = d->cursor_.selectionBegin();
754         // The selected content might have been changed (see #7685)
755         dit = dit.getInnerText();
756         return dit.paragraph().lookupChange(dit.pos());
757 }
758
759
760 // this could be used elsewhere as well?
761 // FIXME: This does not work within mathed!
762 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
763 {
764         Point const p = getPos(dit);
765         if (p.y_ < 0)
766                 return CUR_ABOVE;
767         if (p.y_ > workHeight())
768                 return CUR_BELOW;
769         return CUR_INSIDE;
770 }
771
772
773 void BufferView::bookmarkEditPosition()
774 {
775         // Don't eat cpu time for each keystroke
776         if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
777                 return;
778         saveBookmark(0);
779         d->bookmark_edit_position_ = d->cursor_.paragraph().id();
780 }
781
782
783 void BufferView::saveBookmark(unsigned int idx)
784 {
785         // tentatively save bookmark, id and pos will be used to
786         // acturately locate a bookmark in a 'live' lyx session.
787         // pit and pos will be updated with bottom level pit/pos
788         // when lyx exits.
789         if (!buffer_.isInternal()) {
790                 theSession().bookmarks().save(
791                         buffer_.fileName(),
792                         d->cursor_.bottom().pit(),
793                         d->cursor_.bottom().pos(),
794                         d->cursor_.paragraph().id(),
795                         d->cursor_.pos(),
796                         idx
797                         );
798                 if (idx)
799                         // emit message signal.
800                         message(_("Save bookmark"));
801         }
802 }
803
804
805 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
806         int top_id, pos_type top_pos)
807 {
808         bool success = false;
809         DocIterator dit;
810
811         d->cursor_.clearSelection();
812
813         // if a valid par_id is given, try it first
814         // This is the case for a 'live' bookmark when unique paragraph ID
815         // is used to track bookmarks.
816         if (top_id > 0) {
817                 dit = buffer_.getParFromID(top_id);
818                 if (!dit.atEnd()) {
819                         dit.pos() = min(dit.paragraph().size(), top_pos);
820                         // Some slices of the iterator may not be
821                         // reachable (e.g. closed collapsible inset)
822                         // so the dociterator may need to be
823                         // shortened. Otherwise, setCursor may crash
824                         // lyx when the cursor can not be set to these
825                         // insets.
826                         size_t const n = dit.depth();
827                         for (size_t i = 0; i < n; ++i)
828                                 if (!dit[i].inset().editable()) {
829                                         dit.resize(i);
830                                         break;
831                                 }
832                         success = true;
833                 }
834         }
835
836         // if top_id == 0, or searching through top_id failed
837         // This is the case for a 'restored' bookmark when only bottom
838         // (document level) pit was saved. Because of this, bookmark
839         // restoration is inaccurate. If a bookmark was within an inset,
840         // it will be restored to the left of the outmost inset that contains
841         // the bookmark.
842         if (bottom_pit < int(buffer_.paragraphs().size())) {
843                 dit = doc_iterator_begin(&buffer_);
844
845                 dit.pit() = bottom_pit;
846                 dit.pos() = min(bottom_pos, dit.paragraph().size());
847                 success = true;
848         }
849
850         if (success) {
851                 // Note: only bottom (document) level pit is set.
852                 setCursor(dit);
853                 // set the current font.
854                 d->cursor_.setCurrentFont();
855                 // Do not forget to reset the anchor (see #9912)
856                 d->cursor_.resetAnchor();
857                 processUpdateFlags(Update::FitCursor);
858         }
859
860         return success;
861 }
862
863
864 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
865 {
866         if (d->cursor_.real_current_font.isRightToLeft()) {
867                 if (d->intl_.keymap == Intl::PRIMARY)
868                         d->intl_.keyMapSec();
869         } else {
870                 if (d->intl_.keymap == Intl::SECONDARY)
871                         d->intl_.keyMapPrim();
872         }
873
874         d->intl_.getTransManager().translateAndInsert(c, t, cur);
875 }
876
877
878 int BufferView::workWidth() const
879 {
880         return width_;
881 }
882
883
884 void BufferView::recenter()
885 {
886         showCursor(d->cursor_, true, true);
887 }
888
889
890 void BufferView::showCursor()
891 {
892         showCursor(d->cursor_, false, true);
893 }
894
895
896 void BufferView::showCursor(DocIterator const & dit,
897         bool recenter, bool update)
898 {
899         if (scrollToCursor(dit, recenter) && update)
900                 processUpdateFlags(Update::Force);
901 }
902
903
904 void BufferView::scrollToCursor()
905 {
906         if (scrollToCursor(d->cursor_, false))
907                 processUpdateFlags(Update::Force);
908 }
909
910
911 bool BufferView::scrollToCursor(DocIterator const & dit, bool const recenter)
912 {
913         // We are not properly started yet, delay until resizing is
914         // done.
915         if (height_ == 0)
916                 return false;
917
918         LYXERR(Debug::SCROLLING, "recentering!");
919
920         CursorSlice const & bot = dit.bottom();
921         TextMetrics & tm = d->text_metrics_[bot.text()];
922
923         pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
924         int bot_pit = bot.pit();
925         if (bot_pit > max_pit) {
926                 // FIXME: Why does this happen?
927                 LYXERR0("bottom pit is greater that max pit: "
928                         << bot_pit << " > " << max_pit);
929                 bot_pit = max_pit;
930         }
931
932         if (bot_pit == tm.first().first - 1)
933                 tm.newParMetricsUp();
934         else if (bot_pit == tm.last().first + 1)
935                 tm.newParMetricsDown();
936
937         if (tm.contains(bot_pit)) {
938                 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
939                 LBUFERR(!pm.rows().empty());
940                 // FIXME: smooth scrolling doesn't work in mathed.
941                 CursorSlice const & cs = dit.innerTextSlice();
942                 int offset = coordOffset(dit).y_;
943                 int ypos = pm.position() + offset;
944                 Dimension const & row_dim =
945                         pm.getRow(cs.pos(), dit.boundary()).dimension();
946                 int scrolled = 0;
947                 if (recenter)
948                         scrolled = scroll(ypos - height_/2);
949
950                 // We try to visualize the whole row, if the row height is larger than
951                 // the screen height, we scroll to a heuristic value of height_ / 4.
952                 // FIXME: This heuristic value should be replaced by a recursive search
953                 // for a row in the inset that can be visualized completely.
954                 else if (row_dim.height() > height_) {
955                         if (ypos < defaultRowHeight())
956                                 scrolled = scroll(ypos - height_ / 4);
957                         else if (ypos > height_ - defaultRowHeight())
958                                 scrolled = scroll(ypos - 3 * height_ / 4);
959                 }
960
961                 // If the top part of the row falls of the screen, we scroll
962                 // up to align the top of the row with the top of the screen.
963                 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
964                         int ynew = row_dim.ascent();
965                         scrolled = scrollUp(ynew - ypos);
966                 }
967
968                 // If the bottom of the row falls of the screen, we scroll down.
969                 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
970                         int ynew = height_ - row_dim.descent();
971                         scrolled = scrollDown(ypos - ynew);
972                 }
973
974                 // else, nothing to do, the cursor is already visible so we just return.
975                 return scrolled != 0;
976         }
977
978         // fix inline completion position
979         if (d->inlineCompletionPos_.fixIfBroken())
980                 d->inlineCompletionPos_ = DocIterator();
981
982         tm.redoParagraph(bot_pit);
983         ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
984         int offset = coordOffset(dit).y_;
985
986         d->anchor_pit_ = bot_pit;
987         CursorSlice const & cs = dit.innerTextSlice();
988         Dimension const & row_dim =
989                 pm.getRow(cs.pos(), dit.boundary()).dimension();
990
991         if (recenter)
992                 d->anchor_ypos_ = height_/2;
993         else if (d->anchor_pit_ == 0)
994                 d->anchor_ypos_ = offset + pm.ascent();
995         else if (d->anchor_pit_ == max_pit)
996                 d->anchor_ypos_ = height_ - offset - row_dim.descent();
997         else if (offset > height_)
998                 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
999         else
1000                 d->anchor_ypos_ = defaultRowHeight() * 2;
1001
1002         return true;
1003 }
1004
1005
1006 void BufferView::makeDocumentClass()
1007 {
1008         DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1009         buffer_.params().makeDocumentClass();
1010         updateDocumentClass(olddc);
1011 }
1012
1013
1014 void BufferView::updateDocumentClass(DocumentClassConstPtr olddc)
1015 {
1016         message(_("Converting document to new document class..."));
1017
1018         StableDocIterator backcur(d->cursor_);
1019         ErrorList & el = buffer_.errorList("Class Switch");
1020         cap::switchBetweenClasses(
1021                         olddc, buffer_.params().documentClassPtr(),
1022                         static_cast<InsetText &>(buffer_.inset()), el);
1023
1024         setCursor(backcur.asDocIterator(&buffer_));
1025
1026         buffer_.errors("Class Switch");
1027 }
1028
1029
1030 /** Return the change status at cursor position, taking into account the
1031  * status at each level of the document iterator (a table in a deleted
1032  * footnote is deleted).
1033  * When \param outer is true, the top slice is not looked at.
1034  */
1035 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
1036 {
1037         size_t const depth = dit.depth() - (outer ? 1 : 0);
1038
1039         for (size_t i = 0 ; i < depth ; ++i) {
1040                 CursorSlice const & slice = dit[i];
1041                 if (!slice.inset().inMathed()
1042                     && slice.pos() < slice.paragraph().size()) {
1043                         Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
1044                         if (ch != Change::UNCHANGED)
1045                                 return ch;
1046                 }
1047         }
1048         return Change::UNCHANGED;
1049 }
1050
1051
1052 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1053 {
1054         FuncCode const act = cmd.action();
1055
1056         // Can we use a readonly buffer?
1057         if (buffer_.isReadonly()
1058             && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1059             && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1060                 if (buffer_.hasReadonlyFlag())
1061                         flag.message(from_utf8(N_("Document is read-only")));
1062                 else
1063                         flag.message(from_utf8(N_("Document has been modified externally")));
1064                 flag.setEnabled(false);
1065                 return true;
1066         }
1067
1068         // Are we in a DELETED change-tracking region?
1069         if (lookupChangeType(d->cursor_, true) == Change::DELETED
1070             && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1071             && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1072                 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1073                 flag.setEnabled(false);
1074                 return true;
1075         }
1076
1077         Cursor & cur = d->cursor_;
1078
1079         if (cur.getStatus(cmd, flag))
1080                 return true;
1081
1082         switch (act) {
1083
1084         // FIXME: This is a bit problematic because we don't check if this is
1085         // a document BufferView or not for these LFUNs. We probably have to
1086         // dispatch both to currentBufferView() and, if that fails,
1087         // to documentBufferView(); same as we do now for current Buffer and
1088         // document Buffer. Ideally those LFUN should go to Buffer as they
1089         // operate on the full Buffer and the cursor is only needed either for
1090         // an Undo record or to restore a cursor position. But we don't know
1091         // how to do that inside Buffer of course.
1092         case LFUN_BUFFER_PARAMS_APPLY:
1093         case LFUN_LAYOUT_MODULES_CLEAR:
1094         case LFUN_LAYOUT_MODULE_ADD:
1095         case LFUN_LAYOUT_RELOAD:
1096         case LFUN_TEXTCLASS_APPLY:
1097         case LFUN_TEXTCLASS_LOAD:
1098                 flag.setEnabled(!buffer_.isReadonly());
1099                 break;
1100
1101         case LFUN_UNDO:
1102                 // We do not use the LyXAction flag for readonly because Undo sets the
1103                 // buffer clean/dirty status by itself.
1104                 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1105                 break;
1106         case LFUN_REDO:
1107                 // We do not use the LyXAction flag for readonly because Redo sets the
1108                 // buffer clean/dirty status by itself.
1109                 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1110                 break;
1111         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1112         case LFUN_FILE_INSERT_PLAINTEXT: {
1113                 docstring const fname = cmd.argument();
1114                 if (!FileName::isAbsolute(to_utf8(fname))) {
1115                         flag.message(_("Absolute filename expected."));
1116                         return false;
1117                 }
1118                 flag.setEnabled(cur.inTexted());
1119                 break;
1120         }
1121         case LFUN_FILE_INSERT:
1122         case LFUN_BOOKMARK_SAVE:
1123                 // FIXME: Actually, these LFUNS should be moved to Text
1124                 flag.setEnabled(cur.inTexted());
1125                 break;
1126
1127         case LFUN_FONT_STATE:
1128         case LFUN_LABEL_INSERT:
1129         case LFUN_INFO_INSERT:
1130         case LFUN_PARAGRAPH_GOTO:
1131         case LFUN_NOTE_NEXT:
1132         case LFUN_REFERENCE_NEXT:
1133         case LFUN_WORD_FIND:
1134         case LFUN_WORD_FIND_FORWARD:
1135         case LFUN_WORD_FIND_BACKWARD:
1136         case LFUN_WORD_REPLACE:
1137         case LFUN_BUFFER_ANONYMIZE:
1138         case LFUN_MARK_OFF:
1139         case LFUN_MARK_ON:
1140         case LFUN_MARK_TOGGLE:
1141         case LFUN_SCREEN_RECENTER:
1142         case LFUN_SCREEN_SHOW_CURSOR:
1143         case LFUN_BIBTEX_DATABASE_ADD:
1144         case LFUN_BIBTEX_DATABASE_DEL:
1145         case LFUN_STATISTICS:
1146         case LFUN_KEYMAP_OFF:
1147         case LFUN_KEYMAP_PRIMARY:
1148         case LFUN_KEYMAP_SECONDARY:
1149         case LFUN_KEYMAP_TOGGLE:
1150         case LFUN_INSET_SELECT_ALL:
1151                 flag.setEnabled(true);
1152                 break;
1153
1154         case LFUN_GRAPHICS_UNIFY:
1155                 flag.setEnabled(cur.selection());
1156                 break;
1157
1158         case LFUN_WORD_FINDADV: {
1159                 FindAndReplaceOptions opt;
1160                 istringstream iss(to_utf8(cmd.argument()));
1161                 iss >> opt;
1162                 flag.setEnabled(opt.repl_buf_name.empty()
1163                                 || !buffer_.isReadonly());
1164                 break;
1165         }
1166
1167         case LFUN_LABEL_GOTO:
1168                 flag.setEnabled(!cmd.argument().empty()
1169                     || getInsetByCode<InsetRef>(cur, REF_CODE));
1170                 break;
1171
1172         case LFUN_CHANGES_MERGE:
1173         case LFUN_CHANGE_NEXT:
1174         case LFUN_CHANGE_PREVIOUS:
1175         case LFUN_ALL_CHANGES_ACCEPT:
1176         case LFUN_ALL_CHANGES_REJECT:
1177                 flag.setEnabled(buffer_.areChangesPresent());
1178                 break;
1179
1180         case LFUN_SCREEN_UP:
1181         case LFUN_SCREEN_DOWN:
1182         case LFUN_SCROLL:
1183         case LFUN_SCREEN_UP_SELECT:
1184         case LFUN_SCREEN_DOWN_SELECT:
1185         case LFUN_INSET_FORALL:
1186                 flag.setEnabled(true);
1187                 break;
1188
1189         case LFUN_LAYOUT_TABULAR:
1190                 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1191                 break;
1192
1193         case LFUN_LAYOUT:
1194                 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1195                 break;
1196
1197         case LFUN_LAYOUT_PARAGRAPH:
1198                 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1199                 break;
1200
1201         case LFUN_BRANCH_ADD_INSERT:
1202                 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1203                 break;
1204
1205         case LFUN_DIALOG_SHOW_NEW_INSET:
1206                 // FIXME: this is wrong, but I do not understand the
1207                 // intent (JMarc)
1208                 if (cur.inset().lyxCode() == CAPTION_CODE)
1209                         return cur.inset().getStatus(cur, cmd, flag);
1210                 // FIXME we should consider passthru paragraphs too.
1211                 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1212                 break;
1213
1214         case LFUN_CITATION_INSERT: {
1215                 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1216                 // FIXME: This could turn in a recursive hell.
1217                 // Shouldn't we use Buffer::getStatus() instead?
1218                 flag.setEnabled(lyx::getStatus(fr).enabled());
1219                 break;
1220         }
1221         case LFUN_INSET_APPLY: {
1222                 string const name = cmd.getArg(0);
1223                 Inset * inset = editedInset(name);
1224                 if (inset) {
1225                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1226                         if (!inset->getStatus(cur, fr, flag)) {
1227                                 // Every inset is supposed to handle this
1228                                 LASSERT(false, break);
1229                         }
1230                 } else {
1231                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1232                         flag = lyx::getStatus(fr);
1233                 }
1234                 break;
1235         }
1236
1237         default:
1238                 return false;
1239         }
1240
1241         return true;
1242 }
1243
1244
1245 Inset * BufferView::editedInset(string const & name) const
1246 {
1247         map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1248         return it == d->edited_insets_.end() ? 0 : it->second;
1249 }
1250
1251
1252 void BufferView::editInset(string const & name, Inset * inset)
1253 {
1254         d->edited_insets_[name] = inset;
1255 }
1256
1257
1258 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1259 {
1260         LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1261
1262         string const argument = to_utf8(cmd.argument());
1263         Cursor & cur = d->cursor_;
1264         Cursor old = cur;
1265
1266         // Don't dispatch function that does not apply to internal buffers.
1267         if (buffer_.isInternal()
1268             && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1269                 return;
1270
1271         // We'll set this back to false if need be.
1272         bool dispatched = true;
1273         buffer_.undo().beginUndoGroup();
1274
1275         FuncCode const act = cmd.action();
1276         switch (act) {
1277
1278         case LFUN_BUFFER_PARAMS_APPLY: {
1279                 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1280                 cur.recordUndoBufferParams();
1281                 istringstream ss(to_utf8(cmd.argument()));
1282                 Lexer lex;
1283                 lex.setStream(ss);
1284                 int const unknown_tokens = buffer_.readHeader(lex);
1285                 if (unknown_tokens != 0) {
1286                         LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1287                                                 << unknown_tokens << " unknown token"
1288                                                 << (unknown_tokens == 1 ? "" : "s"));
1289                 }
1290                 updateDocumentClass(olddc);
1291
1292                 // We are most certainly here because of a change in the document
1293                 // It is then better to make sure that all dialogs are in sync with
1294                 // current document settings.
1295                 dr.screenUpdate(Update::Force | Update::FitCursor);
1296                 dr.forceBufferUpdate();
1297                 break;
1298         }
1299
1300         case LFUN_LAYOUT_MODULES_CLEAR: {
1301                 // FIXME: this modifies the document in cap::switchBetweenClasses
1302                 //  without calling recordUndo. Fix this before using
1303                 //  recordUndoBufferParams().
1304                 cur.recordUndoFullBuffer();
1305                 buffer_.params().clearLayoutModules();
1306                 makeDocumentClass();
1307                 dr.screenUpdate(Update::Force);
1308                 dr.forceBufferUpdate();
1309                 break;
1310         }
1311
1312         case LFUN_LAYOUT_MODULE_ADD: {
1313                 BufferParams const & params = buffer_.params();
1314                 if (!params.layoutModuleCanBeAdded(argument)) {
1315                         LYXERR0("Module `" << argument <<
1316                                 "' cannot be added due to failed requirements or "
1317                                 "conflicts with installed modules.");
1318                         break;
1319                 }
1320                 // FIXME: this modifies the document in cap::switchBetweenClasses
1321                 //  without calling recordUndo. Fix this before using
1322                 //  recordUndoBufferParams().
1323                 cur.recordUndoFullBuffer();
1324                 buffer_.params().addLayoutModule(argument);
1325                 makeDocumentClass();
1326                 dr.screenUpdate(Update::Force);
1327                 dr.forceBufferUpdate();
1328                 break;
1329         }
1330
1331         case LFUN_TEXTCLASS_APPLY: {
1332                 // since this shortcircuits, the second call is made only if
1333                 // the first fails
1334                 bool const success =
1335                         LayoutFileList::get().load(argument, buffer_.temppath()) ||
1336                         LayoutFileList::get().load(argument, buffer_.filePath());
1337                 if (!success) {
1338                         docstring s = bformat(_("The document class `%1$s' "
1339                                                  "could not be loaded."), from_utf8(argument));
1340                         frontend::Alert::error(_("Could not load class"), s);
1341                         break;
1342                 }
1343
1344                 LayoutFile const * old_layout = buffer_.params().baseClass();
1345                 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1346
1347                 if (old_layout == new_layout)
1348                         // nothing to do
1349                         break;
1350
1351                 // Save the old, possibly modular, layout for use in conversion.
1352                 // FIXME: this modifies the document in cap::switchBetweenClasses
1353                 //  without calling recordUndo. Fix this before using
1354                 //  recordUndoBufferParams().
1355                 cur.recordUndoFullBuffer();
1356                 buffer_.params().setBaseClass(argument);
1357                 makeDocumentClass();
1358                 dr.screenUpdate(Update::Force);
1359                 dr.forceBufferUpdate();
1360                 break;
1361         }
1362
1363         case LFUN_TEXTCLASS_LOAD: {
1364                 // since this shortcircuits, the second call is made only if
1365                 // the first fails
1366                 bool const success =
1367                         LayoutFileList::get().load(argument, buffer_.temppath()) ||
1368                         LayoutFileList::get().load(argument, buffer_.filePath());
1369                 if (!success) {
1370                         docstring s = bformat(_("The document class `%1$s' "
1371                                                  "could not be loaded."), from_utf8(argument));
1372                         frontend::Alert::error(_("Could not load class"), s);
1373                 }
1374                 break;
1375         }
1376
1377         case LFUN_LAYOUT_RELOAD: {
1378                 LayoutFileIndex bc = buffer_.params().baseClassID();
1379                 LayoutFileList::get().reset(bc);
1380                 buffer_.params().setBaseClass(bc);
1381                 makeDocumentClass();
1382                 dr.screenUpdate(Update::Force);
1383                 dr.forceBufferUpdate();
1384                 break;
1385         }
1386
1387         case LFUN_UNDO: {
1388                 dr.setMessage(_("Undo"));
1389                 cur.clearSelection();
1390                 // We need to find out if the bibliography information
1391                 // has changed. See bug #11055.
1392                 // So these should not be references...
1393                 LayoutModuleList const engines = buffer().params().citeEngine();
1394                 CiteEngineType const enginetype = buffer().params().citeEngineType();
1395                 if (!cur.textUndo())
1396                         dr.setMessage(_("No further undo information"));
1397                 else {
1398                         dr.screenUpdate(Update::Force | Update::FitCursor);
1399                         dr.forceBufferUpdate();
1400                         if (buffer().params().citeEngine() != engines ||
1401                             buffer().params().citeEngineType() != enginetype)
1402                                 buffer().invalidateCiteLabels();
1403                 }
1404                 break;
1405         }
1406
1407         case LFUN_REDO: {
1408                 dr.setMessage(_("Redo"));
1409                 cur.clearSelection();
1410                 // We need to find out if the bibliography information
1411                 // has changed. See bug #11055.
1412                 // So these should not be references...
1413                 LayoutModuleList const engines = buffer().params().citeEngine();
1414                 CiteEngineType const enginetype = buffer().params().citeEngineType();
1415                 if (!cur.textRedo())
1416                         dr.setMessage(_("No further redo information"));
1417                 else {
1418                         dr.screenUpdate(Update::Force | Update::FitCursor);
1419                         dr.forceBufferUpdate();
1420                         if (buffer().params().citeEngine() != engines ||
1421                             buffer().params().citeEngineType() != enginetype)
1422                                 buffer().invalidateCiteLabels();
1423                 }
1424                 break;
1425         }
1426
1427         case LFUN_FONT_STATE:
1428                 dr.setMessage(cur.currentState(false));
1429                 break;
1430
1431         case LFUN_BOOKMARK_SAVE:
1432                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1433                 break;
1434
1435         case LFUN_LABEL_GOTO: {
1436                 docstring label = cmd.argument();
1437                 if (label.empty()) {
1438                         InsetRef * inset =
1439                                 getInsetByCode<InsetRef>(cur, REF_CODE);
1440                         if (inset) {
1441                                 label = inset->getParam("reference");
1442                                 // persistent=false: use temp_bookmark
1443                                 saveBookmark(0);
1444                         }
1445                 }
1446                 if (!label.empty()) {
1447                         gotoLabel(label);
1448                         // at the moment, this is redundant, since gotoLabel will
1449                         // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1450                         // to have it here.
1451                         dr.screenUpdate(Update::Force | Update::FitCursor);
1452                 }
1453                 break;
1454         }
1455
1456         case LFUN_PARAGRAPH_GOTO: {
1457                 int const id = convert<int>(cmd.getArg(0));
1458                 pos_type const pos = convert<int>(cmd.getArg(1));
1459                 if (id < 0)
1460                         break;
1461                 string const str_id_end = cmd.getArg(2);
1462                 string const str_pos_end = cmd.getArg(3);
1463                 int i = 0;
1464                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1465                         b = theBufferList().next(b)) {
1466
1467                         Cursor cur(*this);
1468                         cur.setCursor(b->getParFromID(id));
1469                         if (cur.atEnd()) {
1470                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1471                                 ++i;
1472                                 continue;
1473                         }
1474                         LYXERR(Debug::INFO, "Paragraph " << cur.paragraph().id()
1475                                 << " found in buffer `"
1476                                 << b->absFileName() << "'.");
1477
1478                         if (b == &buffer_) {
1479                                 bool success;
1480                                 if (str_id_end.empty() || str_pos_end.empty()) {
1481                                         // Set the cursor
1482                                         cur.pos() = pos;
1483                                         mouseSetCursor(cur);
1484                                         success = true;
1485                                 } else {
1486                                         int const id_end = convert<int>(str_id_end);
1487                                         pos_type const pos_end = convert<int>(str_pos_end);
1488                                         success = setCursorFromEntries({id, pos},
1489                                                                        {id_end, pos_end});
1490                                 }
1491                                 if (success)
1492                                         dr.screenUpdate(Update::Force | Update::FitCursor);
1493                         } else {
1494                                 // Switch to other buffer view and resend cmd
1495                                 lyx::dispatch(FuncRequest(
1496                                         LFUN_BUFFER_SWITCH, b->absFileName()));
1497                                 lyx::dispatch(cmd);
1498                         }
1499                         break;
1500                 }
1501                 break;
1502         }
1503
1504         case LFUN_NOTE_NEXT:
1505                 gotoInset(this, NOTE_CODE, false);
1506                 break;
1507
1508         case LFUN_REFERENCE_NEXT: {
1509                 vector<InsetCode> tmp;
1510                 tmp.push_back(LABEL_CODE);
1511                 tmp.push_back(REF_CODE);
1512                 gotoInset(this, tmp, true);
1513                 break;
1514         }
1515
1516         case LFUN_CHANGE_NEXT:
1517                 findNextChange(this);
1518                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1519                 dr.screenUpdate(Update::Force | Update::FitCursor);
1520                 break;
1521
1522         case LFUN_CHANGE_PREVIOUS:
1523                 findPreviousChange(this);
1524                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1525                 dr.screenUpdate(Update::Force | Update::FitCursor);
1526                 break;
1527
1528         case LFUN_CHANGES_MERGE:
1529                 if (findNextChange(this) || findPreviousChange(this)) {
1530                         dr.screenUpdate(Update::Force | Update::FitCursor);
1531                         dr.forceBufferUpdate();
1532                         showDialog("changes");
1533                 }
1534                 break;
1535
1536         case LFUN_ALL_CHANGES_ACCEPT:
1537                 // select complete document
1538                 cur.reset();
1539                 cur.selHandle(true);
1540                 buffer_.text().cursorBottom(cur);
1541                 // accept everything in a single step to support atomic undo
1542                 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1543                 cur.resetAnchor();
1544                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1545                 dr.screenUpdate(Update::Force | Update::FitCursor);
1546                 dr.forceBufferUpdate();
1547                 break;
1548
1549         case LFUN_ALL_CHANGES_REJECT:
1550                 // select complete document
1551                 cur.reset();
1552                 cur.selHandle(true);
1553                 buffer_.text().cursorBottom(cur);
1554                 // reject everything in a single step to support atomic undo
1555                 // Note: reject does not work recursively; the user may have to repeat the operation
1556                 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1557                 cur.resetAnchor();
1558                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1559                 dr.screenUpdate(Update::Force | Update::FitCursor);
1560                 dr.forceBufferUpdate();
1561                 break;
1562
1563         case LFUN_WORD_FIND_FORWARD:
1564         case LFUN_WORD_FIND_BACKWARD: {
1565                 // FIXME THREAD
1566                 // Would it maybe be better if this variable were view specific anyway?
1567                 static docstring last_search;
1568                 docstring searched_string;
1569
1570                 if (!cmd.argument().empty()) {
1571                         last_search = cmd.argument();
1572                         searched_string = cmd.argument();
1573                 } else {
1574                         searched_string = last_search;
1575                 }
1576
1577                 if (searched_string.empty())
1578                         break;
1579
1580                 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1581                 docstring const data =
1582                         find2string(searched_string, true, false, fw);
1583                 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1584                 if (found)
1585                         dr.screenUpdate(Update::Force | Update::FitCursor);
1586                 break;
1587         }
1588
1589         case LFUN_WORD_FIND: {
1590                 FuncRequest req = cmd;
1591                 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1592                         req = d->search_request_cache_;
1593                 if (req.argument().empty()) {
1594                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1595                         break;
1596                 }
1597                 if (lyxfind(this, req))
1598                         dr.screenUpdate(Update::Force | Update::FitCursor);
1599
1600                 d->search_request_cache_ = req;
1601                 break;
1602         }
1603
1604         case LFUN_WORD_REPLACE: {
1605                 bool has_deleted = false;
1606                 if (cur.selection()) {
1607                         DocIterator beg = cur.selectionBegin();
1608                         DocIterator end = cur.selectionEnd();
1609                         if (beg.pit() == end.pit()) {
1610                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1611                                         if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1612                                                 has_deleted = true;
1613                                                 break;
1614                                         }
1615                                 }
1616                         }
1617                 }
1618                 if (lyxreplace(this, cmd, has_deleted)) {
1619                         dr.forceBufferUpdate();
1620                         dr.screenUpdate(Update::Force | Update::FitCursor);
1621                 }
1622                 break;
1623         }
1624
1625         case LFUN_BUFFER_ANONYMIZE: {
1626                 for (char c = '0'; c <= 'Z'; c++) {
1627                         odocstringstream ss;
1628                         ss << "a\n" << c << "\n0 0 1 1 0";
1629                         lyx::dispatch(FuncRequest(LFUN_WORD_REPLACE, ss.str()));
1630                 }
1631                 break;
1632         }
1633
1634         case LFUN_WORD_FINDADV: {
1635                 FindAndReplaceOptions opt;
1636                 istringstream iss(to_utf8(cmd.argument()));
1637                 iss >> opt;
1638                 if (findAdv(this, opt)) {
1639                         dr.screenUpdate(Update::Force | Update::FitCursor);
1640                         cur.dispatched();
1641                         dispatched = true;
1642                 } else {
1643                         cur.undispatched();
1644                         dispatched = false;
1645                 }
1646                 break;
1647         }
1648
1649         case LFUN_MARK_OFF:
1650                 cur.clearSelection();
1651                 dr.setMessage(from_utf8(N_("Mark off")));
1652                 break;
1653
1654         case LFUN_MARK_ON:
1655                 cur.clearSelection();
1656                 cur.setMark(true);
1657                 dr.setMessage(from_utf8(N_("Mark on")));
1658                 break;
1659
1660         case LFUN_MARK_TOGGLE:
1661                 cur.selection(false);
1662                 if (cur.mark()) {
1663                         cur.setMark(false);
1664                         dr.setMessage(from_utf8(N_("Mark removed")));
1665                 } else {
1666                         cur.setMark(true);
1667                         dr.setMessage(from_utf8(N_("Mark set")));
1668                 }
1669                 cur.resetAnchor();
1670                 break;
1671
1672         case LFUN_SCREEN_SHOW_CURSOR:
1673                 showCursor();
1674                 break;
1675
1676         case LFUN_SCREEN_RECENTER:
1677                 recenter();
1678                 break;
1679
1680         case LFUN_BIBTEX_DATABASE_ADD: {
1681                 Cursor tmpcur = cur;
1682                 findInset(tmpcur, BIBTEX_CODE, false);
1683                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1684                                                 BIBTEX_CODE);
1685                 if (inset) {
1686                         if (inset->addDatabase(cmd.argument()))
1687                                 dr.forceBufferUpdate();
1688                 }
1689                 break;
1690         }
1691
1692         case LFUN_BIBTEX_DATABASE_DEL: {
1693                 Cursor tmpcur = cur;
1694                 findInset(tmpcur, BIBTEX_CODE, false);
1695                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1696                                                 BIBTEX_CODE);
1697                 if (inset) {
1698                         if (inset->delDatabase(cmd.argument()))
1699                                 dr.forceBufferUpdate();
1700                 }
1701                 break;
1702         }
1703
1704         case LFUN_GRAPHICS_UNIFY: {
1705
1706                 cur.recordUndoFullBuffer();
1707
1708                 DocIterator from, to;
1709                 from = cur.selectionBegin();
1710                 to = cur.selectionEnd();
1711
1712                 string newId = cmd.getArg(0);
1713                 bool fetchId=newId.empty(); //if we wait for groupId from first graphics inset
1714
1715                 InsetGraphicsParams grp_par;
1716                 InsetGraphics::string2params(graphics::getGroupParams(buffer_, newId), buffer_, grp_par);
1717
1718                 if (!from.nextInset())  //move to closest inset
1719                         from.forwardInset();
1720
1721                 while (!from.empty() && from < to) {
1722                         Inset * inset = from.nextInset();
1723                         if (!inset)
1724                                 break;
1725                         if (inset->lyxCode() == GRAPHICS_CODE) {
1726                                 InsetGraphics * ig = inset->asInsetGraphics();
1727                                 if (!ig)
1728                                         break;
1729                                 InsetGraphicsParams inspar = ig->getParams();
1730                                 if (fetchId) {
1731                                         grp_par = inspar;
1732                                         fetchId = false;
1733
1734                                 } else {
1735                                         grp_par.filename = inspar.filename;
1736                                         ig->setParams(grp_par);
1737                                 }
1738                         }
1739                         from.forwardInset();
1740                 }
1741                 dr.screenUpdate(Update::Force); //needed if triggered from context menu
1742                 break;
1743         }
1744
1745         case LFUN_STATISTICS: {
1746                 DocIterator from, to;
1747                 if (cur.selection()) {
1748                         from = cur.selectionBegin();
1749                         to = cur.selectionEnd();
1750                 } else {
1751                         from = doc_iterator_begin(&buffer_);
1752                         to = doc_iterator_end(&buffer_);
1753                 }
1754                 buffer_.updateStatistics(from, to);
1755                 int const words = buffer_.wordCount();
1756                 int const chars = buffer_.charCount(false);
1757                 int const chars_blanks = buffer_.charCount(true);
1758                 docstring message;
1759                 if (cur.selection())
1760                         message = _("Statistics for the selection:");
1761                 else
1762                         message = _("Statistics for the document:");
1763                 message += "\n\n";
1764                 if (words != 1)
1765                         message += bformat(_("%1$d words"), words);
1766                 else
1767                         message += _("One word");
1768                 message += "\n";
1769                 if (chars_blanks != 1)
1770                         message += bformat(_("%1$d characters (including blanks)"),
1771                                           chars_blanks);
1772                 else
1773                         message += _("One character (including blanks)");
1774                 message += "\n";
1775                 if (chars != 1)
1776                         message += bformat(_("%1$d characters (excluding blanks)"),
1777                                           chars);
1778                 else
1779                         message += _("One character (excluding blanks)");
1780
1781                 Alert::information(_("Statistics"), message);
1782         }
1783                 break;
1784
1785         case LFUN_SCREEN_UP:
1786         case LFUN_SCREEN_DOWN: {
1787                 Point p = getPos(cur);
1788                 // This code has been commented out to enable to scroll down a
1789                 // document, even if there are large insets in it (see bug #5465).
1790                 /*if (p.y_ < 0 || p.y_ > height_) {
1791                         // The cursor is off-screen so recenter before proceeding.
1792                         showCursor();
1793                         p = getPos(cur);
1794                 }*/
1795                 int const scrolled = scroll(act == LFUN_SCREEN_UP
1796                         ? -height_ : height_);
1797                 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1798                         p = Point(0, 0);
1799                 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1800                         p = Point(width_, height_);
1801                 bool const in_texted = cur.inTexted();
1802                 cur.setCursor(doc_iterator_begin(cur.buffer()));
1803                 cur.selHandle(false);
1804                 // Force an immediate computation of metrics because we need it below
1805                 processUpdateFlags(Update::Force);
1806
1807                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1808                         true, act == LFUN_SCREEN_UP);
1809                 //FIXME: what to do with cur.x_target()?
1810                 bool update = in_texted && cur.bv().checkDepm(cur, old);
1811                 cur.finishUndo();
1812
1813                 if (update || cur.mark())
1814                         dr.screenUpdate(Update::Force | Update::FitCursor);
1815                 if (update)
1816                         dr.forceBufferUpdate();
1817                 break;
1818         }
1819
1820         case LFUN_SCROLL: {
1821                 string const scroll_type = cmd.getArg(0);
1822                 int scroll_step = 0;
1823                 if (scroll_type == "line")
1824                         scroll_step = d->scrollbarParameters_.single_step;
1825                 else if (scroll_type == "page")
1826                         scroll_step = d->scrollbarParameters_.page_step;
1827                 else
1828                         return;
1829                 string const scroll_quantity = cmd.getArg(1);
1830                 if (scroll_quantity == "up")
1831                         scrollUp(scroll_step);
1832                 else if (scroll_quantity == "down")
1833                         scrollDown(scroll_step);
1834                 else {
1835                         int const scroll_value = convert<int>(scroll_quantity);
1836                         if (scroll_value)
1837                                 scroll(scroll_step * scroll_value);
1838                 }
1839                 dr.screenUpdate(Update::ForceDraw);
1840                 dr.forceBufferUpdate();
1841                 break;
1842         }
1843
1844         case LFUN_SCREEN_UP_SELECT: {
1845                 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
1846                 cur.selHandle(true);
1847                 if (isTopScreen()) {
1848                         lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1849                         cur.finishUndo();
1850                         break;
1851                 }
1852                 int y = getPos(cur).y_;
1853                 int const ymin = y - height_ + defaultRowHeight();
1854                 while (y > ymin && cur.up())
1855                         y = getPos(cur).y_;
1856
1857                 cur.finishUndo();
1858                 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1859                 break;
1860         }
1861
1862         case LFUN_SCREEN_DOWN_SELECT: {
1863                 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
1864                 cur.selHandle(true);
1865                 if (isBottomScreen()) {
1866                         lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1867                         cur.finishUndo();
1868                         break;
1869                 }
1870                 int y = getPos(cur).y_;
1871                 int const ymax = y + height_ - defaultRowHeight();
1872                 while (y < ymax && cur.down())
1873                         y = getPos(cur).y_;
1874
1875                 cur.finishUndo();
1876                 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1877                 break;
1878         }
1879
1880
1881         case LFUN_INSET_SELECT_ALL: {
1882                 // true if all cells are selected
1883                 bool const all_selected = cur.depth() > 1
1884                     && cur.selBegin().at_begin()
1885                     && cur.selEnd().at_end();
1886                 // true if some cells are selected
1887                 bool const cells_selected = cur.depth() > 1
1888                     && cur.selBegin().at_cell_begin()
1889                         && cur.selEnd().at_cell_end();
1890                 if (all_selected || (cells_selected && !cur.inset().isTable())) {
1891                         // All the contents of the inset if selected, or only at
1892                         // least one cell but inset is not a table.
1893                         // Select the inset from outside.
1894                         cur.pop();
1895                         cur.resetAnchor();
1896                         cur.selection(true);
1897                         cur.posForward();
1898                 } else if (cells_selected) {
1899                         // At least one complete cell is selected and inset is a table.
1900                         // Select all cells
1901                         cur.idx() = 0;
1902                         cur.pos() = 0;
1903                         cur.resetAnchor();
1904                         cur.selection(true);
1905                         cur.idx() = cur.lastidx();
1906                         cur.pos() = cur.lastpos();
1907                 } else {
1908                         // select current cell
1909                         cur.pit() = 0;
1910                         cur.pos() = 0;
1911                         cur.resetAnchor();
1912                         cur.selection(true);
1913                         cur.pit() = cur.lastpit();
1914                         cur.pos() = cur.lastpos();
1915                 }
1916                 cur.setCurrentFont();
1917                 dr.screenUpdate(Update::Force);
1918                 break;
1919         }
1920
1921
1922         // This would be in Buffer class if only Cursor did not
1923         // require a bufferview
1924         case LFUN_INSET_FORALL: {
1925                 docstring const name = from_utf8(cmd.getArg(0));
1926                 string const commandstr = cmd.getLongArg(1);
1927                 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1928
1929                 // an arbitrary number to limit number of iterations
1930                 const int max_iter = 100000;
1931                 int iterations = 0;
1932                 Cursor & cur = d->cursor_;
1933                 Cursor const savecur = cur;
1934                 cur.reset();
1935                 if (!cur.nextInset())
1936                         cur.forwardInset();
1937                 cur.beginUndoGroup();
1938                 while(cur && iterations < max_iter) {
1939                         Inset * const ins = cur.nextInset();
1940                         if (!ins)
1941                                 break;
1942                         docstring insname = ins->layoutName();
1943                         while (!insname.empty()) {
1944                                 if (insname == name || name == from_utf8("*")) {
1945                                         cur.recordUndo();
1946                                         lyx::dispatch(fr, dr);
1947                                         ++iterations;
1948                                         break;
1949                                 }
1950                                 size_t const i = insname.rfind(':');
1951                                 if (i == string::npos)
1952                                         break;
1953                                 insname = insname.substr(0, i);
1954                         }
1955                         // if we did not delete the inset, skip it
1956                         if (!cur.nextInset() || cur.nextInset() == ins)
1957                                 cur.forwardInset();
1958                 }
1959                 cur = savecur;
1960                 cur.fixIfBroken();
1961                 /** This is a dummy undo record only to remember the cursor
1962                  * that has just been set; this will be used on a redo action
1963                  * (see ticket #10097)
1964
1965                  * FIXME: a better fix would be to have a way to set the
1966                  * cursor value directly, but I am not sure it is worth it.
1967                  */
1968                 cur.recordUndo();
1969                 cur.endUndoGroup();
1970                 dr.screenUpdate(Update::Force);
1971                 dr.forceBufferUpdate();
1972
1973                 if (iterations >= max_iter) {
1974                         dr.setError(true);
1975                         dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1976                 } else
1977                         dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1978                 break;
1979         }
1980
1981
1982         case LFUN_BRANCH_ADD_INSERT: {
1983                 docstring branch_name = from_utf8(cmd.getArg(0));
1984                 if (branch_name.empty())
1985                         if (!Alert::askForText(branch_name, _("Branch name")) ||
1986                                                 branch_name.empty())
1987                                 break;
1988
1989                 DispatchResult drtmp;
1990                 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1991                 if (drtmp.error()) {
1992                         Alert::warning(_("Branch already exists"), drtmp.message());
1993                         break;
1994                 }
1995                 docstring const sep = buffer_.params().branchlist().separator();
1996                 for (docstring const & branch : getVectorFromString(branch_name, sep))
1997                         lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch));
1998                 break;
1999         }
2000
2001         case LFUN_KEYMAP_OFF:
2002                 getIntl().keyMapOn(false);
2003                 break;
2004
2005         case LFUN_KEYMAP_PRIMARY:
2006                 getIntl().keyMapPrim();
2007                 break;
2008
2009         case LFUN_KEYMAP_SECONDARY:
2010                 getIntl().keyMapSec();
2011                 break;
2012
2013         case LFUN_KEYMAP_TOGGLE:
2014                 getIntl().toggleKeyMap();
2015                 break;
2016
2017         case LFUN_DIALOG_SHOW_NEW_INSET: {
2018                 string const name = cmd.getArg(0);
2019                 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2020                 if (decodeInsetParam(name, data, buffer_))
2021                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
2022                 else
2023                         lyxerr << "Inset type '" << name <<
2024                         "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" <<  endl;
2025                 break;
2026         }
2027
2028         case LFUN_CITATION_INSERT: {
2029                 if (argument.empty()) {
2030                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
2031                         break;
2032                 }
2033                 // we can have one optional argument, delimited by '|'
2034                 // citation-insert <key>|<text_before>
2035                 // this should be enhanced to also support text_after
2036                 // and citation style
2037                 string arg = argument;
2038                 string opt1;
2039                 if (contains(argument, "|")) {
2040                         arg = token(argument, '|', 0);
2041                         opt1 = token(argument, '|', 1);
2042                 }
2043
2044                 // if our cursor is directly in front of or behind a citation inset,
2045                 // we will instead add the new key to it.
2046                 Inset * inset = cur.nextInset();
2047                 if (!inset || inset->lyxCode() != CITE_CODE)
2048                         inset = cur.prevInset();
2049                 if (inset && inset->lyxCode() == CITE_CODE) {
2050                         InsetCitation * icite = static_cast<InsetCitation *>(inset);
2051                         if (icite->addKey(arg)) {
2052                                 dr.forceBufferUpdate();
2053                                 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
2054                                 if (!opt1.empty())
2055                                         LYXERR0("Discarding optional argument to citation-insert.");
2056                         }
2057                         dispatched = true;
2058                         break;
2059                 }
2060                 InsetCommandParams icp(CITE_CODE);
2061                 icp["key"] = from_utf8(arg);
2062                 if (!opt1.empty())
2063                         icp["before"] = from_utf8(opt1);
2064                 string icstr = InsetCommand::params2string(icp);
2065                 FuncRequest fr(LFUN_INSET_INSERT, icstr);
2066                 lyx::dispatch(fr);
2067                 break;
2068         }
2069
2070         case LFUN_INSET_APPLY: {
2071                 string const name = cmd.getArg(0);
2072                 Inset * inset = editedInset(name);
2073                 if (!inset) {
2074                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2075                         lyx::dispatch(fr);
2076                         break;
2077                 }
2078                 // put cursor in front of inset.
2079                 if (!setCursorFromInset(inset)) {
2080                         LASSERT(false, break);
2081                 }
2082                 cur.recordUndo();
2083                 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2084                 inset->dispatch(cur, fr);
2085                 dr.screenUpdate(cur.result().screenUpdate());
2086                 if (cur.result().needBufferUpdate())
2087                         dr.forceBufferUpdate();
2088                 break;
2089         }
2090
2091         // FIXME:
2092         // The change of language of buffer belongs to the Buffer class.
2093         // We have to do it here because we need a cursor for Undo.
2094         // When Undo::recordUndoBufferParams() is implemented someday
2095         // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
2096         case LFUN_BUFFER_LANGUAGE: {
2097                 Language const * oldL = buffer_.params().language;
2098                 Language const * newL = languages.getLanguage(argument);
2099                 if (!newL || oldL == newL)
2100                         break;
2101                 if (oldL->rightToLeft() == newL->rightToLeft()) {
2102                         cur.recordUndoFullBuffer();
2103                         buffer_.changeLanguage(oldL, newL);
2104                         cur.setCurrentFont();
2105                         dr.forceBufferUpdate();
2106                 }
2107                 break;
2108         }
2109
2110         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2111         case LFUN_FILE_INSERT_PLAINTEXT: {
2112                 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
2113                 string const fname = to_utf8(cmd.argument());
2114                 if (!FileName::isAbsolute(fname))
2115                         dr.setMessage(_("Absolute filename expected."));
2116                 else
2117                         insertPlaintextFile(FileName(fname), as_paragraph);
2118                 break;
2119         }
2120
2121         default:
2122                 // OK, so try the Buffer itself...
2123                 buffer_.dispatch(cmd, dr);
2124                 dispatched = dr.dispatched();
2125                 break;
2126         }
2127
2128         buffer_.undo().endUndoGroup();
2129         dr.dispatched(dispatched);
2130
2131         // NOTE: The code below is copied from Cursor::dispatch. If you
2132         // need to modify this, please update the other one too.
2133
2134         // notify insets we just entered/left
2135         if (cursor() != old) {
2136                 old.beginUndoGroup();
2137                 old.fixIfBroken();
2138                 bool badcursor = notifyCursorLeavesOrEnters(old, cursor());
2139                 if (badcursor) {
2140                         cursor().fixIfBroken();
2141                         resetInlineCompletionPos();
2142                 }
2143                 old.endUndoGroup();
2144         }
2145 }
2146
2147
2148 docstring const BufferView::requestSelection()
2149 {
2150         Cursor & cur = d->cursor_;
2151
2152         LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2153         if (!cur.selection()) {
2154                 d->xsel_cache_.set = false;
2155                 return docstring();
2156         }
2157
2158         LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2159         if (!d->xsel_cache_.set ||
2160             cur.top() != d->xsel_cache_.cursor ||
2161             cur.realAnchor().top() != d->xsel_cache_.anchor)
2162         {
2163                 d->xsel_cache_.cursor = cur.top();
2164                 d->xsel_cache_.anchor = cur.realAnchor().top();
2165                 d->xsel_cache_.set = cur.selection();
2166                 return cur.selectionAsString(false);
2167         }
2168         return docstring();
2169 }
2170
2171
2172 void BufferView::clearSelection()
2173 {
2174         d->cursor_.clearSelection();
2175         // Clear the selection buffer. Otherwise a subsequent
2176         // middle-mouse-button paste would use the selection buffer,
2177         // not the more current external selection.
2178         cap::clearSelection();
2179         d->xsel_cache_.set = false;
2180         // The buffer did not really change, but this causes the
2181         // redraw we need because we cleared the selection above.
2182         buffer_.changed(false);
2183 }
2184
2185
2186 void BufferView::resize(int width, int height)
2187 {
2188         // Update from work area
2189         width_ = width;
2190         height_ = height;
2191
2192         // Clear the paragraph height cache.
2193         d->par_height_.clear();
2194         // Redo the metrics.
2195         updateMetrics();
2196 }
2197
2198
2199 Inset const * BufferView::getCoveringInset(Text const & text,
2200                 int x, int y) const
2201 {
2202         TextMetrics & tm = d->text_metrics_[&text];
2203         Inset * inset = tm.checkInsetHit(x, y);
2204         if (!inset)
2205                 return 0;
2206
2207         if (!inset->descendable(*this))
2208                 // No need to go further down if the inset is not
2209                 // descendable.
2210                 return inset;
2211
2212         size_t cell_number = inset->nargs();
2213         // Check all the inner cell.
2214         for (size_t i = 0; i != cell_number; ++i) {
2215                 Text const * inner_text = inset->getText(i);
2216                 if (inner_text) {
2217                         // Try deeper.
2218                         Inset const * inset_deeper =
2219                                 getCoveringInset(*inner_text, x, y);
2220                         if (inset_deeper)
2221                                 return inset_deeper;
2222                 }
2223         }
2224
2225         return inset;
2226 }
2227
2228
2229 void BufferView::updateHoveredInset() const
2230 {
2231         // Get inset under mouse, if there is one.
2232         int const x = d->mouse_position_cache_.x_;
2233         int const y = d->mouse_position_cache_.y_;
2234         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2235
2236         d->clickable_inset_ = covering_inset && covering_inset->clickable(*this, x, y);
2237
2238         if (covering_inset == d->last_inset_)
2239                 // Same inset, no need to do anything...
2240                 return;
2241
2242         bool need_redraw = false;
2243         if (d->last_inset_) {
2244                 // Remove the hint on the last hovered inset (if any).
2245                 need_redraw |= d->last_inset_->setMouseHover(this, false);
2246                 d->last_inset_ = 0;
2247         }
2248
2249         if (covering_inset && covering_inset->setMouseHover(this, true)) {
2250                 need_redraw = true;
2251                 // Only the insets that accept the hover state, do
2252                 // clear the last_inset_, so only set the last_inset_
2253                 // member if the hovered setting is accepted.
2254                 d->last_inset_ = covering_inset;
2255         }
2256
2257         if (need_redraw) {
2258                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2259                                 << d->mouse_position_cache_.x_ << ", "
2260                                 << d->mouse_position_cache_.y_ << ")");
2261
2262                 d->update_strategy_ = DecorationUpdate;
2263
2264                 // This event (moving without mouse click) is not passed further.
2265                 // This should be changed if it is further utilized.
2266                 buffer_.changed(false);
2267         }
2268 }
2269
2270
2271 void BufferView::clearLastInset(Inset * inset) const
2272 {
2273         if (d->last_inset_ != inset) {
2274                 LYXERR0("Wrong last_inset!");
2275                 LATTEST(false);
2276         }
2277         d->last_inset_ = 0;
2278 }
2279
2280
2281 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2282 {
2283         //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2284
2285         // This is only called for mouse related events including
2286         // LFUN_FILE_OPEN generated by drag-and-drop.
2287         FuncRequest cmd = cmd0;
2288
2289         Cursor old = cursor();
2290         Cursor cur(*this);
2291         cur.push(buffer_.inset());
2292         cur.selection(d->cursor_.selection());
2293
2294         // Either the inset under the cursor or the
2295         // surrounding Text will handle this event.
2296
2297         // make sure we stay within the screen...
2298         cmd.set_y(min(max(cmd.y(), -1), height_));
2299
2300         d->mouse_position_cache_.x_ = cmd.x();
2301         d->mouse_position_cache_.y_ = cmd.y();
2302
2303         if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2304                 updateHoveredInset();
2305                 return;
2306         }
2307
2308         // Build temporary cursor.
2309         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2310         if (inset) {
2311                 // If inset is not editable, cur.pos() might point behind the
2312                 // inset (depending on cmd.x(), cmd.y()). This is needed for
2313                 // editing to fix bug 9628, but e.g. the context menu needs a
2314                 // cursor in front of the inset.
2315                 if ((inset->hasSettings() || !inset->contextMenuName().empty()
2316                      || inset->lyxCode() == SEPARATOR_CODE) &&
2317                     cur.nextInset() != inset && cur.prevInset() == inset)
2318                         cur.posBackward();
2319         } else if (cur.inTexted() && cur.pos()
2320                         && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
2321                 // Always place cursor in front of a separator inset.
2322                 cur.posBackward();
2323         }
2324
2325         // Put anchor at the same position.
2326         cur.resetAnchor();
2327
2328         cur.beginUndoGroup();
2329
2330         // Try to dispatch to an non-editable inset near this position
2331         // via the temp cursor. If the inset wishes to change the real
2332         // cursor it has to do so explicitly by using
2333         //  cur.bv().cursor() = cur;  (or similar)
2334         if (inset)
2335                 inset->dispatch(cur, cmd);
2336
2337         // Now dispatch to the temporary cursor. If the real cursor should
2338         // be modified, the inset's dispatch has to do so explicitly.
2339         if (!inset || !cur.result().dispatched())
2340                 cur.dispatch(cmd);
2341
2342         // Notify left insets
2343         if (cur != old) {
2344                 bool badcursor = old.fixIfBroken() | cur.fixIfBroken();
2345                 badcursor |= notifyCursorLeavesOrEnters(old, cur);
2346                 if (badcursor)
2347                         cursor().fixIfBroken();
2348         }
2349
2350         cur.endUndoGroup();
2351
2352         // Do we have a selection?
2353         theSelection().haveSelection(cursor().selection());
2354
2355         if (cur.needBufferUpdate()) {
2356                 cur.clearBufferUpdate();
2357                 buffer().updateBuffer();
2358         }
2359
2360         // If the command has been dispatched,
2361         if (cur.result().dispatched() || cur.result().screenUpdate())
2362                 processUpdateFlags(cur.result().screenUpdate());
2363 }
2364
2365
2366 int BufferView::minVisiblePart()
2367 {
2368         return 2 * defaultRowHeight();
2369 }
2370
2371
2372 int BufferView::scroll(int y)
2373 {
2374         if (y > 0)
2375                 return scrollDown(y);
2376         if (y < 0)
2377                 return scrollUp(-y);
2378         return 0;
2379 }
2380
2381
2382 int BufferView::scrollDown(int offset)
2383 {
2384         Text * text = &buffer_.text();
2385         TextMetrics & tm = d->text_metrics_[text];
2386         int const ymax = height_ + offset;
2387         while (true) {
2388                 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2389                 int bottom_pos = last.second->position() + last.second->descent();
2390                 if (lyxrc.scroll_below_document)
2391                         bottom_pos += height_ - minVisiblePart();
2392                 if (last.first + 1 == int(text->paragraphs().size())) {
2393                         if (bottom_pos <= height_)
2394                                 return 0;
2395                         offset = min(offset, bottom_pos - height_);
2396                         break;
2397                 }
2398                 if (bottom_pos > ymax)
2399                         break;
2400                 tm.newParMetricsDown();
2401         }
2402         d->anchor_ypos_ -= offset;
2403         return -offset;
2404 }
2405
2406
2407 int BufferView::scrollUp(int offset)
2408 {
2409         Text * text = &buffer_.text();
2410         TextMetrics & tm = d->text_metrics_[text];
2411         int ymin = - offset;
2412         while (true) {
2413                 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2414                 int top_pos = first.second->position() - first.second->ascent();
2415                 if (first.first == 0) {
2416                         if (top_pos >= 0)
2417                                 return 0;
2418                         offset = min(offset, - top_pos);
2419                         break;
2420                 }
2421                 if (top_pos < ymin)
2422                         break;
2423                 tm.newParMetricsUp();
2424         }
2425         d->anchor_ypos_ += offset;
2426         return offset;
2427 }
2428
2429
2430 bool BufferView::setCursorFromRow(int row)
2431 {
2432         TexRow::TextEntry start, end;
2433         tie(start,end) = buffer_.texrow().getEntriesFromRow(row);
2434         LYXERR(Debug::LATEX,
2435                "setCursorFromRow: for row " << row << ", TexRow has found "
2436                "start (id=" << start.id << ",pos=" << start.pos << "), "
2437                "end (id=" << end.id << ",pos=" << end.pos << ")");
2438         return setCursorFromEntries(start, end);
2439 }
2440
2441
2442 bool BufferView::setCursorFromEntries(TexRow::TextEntry start,
2443                                       TexRow::TextEntry end)
2444 {
2445         DocIterator dit_start, dit_end;
2446         tie(dit_start,dit_end) =
2447                 TexRow::getDocIteratorsFromEntries(start, end, buffer_);
2448         if (!dit_start)
2449                 return false;
2450         // Setting selection start
2451         d->cursor_.clearSelection();
2452         setCursor(dit_start);
2453         // Setting selection end
2454         if (dit_end) {
2455                 d->cursor_.resetAnchor();
2456                 setCursorSelectionTo(dit_end);
2457         }
2458         return true;
2459 }
2460
2461
2462 bool BufferView::setCursorFromInset(Inset const * inset)
2463 {
2464         // are we already there?
2465         if (cursor().nextInset() == inset)
2466                 return true;
2467
2468         // Inset is not at cursor position. Find it in the document.
2469         Cursor cur(*this);
2470         cur.reset();
2471         while (cur && cur.nextInset() != inset)
2472                 cur.forwardInset();
2473
2474         if (cur) {
2475                 setCursor(cur);
2476                 return true;
2477         }
2478         return false;
2479 }
2480
2481
2482 void BufferView::gotoLabel(docstring const & label)
2483 {
2484         for (Buffer const * buf : buffer().allRelatives()) {
2485                 // find label
2486                 for (TocItem const & item : *buf->tocBackend().toc("label")) {
2487                         if (label == item.str()) {
2488                                 lyx::dispatch(item.action());
2489                                 return;
2490                         }
2491                 }
2492         }
2493 }
2494
2495
2496 TextMetrics const & BufferView::textMetrics(Text const * t) const
2497 {
2498         return const_cast<BufferView *>(this)->textMetrics(t);
2499 }
2500
2501
2502 TextMetrics & BufferView::textMetrics(Text const * t)
2503 {
2504         LBUFERR(t);
2505         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
2506         if (tmc_it == d->text_metrics_.end()) {
2507                 tmc_it = d->text_metrics_.insert(
2508                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2509         }
2510         return tmc_it->second;
2511 }
2512
2513
2514 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2515                 pit_type pit) const
2516 {
2517         return textMetrics(t).parMetrics(pit);
2518 }
2519
2520
2521 int BufferView::workHeight() const
2522 {
2523         return height_;
2524 }
2525
2526
2527 void BufferView::setCursor(DocIterator const & dit)
2528 {
2529         d->cursor_.reset();
2530         size_t const n = dit.depth();
2531         for (size_t i = 0; i < n; ++i)
2532                 dit[i].inset().edit(d->cursor_, true);
2533
2534         d->cursor_.setCursor(dit);
2535         d->cursor_.selection(false);
2536         d->cursor_.setCurrentFont();
2537         // FIXME
2538         // It seems on general grounds as if this is probably needed, but
2539         // it is not yet clear.
2540         // See bug #7394 and r38388.
2541         // d->cursor.resetAnchor();
2542 }
2543
2544
2545 void BufferView::setCursorSelectionTo(DocIterator const & dit)
2546 {
2547         size_t const n = dit.depth();
2548         for (size_t i = 0; i < n; ++i)
2549                 dit[i].inset().edit(d->cursor_, true);
2550
2551         d->cursor_.selection(true);
2552         d->cursor_.setCursorSelectionTo(dit);
2553         d->cursor_.setCurrentFont();
2554 }
2555
2556
2557 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2558 {
2559         // Would be wrong to delete anything if we have a selection.
2560         if (cur.selection())
2561                 return false;
2562
2563         bool need_anchor_change = false;
2564         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2565                 need_anchor_change);
2566
2567         if (need_anchor_change)
2568                 cur.resetAnchor();
2569
2570         if (!changed)
2571                 return false;
2572
2573         d->cursor_ = cur;
2574
2575         // we would rather not do this here, but it needs to be done before
2576         // the changed() signal is sent.
2577         buffer_.updateBuffer();
2578
2579         buffer_.changed(true);
2580         return true;
2581 }
2582
2583
2584 bool BufferView::mouseSetCursor(Cursor & cur, bool const select)
2585 {
2586         LASSERT(&cur.bv() == this, return false);
2587
2588         if (!select)
2589                 // this event will clear selection so we save selection for
2590                 // persistent selection
2591                 cap::saveSelection(cursor());
2592
2593         d->cursor_.macroModeClose();
2594         // If a macro has been finalized, the cursor might have been broken
2595         cur.fixIfBroken();
2596
2597         // Has the cursor just left the inset?
2598         bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2599         if (leftinset)
2600                 d->cursor_.fixIfBroken();
2601
2602         // do the dEPM magic if needed
2603         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2604         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2605         // the leftinset bool would not be necessary (badcursor instead).
2606         bool update = leftinset;
2607
2608         if (select) {
2609                 d->cursor_.setSelection();
2610                 d->cursor_.setCursorSelectionTo(cur);
2611         } else {
2612                 if (d->cursor_.inTexted())
2613                         update |= checkDepm(cur, d->cursor_);
2614                 d->cursor_.resetAnchor();
2615                 d->cursor_.setCursor(cur);
2616                 d->cursor_.clearSelection();
2617         }
2618         d->cursor_.boundary(cur.boundary());
2619         d->cursor_.finishUndo();
2620         d->cursor_.setCurrentFont();
2621         if (update)
2622                 cur.forceBufferUpdate();
2623         return update;
2624 }
2625
2626
2627 void BufferView::putSelectionAt(DocIterator const & cur,
2628                                 int length, bool backwards)
2629 {
2630         d->cursor_.clearSelection();
2631
2632         setCursor(cur);
2633
2634         if (length) {
2635                 if (backwards) {
2636                         d->cursor_.pos() += length;
2637                         d->cursor_.setSelection(d->cursor_, -length);
2638                 } else
2639                         d->cursor_.setSelection(d->cursor_, length);
2640         }
2641 }
2642
2643
2644 bool BufferView::selectIfEmpty(DocIterator & cur)
2645 {
2646         if ((cur.inTexted() && !cur.paragraph().empty())
2647             || (cur.inMathed() && !cur.cell().empty()))
2648                 return false;
2649
2650         pit_type const beg_pit = cur.pit();
2651         if (beg_pit > 0) {
2652                 // The paragraph associated to this item isn't
2653                 // the first one, so it can be selected
2654                 cur.backwardPos();
2655         } else {
2656                 // We have to resort to select the space between the
2657                 // end of this item and the begin of the next one
2658                 cur.forwardPos();
2659         }
2660         if (cur.empty()) {
2661                 // If it is the only item in the document,
2662                 // nothing can be selected
2663                 return false;
2664         }
2665         pit_type const end_pit = cur.pit();
2666         pos_type const end_pos = cur.pos();
2667         d->cursor_.clearSelection();
2668         d->cursor_.reset();
2669         d->cursor_.setCursor(cur);
2670         d->cursor_.pit() = beg_pit;
2671         d->cursor_.pos() = 0;
2672         d->cursor_.selection(false);
2673         d->cursor_.resetAnchor();
2674         d->cursor_.pit() = end_pit;
2675         d->cursor_.pos() = end_pos;
2676         d->cursor_.setSelection();
2677         return true;
2678 }
2679
2680
2681 Cursor & BufferView::cursor()
2682 {
2683         return d->cursor_;
2684 }
2685
2686
2687 Cursor const & BufferView::cursor() const
2688 {
2689         return d->cursor_;
2690 }
2691
2692
2693 bool BufferView::singleParUpdate()
2694 {
2695         Text & buftext = buffer_.text();
2696         pit_type const bottom_pit = d->cursor_.bottom().pit();
2697         TextMetrics & tm = textMetrics(&buftext);
2698         int old_height = tm.parMetrics(bottom_pit).height();
2699
2700         // make sure inline completion pointer is ok
2701         if (d->inlineCompletionPos_.fixIfBroken())
2702                 d->inlineCompletionPos_ = DocIterator();
2703
2704         // In Single Paragraph mode, rebreak only
2705         // the (main text, not inset!) paragraph containing the cursor.
2706         // (if this paragraph contains insets etc., rebreaking will
2707         // recursively descend)
2708         tm.redoParagraph(bottom_pit);
2709         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2710         if (pm.height() != old_height)
2711                 // Paragraph height has changed so we cannot proceed to
2712                 // the singlePar optimisation.
2713                 return false;
2714
2715         tm.updatePosCache(bottom_pit);
2716
2717         LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2718                 << " y2: " << pm.position() + pm.descent()
2719                 << " pit: " << bottom_pit
2720                 << " singlepar: 1");
2721         return true;
2722 }
2723
2724
2725 void BufferView::updateMetrics()
2726 {
2727         updateMetrics(d->update_flags_);
2728         d->update_strategy_ = FullScreenUpdate;
2729 }
2730
2731
2732 void BufferView::updateMetrics(Update::flags & update_flags)
2733 {
2734         if (height_ == 0 || width_ == 0)
2735                 return;
2736
2737         Text & buftext = buffer_.text();
2738         pit_type const npit = int(buftext.paragraphs().size());
2739
2740         // Clear out the position cache in case of full screen redraw,
2741         d->coord_cache_.clear();
2742
2743         // Clear out paragraph metrics to avoid having invalid metrics
2744         // in the cache from paragraphs not relayouted below
2745         // The complete text metrics will be redone.
2746         d->text_metrics_.clear();
2747
2748         TextMetrics & tm = textMetrics(&buftext);
2749
2750         // make sure inline completion pointer is ok
2751         if (d->inlineCompletionPos_.fixIfBroken())
2752                 d->inlineCompletionPos_ = DocIterator();
2753
2754         if (d->anchor_pit_ >= npit)
2755                 // The anchor pit must have been deleted...
2756                 d->anchor_pit_ = npit - 1;
2757
2758         // Rebreak anchor paragraph.
2759         tm.redoParagraph(d->anchor_pit_);
2760         ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2761
2762         // position anchor
2763         if (d->anchor_pit_ == 0) {
2764                 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2765
2766                 // Complete buffer visible? Then it's easy.
2767                 if (scrollRange == 0)
2768                         d->anchor_ypos_ = anchor_pm.ascent();
2769                 else {
2770                         // avoid empty space above the first row
2771                         d->anchor_ypos_ = min(d->anchor_ypos_, anchor_pm.ascent());
2772                 }
2773         }
2774         anchor_pm.setPosition(d->anchor_ypos_);
2775         tm.updatePosCache(d->anchor_pit_);
2776
2777         LYXERR(Debug::PAINTING, "metrics: "
2778                 << " anchor pit = " << d->anchor_pit_
2779                 << " anchor ypos = " << d->anchor_ypos_);
2780
2781         // Redo paragraphs above anchor if necessary.
2782         int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2783         // We are now just above the anchor paragraph.
2784         pit_type pit1 = d->anchor_pit_ - 1;
2785         for (; pit1 >= 0 && y1 >= 0; --pit1) {
2786                 tm.redoParagraph(pit1);
2787                 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2788                 y1 -= pm.descent();
2789                 // Save the paragraph position in the cache.
2790                 pm.setPosition(y1);
2791                 tm.updatePosCache(pit1);
2792                 y1 -= pm.ascent();
2793         }
2794
2795         // Redo paragraphs below the anchor if necessary.
2796         int y2 = d->anchor_ypos_ + anchor_pm.descent();
2797         // We are now just below the anchor paragraph.
2798         pit_type pit2 = d->anchor_pit_ + 1;
2799         for (; pit2 < npit && y2 <= height_; ++pit2) {
2800                 tm.redoParagraph(pit2);
2801                 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2802                 y2 += pm.ascent();
2803                 // Save the paragraph position in the cache.
2804                 pm.setPosition(y2);
2805                 tm.updatePosCache(pit2);
2806                 y2 += pm.descent();
2807         }
2808
2809         LYXERR(Debug::PAINTING, "Metrics: "
2810                 << " anchor pit = " << d->anchor_pit_
2811                 << " anchor ypos = " << d->anchor_ypos_
2812                 << " y1 = " << y1
2813                 << " y2 = " << y2
2814                 << " pit1 = " << pit1
2815                 << " pit2 = " << pit2);
2816
2817         // metrics is done, full drawing is necessary now
2818         update_flags = (update_flags & ~Update::Force) | Update::ForceDraw;
2819
2820         // Now update the positions of insets in the cache.
2821         updatePosCache();
2822
2823         if (lyxerr.debugging(Debug::WORKAREA)) {
2824                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2825                 d->coord_cache_.dump();
2826         }
2827 }
2828
2829
2830 void BufferView::updatePosCache()
2831 {
2832         // this is the "nodraw" drawing stage: only set the positions of the
2833         // insets in metrics cache.
2834         frontend::NullPainter np;
2835         draw(np, false);
2836 }
2837
2838
2839 void BufferView::insertLyXFile(FileName const & fname)
2840 {
2841         LASSERT(d->cursor_.inTexted(), return);
2842
2843         // Get absolute path of file and add ".lyx"
2844         // to the filename if necessary
2845         FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2846
2847         docstring const disp_fn = makeDisplayPath(filename.absFileName());
2848         // emit message signal.
2849         message(bformat(_("Inserting document %1$s..."), disp_fn));
2850
2851         docstring res;
2852         Buffer buf(filename.absFileName(), false);
2853         if (buf.loadLyXFile() == Buffer::ReadSuccess) {
2854                 ErrorList & el = buffer_.errorList("Parse");
2855                 // Copy the inserted document error list into the current buffer one.
2856                 el = buf.errorList("Parse");
2857                 buffer_.undo().recordUndo(d->cursor_);
2858                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2859                                              buf.params().documentClassPtr(), el);
2860                 res = _("Document %1$s inserted.");
2861         } else {
2862                 res = _("Could not insert document %1$s");
2863         }
2864
2865         buffer_.changed(true);
2866         // emit message signal.
2867         message(bformat(res, disp_fn));
2868 }
2869
2870
2871 Point BufferView::coordOffset(DocIterator const & dit) const
2872 {
2873         int x = 0;
2874         int y = 0;
2875         int lastw = 0;
2876
2877         // Addup contribution of nested insets, from inside to outside,
2878         // keeping the outer paragraph for a special handling below
2879         for (size_t i = dit.depth() - 1; i >= 1; --i) {
2880                 CursorSlice const & sl = dit[i];
2881                 int xx = 0;
2882                 int yy = 0;
2883
2884                 // get relative position inside sl.inset()
2885                 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2886
2887                 // Make relative position inside of the edited inset relative to sl.inset()
2888                 x += xx;
2889                 y += yy;
2890
2891                 // In case of an RTL inset, the edited inset will be positioned to the left
2892                 // of xx:yy
2893                 if (sl.text()) {
2894                         bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2895                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2896                         if (rtl)
2897                                 x -= lastw;
2898                 }
2899
2900                 // remember width for the case that sl.inset() is positioned in an RTL inset
2901                 lastw = sl.inset().dimension(*this).wid;
2902
2903                 //lyxerr << "Cursor::getPos, i: "
2904                 // << i << " x: " << xx << " y: " << y << endl;
2905         }
2906
2907         // Add contribution of initial rows of outermost paragraph
2908         CursorSlice const & sl = dit[0];
2909         TextMetrics const & tm = textMetrics(sl.text());
2910         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2911
2912         LBUFERR(!pm.rows().empty());
2913         y -= pm.rows()[0].ascent();
2914 #if 1
2915         // FIXME: document this mess
2916         size_t rend;
2917         if (sl.pos() > 0 && dit.depth() == 1) {
2918                 int pos = sl.pos();
2919                 if (pos && dit.boundary())
2920                         --pos;
2921 //              lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2922                 rend = pm.pos2row(pos);
2923         } else
2924                 rend = pm.pos2row(sl.pos());
2925 #else
2926         size_t rend = pm.pos2row(sl.pos());
2927 #endif
2928         for (size_t rit = 0; rit != rend; ++rit)
2929                 y += pm.rows()[rit].height();
2930         y += pm.rows()[rend].ascent();
2931
2932         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2933
2934         // Make relative position from the nested inset now bufferview absolute.
2935         int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2936         x += xx;
2937
2938         // In the RTL case place the nested inset at the left of the cursor in
2939         // the outer paragraph
2940         bool boundary_1 = dit.boundary() && 1 == dit.depth();
2941         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2942         if (rtl)
2943                 x -= lastw;
2944
2945         return Point(x, y);
2946 }
2947
2948
2949 Point BufferView::getPos(DocIterator const & dit) const
2950 {
2951         if (!paragraphVisible(dit))
2952                 return Point(-1, -1);
2953
2954         CursorSlice const & bot = dit.bottom();
2955         TextMetrics const & tm = textMetrics(bot.text());
2956
2957         // offset from outer paragraph
2958         Point p = coordOffset(dit);
2959         p.y_ += tm.parMetrics(bot.pit()).position();
2960         return p;
2961 }
2962
2963
2964 bool BufferView::paragraphVisible(DocIterator const & dit) const
2965 {
2966         CursorSlice const & bot = dit.bottom();
2967         TextMetrics const & tm = textMetrics(bot.text());
2968
2969         return tm.contains(bot.pit());
2970 }
2971
2972
2973 void BufferView::caretPosAndHeight(Point & p, int & h) const
2974 {
2975         Cursor const & cur = cursor();
2976         Font const font = cur.real_current_font;
2977         frontend::FontMetrics const & fm = theFontMetrics(font);
2978         int const asc = fm.maxAscent();
2979         int const des = fm.maxDescent();
2980         h = asc + des;
2981         p = getPos(cur);
2982         p.y_ -= asc;
2983 }
2984
2985
2986 bool BufferView::cursorInView(Point const & p, int h) const
2987 {
2988         Cursor const & cur = cursor();
2989         // does the cursor touch the screen ?
2990         if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2991                 return false;
2992         return true;
2993 }
2994
2995
2996 int BufferView::horizScrollOffset() const
2997 {
2998         return d->horiz_scroll_offset_;
2999 }
3000
3001
3002 int BufferView::horizScrollOffset(Text const * text,
3003                                   pit_type pit, pos_type pos) const
3004 {
3005         // Is this a row that is currently scrolled?
3006         if (!d->current_row_slice_.empty()
3007             && &text->inset() == d->current_row_slice_.inset().asInsetText()
3008             && pit ==  d->current_row_slice_.pit()
3009             && pos ==  d->current_row_slice_.pos())
3010                 return d->horiz_scroll_offset_;
3011         return 0;
3012 }
3013
3014
3015 bool BufferView::hadHorizScrollOffset(Text const * text,
3016                                       pit_type pit, pos_type pos) const
3017 {
3018         return !d->last_row_slice_.empty()
3019                && &text->inset() == d->last_row_slice_.inset().asInsetText()
3020                && pit ==  d->last_row_slice_.pit()
3021                && pos ==  d->last_row_slice_.pos();
3022 }
3023
3024
3025 void BufferView::setCurrentRowSlice(CursorSlice const & rowSlice)
3026 {
3027         // nothing to do if the cursor was already on this row
3028         if (d->current_row_slice_ == rowSlice) {
3029                 d->last_row_slice_ = CursorSlice();
3030                 return;
3031         }
3032
3033         // if the (previous) current row was scrolled, we have to
3034         // remember it in order to repaint it next time.
3035         if (d->horiz_scroll_offset_ != 0)
3036                 d->last_row_slice_ = d->current_row_slice_;
3037         else
3038                 d->last_row_slice_ = CursorSlice();
3039
3040         // Since we changed row, the scroll offset is not valid anymore
3041         d->horiz_scroll_offset_ = 0;
3042         d->current_row_slice_ = rowSlice;
3043 }
3044
3045
3046 namespace {
3047
3048 bool sliceInRow(CursorSlice const & cs, Text const * text, Row const & row)
3049 {
3050         /* The normal case is the last line. The previous line takes care
3051          * of empty rows (e.g. empty paragraphs). Cursor boundary issues
3052          * are taken care of when setting caret_slice_ in
3053          * BufferView::draw.
3054          */
3055         return !cs.empty() && cs.text() == text && cs.pit() == row.pit()
3056                && ((row.pos() == row.endpos() && row.pos() == cs.pos())
3057                   || (row.pos() <= cs.pos() && cs.pos() < row.endpos()));
3058 }
3059
3060 }
3061
3062
3063 bool BufferView::needRepaint(Text const * text, Row const & row) const
3064 {
3065         return d->repaint_caret_row_ && sliceInRow(d->caret_slice_, text, row);
3066 }
3067
3068
3069 void BufferView::checkCursorScrollOffset()
3070 {
3071         CursorSlice rowSlice = d->cursor_.bottom();
3072         TextMetrics const & tm = textMetrics(rowSlice.text());
3073
3074         // Stop if metrics have not been computed yet, since it means
3075         // that there is nothing to do.
3076         if (!tm.contains(rowSlice.pit()))
3077                 return;
3078         ParagraphMetrics const & pm = tm.parMetrics(rowSlice.pit());
3079         Row const & row = pm.getRow(rowSlice.pos(),
3080                                     d->cursor_.boundary() && rowSlice == d->cursor_.top());
3081         rowSlice.pos() = row.pos();
3082
3083         // Set the row on which the cursor lives.
3084         setCurrentRowSlice(rowSlice);
3085
3086         // Current x position of the cursor in pixels
3087         int cur_x = getPos(d->cursor_).x_;
3088
3089         // Horizontal scroll offset of the cursor row in pixels
3090         int offset = d->horiz_scroll_offset_;
3091         int const MARGIN = 2 * theFontMetrics(d->cursor_.real_current_font).em()
3092                            + row.right_margin;
3093         if (row.right_x() <= workWidth() - row.right_margin) {
3094                 // Row is narrower than the work area, no offset needed.
3095                 offset = 0;
3096         } else {
3097                 if (cur_x - offset < MARGIN) {
3098                         // cursor would be too far right
3099                         offset = cur_x - MARGIN;
3100                 } else if (cur_x - offset > workWidth() - MARGIN) {
3101                         // cursor would be too far left
3102                         offset = cur_x - workWidth() + MARGIN;
3103                 }
3104                 // Correct the offset to make sure that we do not scroll too much
3105                 if (offset < 0)
3106                         offset = 0;
3107                 if (row.right_x() - offset < workWidth() - row.right_margin)
3108                         offset = row.right_x() - workWidth() + row.right_margin;
3109         }
3110
3111         //lyxerr << "cur_x=" << cur_x << ", offset=" << offset << ", row.wid=" << row.width() << ", margin=" << MARGIN << endl;
3112
3113         if (offset != d->horiz_scroll_offset_)
3114                 LYXERR(Debug::PAINTING, "Horiz. scroll offset changed from "
3115                        << d->horiz_scroll_offset_ << " to " << offset);
3116
3117         if (d->update_strategy_ == NoScreenUpdate
3118             && (offset != d->horiz_scroll_offset_
3119                 || !d->last_row_slice_.empty())) {
3120                 // FIXME: if one uses SingleParUpdate, then home/end
3121                 // will not work on long rows. Why?
3122                 d->update_strategy_ = FullScreenUpdate;
3123         }
3124
3125         d->horiz_scroll_offset_ = offset;
3126 }
3127
3128
3129 void BufferView::draw(frontend::Painter & pain, bool paint_caret)
3130 {
3131         if (height_ == 0 || width_ == 0)
3132                 return;
3133         LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t--- START NODRAW ---"
3134                                  : "\t\t*** START DRAWING ***"));
3135         Text & text = buffer_.text();
3136         TextMetrics const & tm = d->text_metrics_[&text];
3137         int const y = tm.first().second->position();
3138         PainterInfo pi(this, pain);
3139
3140         /**  A repaint of the previous caret row is needed if there is
3141          *  caret painted on screen and either
3142          *   1/ a new caret has to be painted at a place different from
3143          *      the existing one;
3144          *   2/ there is no need for a caret anymore.
3145          */
3146         d->repaint_caret_row_ = !d->caret_slice_.empty() &&
3147                 ((paint_caret && d->cursor_.top() != d->caret_slice_)
3148                  || ! paint_caret);
3149
3150         // Check whether the row where the cursor lives needs to be scrolled.
3151         // Update the drawing strategy if needed.
3152         checkCursorScrollOffset();
3153
3154         switch (d->update_strategy_) {
3155
3156         case NoScreenUpdate:
3157                 // no screen painting is actually needed. In nodraw stage
3158                 // however, the different coordinates of insets and paragraphs
3159                 // needs to be updated.
3160                 LYXERR(Debug::PAINTING, "Strategy: NoScreenUpdate");
3161                 pi.full_repaint = false;
3162                 if (pain.isNull()) {
3163                         pi.full_repaint = true;
3164                         tm.draw(pi, 0, y);
3165                 } else if (d->repaint_caret_row_) {
3166                         pi.full_repaint = false;
3167                         tm.draw(pi, 0, y);
3168                 }
3169                 break;
3170
3171         case SingleParUpdate:
3172                 pi.full_repaint = false;
3173                 LYXERR(Debug::PAINTING, "Strategy: SingleParUpdate");
3174                 // In general, only the current row of the outermost paragraph
3175                 // will be redrawn. Particular cases where selection spans
3176                 // multiple paragraph are correctly detected in TextMetrics.
3177                 tm.draw(pi, 0, y);
3178                 break;
3179
3180         case DecorationUpdate:
3181                 // FIXME: We should also distinguish DecorationUpdate to avoid text
3182                 // drawing if possible. This is not possible to do easily right now
3183                 // because of the single backing pixmap.
3184
3185         case FullScreenUpdate:
3186
3187                 LYXERR(Debug::PAINTING,
3188                        ((d->update_strategy_ == FullScreenUpdate)
3189                         ? "Strategy: FullScreenUpdate"
3190                         : "Strategy: DecorationUpdate"));
3191
3192                 // The whole screen, including insets, will be refreshed.
3193                 pi.full_repaint = true;
3194
3195                 // Clear background.
3196                 pain.fillRectangle(0, 0, width_, height_,
3197                         pi.backgroundColor(&buffer_.inset()));
3198
3199                 // Draw everything.
3200                 tm.draw(pi, 0, y);
3201
3202                 // and possibly grey out below
3203                 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3204                 int const y2 = lastpm.second->position() + lastpm.second->descent();
3205
3206                 if (y2 < height_) {
3207                         Color color = buffer().isInternal()
3208                                 ? Color_background : Color_bottomarea;
3209                         pain.fillRectangle(0, y2, width_, height_ - y2, color);
3210                 }
3211                 break;
3212         }
3213         LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t --- END NODRAW ---"
3214                                 : "\t\t *** END DRAWING ***"));
3215
3216         // The scrollbar needs an update.
3217         updateScrollbar();
3218
3219         // Normalize anchor for next time
3220         pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
3221         pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3222         for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
3223                 ParagraphMetrics const & pm = tm.parMetrics(pit);
3224                 if (pm.position() + pm.descent() > 0) {
3225                         if (d->anchor_pit_ != pit
3226                             || d->anchor_ypos_ != pm.position())
3227                                 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
3228                                        << "  anchor ypos = " << d->anchor_ypos_);
3229                         d->anchor_pit_ = pit;
3230                         d->anchor_ypos_ = pm.position();
3231                         break;
3232                 }
3233         }
3234         if (!pain.isNull()) {
3235                 // reset the update flags, everything has been done
3236                 d->update_flags_ = Update::None;
3237         }
3238
3239         // Remember what has just been done for the next draw() step
3240         if (paint_caret) {
3241                 d->caret_slice_ = d->cursor_.top();
3242                 if (d->caret_slice_.pos() > 0
3243                     && (d->cursor_.boundary()
3244                         || d->caret_slice_.pos() == d->caret_slice_.lastpos()))
3245                         --d->caret_slice_.pos();
3246         } else
3247                 d->caret_slice_ = CursorSlice();
3248 }
3249
3250
3251 void BufferView::message(docstring const & msg)
3252 {
3253         if (d->gui_)
3254                 d->gui_->message(msg);
3255 }
3256
3257
3258 void BufferView::showDialog(string const & name)
3259 {
3260         if (d->gui_)
3261                 d->gui_->showDialog(name, string());
3262 }
3263
3264
3265 void BufferView::showDialog(string const & name,
3266         string const & data, Inset * inset)
3267 {
3268         if (d->gui_)
3269                 d->gui_->showDialog(name, data, inset);
3270 }
3271
3272
3273 void BufferView::updateDialog(string const & name, string const & data)
3274 {
3275         if (d->gui_)
3276                 d->gui_->updateDialog(name, data);
3277 }
3278
3279
3280 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
3281 {
3282         d->gui_ = gui;
3283 }
3284
3285
3286 // FIXME: Move this out of BufferView again
3287 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
3288 {
3289         if (!fname.isReadableFile()) {
3290                 docstring const error = from_ascii(strerror(errno));
3291                 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3292                 docstring const text =
3293                   bformat(_("Could not read the specified document\n"
3294                             "%1$s\ndue to the error: %2$s"), file, error);
3295                 Alert::error(_("Could not read file"), text);
3296                 return docstring();
3297         }
3298
3299         if (!fname.isReadableFile()) {
3300                 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3301                 docstring const text =
3302                   bformat(_("%1$s\n is not readable."), file);
3303                 Alert::error(_("Could not open file"), text);
3304                 return docstring();
3305         }
3306
3307         // FIXME UNICODE: We don't know the encoding of the file
3308         docstring file_content = fname.fileContents("UTF-8");
3309         if (file_content.empty()) {
3310                 Alert::error(_("Reading not UTF-8 encoded file"),
3311                              _("The file is not UTF-8 encoded.\n"
3312                                "It will be read as local 8Bit-encoded.\n"
3313                                "If this does not give the correct result\n"
3314                                "then please change the encoding of the file\n"
3315                                "to UTF-8 with a program other than LyX.\n"));
3316                 file_content = fname.fileContents("local8bit");
3317         }
3318
3319         return normalize_c(file_content);
3320 }
3321
3322
3323 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
3324 {
3325         docstring const tmpstr = contentsOfPlaintextFile(f);
3326
3327         if (tmpstr.empty())
3328                 return;
3329
3330         Cursor & cur = cursor();
3331         cap::replaceSelection(cur);
3332         buffer_.undo().recordUndo(cur);
3333         if (asParagraph)
3334                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3335         else
3336                 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3337
3338         buffer_.changed(true);
3339 }
3340
3341
3342 docstring const & BufferView::inlineCompletion() const
3343 {
3344         return d->inlineCompletion_;
3345 }
3346
3347
3348 size_t const & BufferView::inlineCompletionUniqueChars() const
3349 {
3350         return d->inlineCompletionUniqueChars_;
3351 }
3352
3353
3354 DocIterator const & BufferView::inlineCompletionPos() const
3355 {
3356         return d->inlineCompletionPos_;
3357 }
3358
3359
3360 void BufferView::resetInlineCompletionPos()
3361 {
3362         d->inlineCompletionPos_ = DocIterator();
3363 }
3364
3365
3366 bool samePar(DocIterator const & a, DocIterator const & b)
3367 {
3368         if (a.empty() && b.empty())
3369                 return true;
3370         if (a.empty() || b.empty())
3371                 return false;
3372         if (a.depth() != b.depth())
3373                 return false;
3374         return &a.innerParagraph() == &b.innerParagraph();
3375 }
3376
3377
3378 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3379         docstring const & completion, size_t uniqueChars)
3380 {
3381         uniqueChars = min(completion.size(), uniqueChars);
3382         bool changed = d->inlineCompletion_ != completion
3383                 || d->inlineCompletionUniqueChars_ != uniqueChars;
3384         bool singlePar = true;
3385         d->inlineCompletion_ = completion;
3386         d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3387
3388         //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3389
3390         // at new position?
3391         DocIterator const & old = d->inlineCompletionPos_;
3392         if (old != pos) {
3393                 //lyxerr << "inlineCompletionPos changed" << std::endl;
3394                 // old or pos are in another paragraph?
3395                 if ((!samePar(cur, pos) && !pos.empty())
3396                     || (!samePar(cur, old) && !old.empty())) {
3397                         singlePar = false;
3398                         //lyxerr << "different paragraph" << std::endl;
3399                 }
3400                 d->inlineCompletionPos_ = pos;
3401         }
3402
3403         // set update flags
3404         if (changed) {
3405                 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3406                         cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3407                 else
3408                         cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3409         }
3410 }
3411
3412
3413 bool BufferView::clickableInset() const
3414 {
3415         return d->clickable_inset_;
3416 }
3417
3418 } // namespace lyx