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