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