]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
Style
[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         pit_type const old_pit = d->anchor_pit_;
1068         d->anchor_pit_ = bot_pit;
1069
1070         CursorSlice const & cs = dit.innerTextSlice();
1071         ParagraphMetrics const & inner_pm =
1072                 textMetrics(cs.text()).parMetrics(cs.pit());
1073         Dimension const & row_dim =
1074                 inner_pm.getRow(cs.pos(), dit.boundary()).dim();
1075
1076         int const old_ypos = d->anchor_ypos_;
1077         d->anchor_ypos_ = - offset + row_dim.ascent();
1078         if (how == SCROLL_CENTER)
1079                 d->anchor_ypos_ += height_/2 - row_dim.height() / 2;
1080         return d->anchor_ypos_ != old_ypos || d->anchor_pit_ != old_pit;
1081 }
1082
1083
1084 void BufferView::makeDocumentClass()
1085 {
1086         DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1087         buffer_.params().makeDocumentClass(buffer_.isClone(), buffer_.isInternal());
1088         updateDocumentClass(olddc);
1089 }
1090
1091
1092 void BufferView::updateDocumentClass(DocumentClassConstPtr olddc)
1093 {
1094         StableDocIterator backcur(d->cursor_);
1095         ErrorList & el = buffer_.errorList("Class Switch");
1096         cap::switchBetweenClasses(
1097                         olddc, buffer_.params().documentClassPtr(),
1098                         static_cast<InsetText &>(buffer_.inset()), el);
1099
1100         setCursor(backcur.asDocIterator(&buffer_));
1101
1102         buffer_.errors("Class Switch");
1103 }
1104
1105
1106 /** Return the change status at cursor position, taking into account the
1107  * status at each level of the document iterator (a table in a deleted
1108  * footnote is deleted).
1109  * When \param outer is true, the top slice is not looked at.
1110  */
1111 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
1112 {
1113         size_t const depth = dit.depth() - (outer ? 1 : 0);
1114
1115         for (size_t i = 0 ; i < depth ; ++i) {
1116                 CursorSlice const & slice = dit[i];
1117                 if (!slice.inset().inMathed()
1118                     && slice.pos() < slice.paragraph().size()) {
1119                         Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
1120                         if (ch != Change::UNCHANGED)
1121                                 return ch;
1122                 }
1123         }
1124         return Change::UNCHANGED;
1125 }
1126
1127
1128 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1129 {
1130         FuncCode const act = cmd.action();
1131
1132         // Can we use a readonly buffer?
1133         if (buffer_.isReadonly()
1134             && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1135             && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1136                 if (buffer_.hasReadonlyFlag())
1137                         flag.message(from_utf8(N_("Document is read-only")));
1138                 else
1139                         flag.message(from_utf8(N_("Document has been modified externally")));
1140                 flag.setEnabled(false);
1141                 return true;
1142         }
1143
1144         // Are we in a DELETED change-tracking region?
1145         if (lookupChangeType(d->cursor_, true) == Change::DELETED
1146             && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1147             && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1148                 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1149                 flag.setEnabled(false);
1150                 return true;
1151         }
1152
1153         Cursor & cur = d->cursor_;
1154
1155         if (cur.getStatus(cmd, flag))
1156                 return true;
1157
1158         switch (act) {
1159
1160         // FIXME: This is a bit problematic because we don't check if this is
1161         // a document BufferView or not for these LFUNs. We probably have to
1162         // dispatch both to currentBufferView() and, if that fails,
1163         // to documentBufferView(); same as we do now for current Buffer and
1164         // document Buffer. Ideally those LFUN should go to Buffer as they
1165         // operate on the full Buffer and the cursor is only needed either for
1166         // an Undo record or to restore a cursor position. But we don't know
1167         // how to do that inside Buffer of course.
1168         case LFUN_BUFFER_PARAMS_APPLY:
1169         case LFUN_LAYOUT_MODULES_CLEAR:
1170         case LFUN_LAYOUT_MODULE_ADD:
1171         case LFUN_LAYOUT_RELOAD:
1172         case LFUN_TEXTCLASS_APPLY:
1173         case LFUN_TEXTCLASS_LOAD:
1174                 flag.setEnabled(!buffer_.isReadonly());
1175                 break;
1176
1177         case LFUN_UNDO:
1178                 // We do not use the LyXAction flag for readonly because Undo sets the
1179                 // buffer clean/dirty status by itself.
1180                 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1181                 break;
1182         case LFUN_REDO:
1183                 // We do not use the LyXAction flag for readonly because Redo sets the
1184                 // buffer clean/dirty status by itself.
1185                 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1186                 break;
1187         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1188         case LFUN_FILE_INSERT_PLAINTEXT: {
1189                 docstring const & fname = cmd.argument();
1190                 if (!FileName::isAbsolute(to_utf8(fname))) {
1191                         flag.message(_("Absolute filename expected."));
1192                         return false;
1193                 }
1194                 flag.setEnabled(cur.inTexted());
1195                 break;
1196         }
1197         case LFUN_FILE_INSERT:
1198         case LFUN_BOOKMARK_SAVE:
1199                 // FIXME: Actually, these LFUNS should be moved to Text
1200                 flag.setEnabled(cur.inTexted());
1201                 break;
1202
1203         case LFUN_FONT_STATE:
1204         case LFUN_LABEL_INSERT:
1205         case LFUN_INFO_INSERT:
1206         case LFUN_PARAGRAPH_GOTO:
1207         case LFUN_NOTE_NEXT:
1208         case LFUN_REFERENCE_NEXT:
1209         case LFUN_WORD_FIND:
1210         case LFUN_WORD_FIND_FORWARD:
1211         case LFUN_WORD_FIND_BACKWARD:
1212         case LFUN_WORD_REPLACE:
1213         case LFUN_MARK_OFF:
1214         case LFUN_MARK_ON:
1215         case LFUN_MARK_TOGGLE:
1216         case LFUN_SEARCH_STRING_SET:
1217         case LFUN_SCREEN_RECENTER:
1218         case LFUN_SCREEN_SHOW_CURSOR:
1219         case LFUN_BIBTEX_DATABASE_ADD:
1220         case LFUN_BIBTEX_DATABASE_DEL:
1221         case LFUN_BIBTEX_DATABASE_LIST:
1222         case LFUN_STATISTICS:
1223         case LFUN_KEYMAP_OFF:
1224         case LFUN_KEYMAP_PRIMARY:
1225         case LFUN_KEYMAP_SECONDARY:
1226         case LFUN_KEYMAP_TOGGLE:
1227         case LFUN_INSET_SELECT_ALL:
1228                 flag.setEnabled(true);
1229                 break;
1230
1231         case LFUN_GRAPHICS_UNIFY:
1232                 flag.setEnabled(cur.countInsetsInSelection(GRAPHICS_CODE)>1);
1233                 break;
1234
1235         case LFUN_WORD_FINDADV: {
1236                 FindAndReplaceOptions opt;
1237                 istringstream iss(to_utf8(cmd.argument()));
1238                 iss >> opt;
1239                 flag.setEnabled(opt.repl_buf_name.empty()
1240                                 || !buffer_.isReadonly());
1241                 break;
1242         }
1243
1244         case LFUN_LABEL_GOTO:
1245                 flag.setEnabled(!cmd.argument().empty()
1246                     || getInsetByCode<InsetRef>(cur, REF_CODE)
1247                     || getInsetByCode<InsetMathRef>(cur, MATH_REF_CODE));
1248                 break;
1249
1250         case LFUN_CHANGES_MERGE:
1251         case LFUN_CHANGE_NEXT:
1252         case LFUN_CHANGE_PREVIOUS:
1253         case LFUN_ALL_CHANGES_ACCEPT:
1254         case LFUN_ALL_CHANGES_REJECT:
1255                 flag.setEnabled(buffer_.areChangesPresent());
1256                 break;
1257
1258         case LFUN_SCREEN_UP:
1259         case LFUN_SCREEN_DOWN:
1260         case LFUN_SCROLL:
1261         case LFUN_SCREEN_UP_SELECT:
1262         case LFUN_SCREEN_DOWN_SELECT:
1263         case LFUN_INSET_FORALL:
1264                 flag.setEnabled(true);
1265                 break;
1266
1267         case LFUN_LAYOUT_TABULAR:
1268                 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1269                 break;
1270
1271         case LFUN_LAYOUT:
1272                 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1273                 break;
1274
1275         case LFUN_LAYOUT_PARAGRAPH:
1276                 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1277                 break;
1278
1279         case LFUN_BRANCH_ADD_INSERT:
1280                 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1281                 break;
1282
1283         case LFUN_DIALOG_SHOW_NEW_INSET:
1284                 // FIXME: this is wrong, but I do not understand the
1285                 // intent (JMarc)
1286                 if (cur.inset().lyxCode() == CAPTION_CODE)
1287                         return cur.inset().getStatus(cur, cmd, flag);
1288                 // FIXME we should consider passthru paragraphs too.
1289                 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1290                 break;
1291
1292         case LFUN_CITATION_INSERT: {
1293                 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1294                 // FIXME: This could turn in a recursive hell.
1295                 // Shouldn't we use Buffer::getStatus() instead?
1296                 flag.setEnabled(lyx::getStatus(fr).enabled());
1297                 break;
1298         }
1299         case LFUN_INSET_APPLY: {
1300                 string const name = cmd.getArg(0);
1301                 Inset * inset = editedInset(name);
1302                 if (inset) {
1303                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1304                         if (!inset->getStatus(cur, fr, flag)) {
1305                                 // Every inset is supposed to handle this
1306                                 LASSERT(false, break);
1307                         }
1308                 } else {
1309                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1310                         flag = lyx::getStatus(fr);
1311                 }
1312                 break;
1313         }
1314
1315         case LFUN_COPY:
1316                 flag.setEnabled(cur.selection());
1317                 break;
1318
1319         default:
1320                 return false;
1321         }
1322
1323         return true;
1324 }
1325
1326
1327 Inset * BufferView::editedInset(string const & name) const
1328 {
1329         map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1330         return it == d->edited_insets_.end() ? nullptr : it->second;
1331 }
1332
1333
1334 void BufferView::editInset(string const & name, Inset * inset)
1335 {
1336         if (inset)
1337                 d->edited_insets_[name] = inset;
1338         else
1339                 d->edited_insets_.erase(name);
1340 }
1341
1342
1343 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1344 {
1345         LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1346
1347         string const argument = to_utf8(cmd.argument());
1348         Cursor & cur = d->cursor_;
1349         Cursor old = cur;
1350
1351         // Don't dispatch function that does not apply to internal buffers.
1352         if (buffer_.isInternal()
1353             && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1354                 return;
1355
1356         // We'll set this back to false if need be.
1357         bool dispatched = true;
1358         buffer_.undo().beginUndoGroup();
1359
1360         FuncCode const act = cmd.action();
1361         switch (act) {
1362
1363         case LFUN_BUFFER_PARAMS_APPLY: {
1364                 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1365                 cur.recordUndoBufferParams();
1366                 istringstream ss(to_utf8(cmd.argument()));
1367                 Lexer lex;
1368                 lex.setStream(ss);
1369                 int const unknown_tokens = buffer_.readHeader(lex);
1370                 if (unknown_tokens != 0) {
1371                         LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1372                                                 << unknown_tokens << " unknown token"
1373                                                 << (unknown_tokens == 1 ? "" : "s"));
1374                 }
1375                 updateDocumentClass(olddc);
1376
1377                 // We are most certainly here because of a change in the document
1378                 // It is then better to make sure that all dialogs are in sync with
1379                 // current document settings.
1380                 dr.screenUpdate(Update::Force | Update::FitCursor);
1381                 dr.forceBufferUpdate();
1382                 break;
1383         }
1384
1385         case LFUN_LAYOUT_MODULES_CLEAR: {
1386                 // FIXME: this modifies the document in cap::switchBetweenClasses
1387                 //  without calling recordUndo. Fix this before using
1388                 //  recordUndoBufferParams().
1389                 cur.recordUndoFullBuffer();
1390                 buffer_.params().clearLayoutModules();
1391                 makeDocumentClass();
1392                 dr.screenUpdate(Update::Force);
1393                 dr.forceBufferUpdate();
1394                 break;
1395         }
1396
1397         case LFUN_LAYOUT_MODULE_ADD: {
1398                 BufferParams const & params = buffer_.params();
1399                 if (!params.layoutModuleCanBeAdded(argument)) {
1400                         LYXERR0("Module `" << argument <<
1401                                 "' cannot be added due to failed requirements or "
1402                                 "conflicts with installed modules.");
1403                         break;
1404                 }
1405                 // FIXME: this modifies the document in cap::switchBetweenClasses
1406                 //  without calling recordUndo. Fix this before using
1407                 //  recordUndoBufferParams().
1408                 cur.recordUndoFullBuffer();
1409                 buffer_.params().addLayoutModule(argument);
1410                 makeDocumentClass();
1411                 dr.screenUpdate(Update::Force);
1412                 dr.forceBufferUpdate();
1413                 break;
1414         }
1415
1416         case LFUN_TEXTCLASS_APPLY: {
1417                 // since this shortcircuits, the second call is made only if
1418                 // the first fails
1419                 bool const success =
1420                         LayoutFileList::get().load(argument, buffer_.temppath()) ||
1421                         LayoutFileList::get().load(argument, buffer_.filePath());
1422                 if (!success) {
1423                         docstring s = bformat(_("The document class `%1$s' "
1424                                                  "could not be loaded."), from_utf8(argument));
1425                         frontend::Alert::error(_("Could not load class"), s);
1426                         break;
1427                 }
1428
1429                 LayoutFile const * old_layout = buffer_.params().baseClass();
1430                 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1431
1432                 if (old_layout == new_layout)
1433                         // nothing to do
1434                         break;
1435
1436                 // Save the old, possibly modular, layout for use in conversion.
1437                 // FIXME: this modifies the document in cap::switchBetweenClasses
1438                 //  without calling recordUndo. Fix this before using
1439                 //  recordUndoBufferParams().
1440                 cur.recordUndoFullBuffer();
1441                 buffer_.params().setBaseClass(argument, buffer_.layoutPos());
1442                 makeDocumentClass();
1443                 dr.screenUpdate(Update::Force);
1444                 dr.forceBufferUpdate();
1445                 break;
1446         }
1447
1448         case LFUN_TEXTCLASS_LOAD: {
1449                 // since this shortcircuits, the second call is made only if
1450                 // the first fails
1451                 bool const success =
1452                         LayoutFileList::get().load(argument, buffer_.temppath()) ||
1453                         LayoutFileList::get().load(argument, buffer_.filePath());
1454                 if (!success) {
1455                         docstring s = bformat(_("The document class `%1$s' "
1456                                                  "could not be loaded."), from_utf8(argument));
1457                         frontend::Alert::error(_("Could not load class"), s);
1458                 }
1459                 break;
1460         }
1461
1462         case LFUN_LAYOUT_RELOAD: {
1463                 LayoutFileIndex bc = buffer_.params().baseClassID();
1464                 LayoutFileList::get().reset(bc);
1465                 buffer_.params().setBaseClass(bc, buffer_.layoutPos());
1466                 makeDocumentClass();
1467                 dr.screenUpdate(Update::Force);
1468                 dr.forceBufferUpdate();
1469                 break;
1470         }
1471
1472         case LFUN_UNDO: {
1473                 dr.setMessage(_("Undo"));
1474                 cur.clearSelection();
1475                 // We need to find out if the bibliography information
1476                 // has changed. See bug #11055.
1477                 // So these should not be references...
1478                 string const engine = buffer().params().citeEngine();
1479                 CiteEngineType const enginetype = buffer().params().citeEngineType();
1480                 if (!cur.undoAction())
1481                         dr.setMessage(_("No further undo information"));
1482                 else {
1483                         dr.screenUpdate(Update::Force | Update::FitCursor);
1484                         dr.forceBufferUpdate();
1485                         resetInlineCompletionPos();
1486                         if (buffer().params().citeEngine() != engine ||
1487                             buffer().params().citeEngineType() != enginetype)
1488                                 buffer().invalidateCiteLabels();
1489                 }
1490                 break;
1491         }
1492
1493         case LFUN_REDO: {
1494                 dr.setMessage(_("Redo"));
1495                 cur.clearSelection();
1496                 // We need to find out if the bibliography information
1497                 // has changed. See bug #11055.
1498                 // So these should not be references...
1499                 string const engine = buffer().params().citeEngine();
1500                 CiteEngineType const enginetype = buffer().params().citeEngineType();
1501                 if (!cur.redoAction())
1502                         dr.setMessage(_("No further redo information"));
1503                 else {
1504                         dr.screenUpdate(Update::Force | Update::FitCursor);
1505                         dr.forceBufferUpdate();
1506                         resetInlineCompletionPos();
1507                         if (buffer().params().citeEngine() != engine ||
1508                             buffer().params().citeEngineType() != enginetype)
1509                                 buffer().invalidateCiteLabels();
1510                 }
1511                 break;
1512         }
1513
1514         case LFUN_FONT_STATE:
1515                 dr.setMessage(cur.currentState(false));
1516                 break;
1517
1518         case LFUN_BOOKMARK_SAVE:
1519                 dr.screenUpdate(Update::Force);
1520                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1521                 break;
1522
1523         case LFUN_LABEL_GOTO: {
1524                 docstring label = cmd.argument();
1525                 if (label.empty()) {
1526                         InsetRef * inset =
1527                                 getInsetByCode<InsetRef>(cur, REF_CODE);
1528                         if (inset) {
1529                                 label = inset->getParam("reference");
1530                                 // persistent=false: use temp_bookmark
1531                                 saveBookmark(0);
1532                         }
1533                 }
1534                 if (!label.empty()) {
1535                         gotoLabel(label);
1536                         // at the moment, this is redundant, since gotoLabel will
1537                         // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1538                         // to have it here.
1539                         dr.screenUpdate(Update::Force | Update::FitCursor);
1540                 } else {
1541                         InsetMathRef * minset =
1542                                 getInsetByCode<InsetMathRef>(cur, MATH_REF_CODE);
1543                         if (minset)
1544                                 lyx::dispatch(FuncRequest(LFUN_LABEL_GOTO,
1545                                                         minset->getTarget()));
1546                 }
1547                 break;
1548         }
1549
1550         case LFUN_PARAGRAPH_GOTO: {
1551                 int const id = convert<int>(cmd.getArg(0));
1552                 pos_type const pos = convert<int>(cmd.getArg(1));
1553                 if (id < 0)
1554                         break;
1555                 string const str_id_end = cmd.getArg(2);
1556                 string const str_pos_end = cmd.getArg(3);
1557                 int i = 0;
1558                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1559                         b = theBufferList().next(b)) {
1560
1561                         Cursor curs(*this);
1562                         curs.setCursor(b->getParFromID(id));
1563                         if (curs.atEnd()) {
1564                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1565                                 ++i;
1566                                 continue;
1567                         }
1568                         LYXERR(Debug::INFO, "Paragraph " << curs.paragraph().id()
1569                                 << " found in buffer `"
1570                                 << b->absFileName() << "'.");
1571
1572                         if (b == &buffer_) {
1573                                 bool success;
1574                                 if (str_id_end.empty() || str_pos_end.empty()) {
1575                                         // Set the cursor
1576                                         curs.pos() = pos;
1577                                         mouseSetCursor(curs);
1578                                         success = true;
1579                                 } else {
1580                                         int const id_end = convert<int>(str_id_end);
1581                                         pos_type const pos_end = convert<int>(str_pos_end);
1582                                         success = setCursorFromEntries({id, pos},
1583                                                                        {id_end, pos_end});
1584                                 }
1585                                 if (success && scrollToCursor(d->cursor_, SCROLL_TOP))
1586                                                 dr.screenUpdate(Update::Force);
1587                         } else {
1588                                 // Switch to other buffer view and resend cmd
1589                                 lyx::dispatch(FuncRequest(
1590                                         LFUN_BUFFER_SWITCH, b->absFileName()));
1591                                 lyx::dispatch(cmd);
1592                         }
1593                         break;
1594                 }
1595                 break;
1596         }
1597
1598         case LFUN_NOTE_NEXT:
1599                 if (gotoInset(this, { NOTE_CODE }, false))
1600                         dr.screenUpdate(Update::Force);
1601                 break;
1602
1603         case LFUN_REFERENCE_NEXT: {
1604                 if (gotoInset(this, { LABEL_CODE, REF_CODE }, true))
1605                         dr.screenUpdate(Update::Force);
1606                 break;
1607         }
1608
1609         case LFUN_CHANGE_NEXT:
1610                 findNextChange(this);
1611                 if (cur.inset().isTable())
1612                         // In tables, there might be whole changed rows or columns
1613                         cur.dispatch(cmd);
1614                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1615                 dr.screenUpdate(Update::Force | Update::FitCursor);
1616                 break;
1617
1618         case LFUN_CHANGE_PREVIOUS:
1619                 findPreviousChange(this);
1620                 if (cur.inset().isTable())
1621                         // In tables, there might be whole changed rows or columns
1622                         cur.dispatch(cmd);
1623                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1624                 dr.screenUpdate(Update::Force | Update::FitCursor);
1625                 break;
1626
1627         case LFUN_CHANGES_MERGE:
1628                 if (findNextChange(this) || findPreviousChange(this)) {
1629                         dr.screenUpdate(Update::Force | Update::FitCursor);
1630                         dr.forceBufferUpdate();
1631                         showDialog("changes");
1632                 }
1633                 break;
1634
1635         case LFUN_ALL_CHANGES_ACCEPT: {
1636                 // select complete document
1637                 cur.reset();
1638                 cur.selHandle(true);
1639                 buffer_.text().cursorBottom(cur);
1640                 // accept everything in a single step to support atomic undo
1641                 // temporarily disable track changes in order to end with really
1642                 // no new (e.g., DPSM-caused) changes (see #7487)
1643                 bool const track = buffer_.params().track_changes;
1644                 buffer_.params().track_changes = false;
1645                 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1646                 buffer_.params().track_changes = track;
1647                 cur.resetAnchor();
1648                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1649                 dr.screenUpdate(Update::Force | Update::FitCursor);
1650                 dr.forceBufferUpdate();
1651                 break;
1652         }
1653
1654         case LFUN_ALL_CHANGES_REJECT: {
1655                 // select complete document
1656                 cur.reset();
1657                 cur.selHandle(true);
1658                 buffer_.text().cursorBottom(cur);
1659                 // reject everything in a single step to support atomic undo
1660                 // temporarily disable track changes in order to end with really
1661                 // no new (e.g., DPSM-caused) changes (see #7487)
1662                 bool const track = buffer_.params().track_changes;
1663                 buffer_.params().track_changes = false;
1664                 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1665                 buffer_.params().track_changes = track;
1666                 cur.resetAnchor();
1667                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1668                 dr.screenUpdate(Update::Force | Update::FitCursor);
1669                 dr.forceBufferUpdate();
1670                 break;
1671         }
1672
1673         case LFUN_WORD_FIND_FORWARD:
1674         case LFUN_WORD_FIND_BACKWARD: {
1675                 docstring searched_string;
1676
1677                 if (!cmd.argument().empty()) {
1678                         setSearchRequestCache(cmd.argument());
1679                         searched_string = cmd.argument();
1680                 } else {
1681                         searched_string = searchRequestCache();
1682                 }
1683
1684                 if (searched_string.empty())
1685                         break;
1686
1687                 docstring const data =
1688                         find2string(searched_string, false, false,
1689                                     act == LFUN_WORD_FIND_FORWARD, false, false, false);
1690                 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1691                 if (found)
1692                         dr.screenUpdate(Update::Force | Update::FitCursor);
1693                 else
1694                         dr.setMessage(_("Search string not found!"));
1695                 break;
1696         }
1697
1698         case LFUN_WORD_FIND: {
1699                 docstring arg = cmd.argument();
1700                 if (arg.empty())
1701                         arg = searchRequestCache();
1702                 if (arg.empty()) {
1703                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1704                         break;
1705                 }
1706                 if (lyxfind(this, FuncRequest(act, arg)))
1707                         dr.screenUpdate(Update::Force | Update::FitCursor);
1708                 else
1709                         dr.setMessage(_("Search string not found!"));
1710
1711                 setSearchRequestCache(arg);
1712                 break;
1713         }
1714
1715         case LFUN_SEARCH_STRING_SET: {
1716                 docstring pattern = cmd.argument();
1717                 if (!pattern.empty()) {
1718                         setSearchRequestCache(pattern);
1719                         break;
1720                 }
1721                 if (cur.selection())
1722                         pattern = cur.selectionAsString(false);
1723                 else if (!cur.inTexted())
1724                         break; // not suitable for selectWord at cursor
1725                 else {
1726                         pos_type spos = cur.pos();
1727                         cur.innerText()->selectWord(cur, WHOLE_WORD);
1728                         pattern = cur.selectionAsString(false);
1729                         cur.selection(false);
1730                         cur.pos() = spos;
1731                 }
1732                 setSearchRequestCache(pattern);
1733                 break;
1734         }
1735
1736         case LFUN_WORD_REPLACE: {
1737                 if (lyxreplace(this, cmd)) {
1738                         dr.forceBufferUpdate();
1739                         dr.screenUpdate(Update::Force | Update::FitCursor);
1740                 }
1741                 else
1742                         dr.setMessage(_("Search string not found!"));
1743                 break;
1744         }
1745
1746         case LFUN_WORD_FINDADV: {
1747                 FindAndReplaceOptions opt;
1748                 istringstream iss(to_utf8(cmd.argument()));
1749                 iss >> opt;
1750                 if (findAdv(this, opt)) {
1751                         dr.screenUpdate(Update::Force | Update::FitCursor);
1752                         cur.dispatched();
1753                         dispatched = true;
1754                 } else {
1755                         cur.undispatched();
1756                         dispatched = false;
1757                 }
1758                 break;
1759         }
1760
1761         case LFUN_INDEX_TAG_ALL: {
1762                 if (cur.pos() == 0)
1763                         // nothing precedes
1764                         break;
1765
1766                 Inset * ins = cur.nextInset();
1767                 if (!ins || ins->lyxCode() != INDEX_CODE)
1768                         // not at index inset
1769                         break;
1770
1771                 // clone the index inset
1772                 InsetIndex * cins =
1773                         new InsetIndex(static_cast<InsetIndex &>(*cur.nextInset()));
1774                 // In order to avoid duplication, we compare the
1775                 // LaTeX output if we find another index inset after
1776                 // the word
1777                 odocstringstream oilatex;
1778                 otexstream oits(oilatex);
1779                 OutputParams rp(&cur.buffer()->params().encoding());
1780                 ins->latex(oits, rp);
1781                 cap::copyInsetToTemp(cur, cins);
1782
1783                 // move backwards into preceding word
1784                 // skip over other index insets
1785                 cur.backwardPosIgnoreCollapsed();
1786                 while (true) {
1787                         if (cur.inset().lyxCode() == INDEX_CODE)
1788                                 cur.pop_back();
1789                         else if (cur.prevInset() && cur.prevInset()->lyxCode() == INDEX_CODE)
1790                                 cur.backwardPosIgnoreCollapsed();
1791                         else
1792                                 break;
1793                 }
1794                 if (!cur.inTexted()) {
1795                         // Nothing to do here.
1796                         setCursorFromInset(ins);
1797                         break;
1798                 }
1799                 // Get word or selection
1800                 cur.text()->selectWord(cur, WHOLE_WORD);
1801                 docstring const searched_string = cur.selectionAsString(false);
1802                 if (searched_string.empty())
1803                         break;
1804                 // Start from the beginning
1805                 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
1806                 while (findOne(this, searched_string,
1807                                false,// case sensitive
1808                                true,// match whole word only
1809                                true,// forward
1810                                false,//find deleted
1811                                false,//check wrap
1812                                false,// auto-wrap
1813                                false,// instant
1814                                false// only selection
1815                                )) {
1816                         cur.clearSelection();
1817                         Inset * ains = cur.nextInset();
1818                         if (ains && ains->lyxCode() == INDEX_CODE) {
1819                                 // We have an index inset.
1820                                 // Check whether it has the same
1821                                 // LaTeX content and move on if so.
1822                                 odocstringstream filatex;
1823                                 otexstream fits(filatex);
1824                                 ains->latex(fits, rp);
1825                                 if (oilatex.str() == filatex.str())
1826                                         continue;
1827                         }
1828                         // Paste the inset and possibly continue
1829                         cap::pasteFromTemp(cursor(), cursor().buffer()->errorList("Paste"));
1830                 }
1831                 // Go back to start position.
1832                 setCursorFromInset(ins);
1833                 dr.screenUpdate(cur.result().screenUpdate());
1834                 if (cur.result().needBufferUpdate())
1835                         dr.forceBufferUpdate();
1836                 break;
1837         }
1838
1839         case LFUN_MARK_OFF:
1840                 cur.clearSelection();
1841                 dr.setMessage(from_utf8(N_("Mark off")));
1842                 break;
1843
1844         case LFUN_MARK_ON:
1845                 cur.clearSelection();
1846                 cur.setMark(true);
1847                 dr.setMessage(from_utf8(N_("Mark on")));
1848                 break;
1849
1850         case LFUN_MARK_TOGGLE:
1851                 cur.selection(false);
1852                 if (cur.mark()) {
1853                         cur.setMark(false);
1854                         dr.setMessage(from_utf8(N_("Mark removed")));
1855                 } else {
1856                         cur.setMark(true);
1857                         dr.setMessage(from_utf8(N_("Mark set")));
1858                 }
1859                 cur.resetAnchor();
1860                 break;
1861
1862         case LFUN_SCREEN_SHOW_CURSOR:
1863                 showCursor();
1864                 break;
1865
1866         case LFUN_SCREEN_RECENTER:
1867                 recenter();
1868                 break;
1869
1870         case LFUN_BIBTEX_DATABASE_ADD: {
1871                 Cursor tmpcur = cur;
1872                 findInset(tmpcur, { BIBTEX_CODE }, false);
1873                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1874                                                 BIBTEX_CODE);
1875                 if (inset) {
1876                         if (inset->addDatabase(cmd.argument()))
1877                                 dr.forceBufferUpdate();
1878                 }
1879                 break;
1880         }
1881
1882         case LFUN_BIBTEX_DATABASE_DEL: {
1883                 Cursor tmpcur = cur;
1884                 findInset(tmpcur, { BIBTEX_CODE }, false);
1885                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1886                                                 BIBTEX_CODE);
1887                 if (inset) {
1888                         if (inset->delDatabase(cmd.argument()))
1889                                 dr.forceBufferUpdate();
1890                 }
1891                 break;
1892         }
1893
1894         case LFUN_GRAPHICS_UNIFY: {
1895
1896                 cur.recordUndoFullBuffer();
1897
1898                 DocIterator from, to;
1899                 from = cur.selectionBegin();
1900                 to = cur.selectionEnd();
1901
1902                 string const newId = cmd.getArg(0);
1903                 bool fetchId = newId.empty(); //if we wait for groupId from first graphics inset
1904
1905                 InsetGraphicsParams grp_par;
1906                 if (!fetchId)
1907                         InsetGraphics::string2params(graphics::getGroupParams(buffer_, newId), buffer_, grp_par);
1908
1909                 if (!from.nextInset())  //move to closest inset
1910                         from.forwardInset();
1911
1912                 while (!from.empty() && from < to) {
1913                         Inset * inset = from.nextInset();
1914                         if (!inset)
1915                                 break;
1916                         InsetGraphics * ig = inset->asInsetGraphics();
1917                         if (ig) {
1918                                 InsetGraphicsParams inspar = ig->getParams();
1919                                 if (fetchId) {
1920                                         grp_par = inspar;
1921                                         fetchId = false;
1922                                 } else {
1923                                         grp_par.filename = inspar.filename;
1924                                         ig->setParams(grp_par);
1925                                 }
1926                         }
1927                         from.forwardInset();
1928                 }
1929                 dr.screenUpdate(Update::Force); //needed if triggered from context menu
1930                 break;
1931         }
1932
1933         case LFUN_BIBTEX_DATABASE_LIST: {
1934                 docstring_list const & files = buffer_.getBibfiles();
1935                 bool first = true;
1936                 docstring result;
1937                 char const separator(os::path_separator());
1938                 for (auto const & file : files) {
1939                         if (first)
1940                                 first = false;
1941                         else
1942                                 result += separator;
1943
1944                         FileName const fn = buffer_.getBibfilePath(file);
1945                         string const path = fn.realPath();
1946                         result += from_utf8(os::external_path(path));
1947                 }
1948                 dr.setMessage(result);
1949                 break;
1950         }
1951
1952         case LFUN_STATISTICS: {
1953                 DocIterator from, to;
1954                 if (cur.selection()) {
1955                         from = cur.selectionBegin();
1956                         to = cur.selectionEnd();
1957                 } else {
1958                         from = doc_iterator_begin(&buffer_);
1959                         to = doc_iterator_end(&buffer_);
1960                 }
1961                 buffer_.updateStatistics(from, to);
1962                 int const words = buffer_.wordCount();
1963                 int const chars = buffer_.charCount(false);
1964                 int const chars_blanks = buffer_.charCount(true);
1965                 docstring message;
1966                 if (cur.selection())
1967                         message = _("Statistics for the selection:");
1968                 else
1969                         message = _("Statistics for the document:");
1970                 message += "\n\n";
1971                 if (words != 1)
1972                         message += bformat(_("%1$d words"), words);
1973                 else
1974                         message += _("One word");
1975                 message += "\n";
1976                 if (chars_blanks != 1)
1977                         message += bformat(_("%1$d characters"), chars_blanks);
1978                 else
1979                         message += _("One character");
1980                 message += "\n";
1981                 if (chars != 1)
1982                         message += bformat(_("%1$d characters (no blanks)"), chars);
1983                 else
1984                         message += _("One character (no blanks)");
1985
1986                 Alert::information(_("Statistics"), message);
1987         }
1988                 break;
1989
1990         case LFUN_SCREEN_UP:
1991         case LFUN_SCREEN_DOWN: {
1992                 Point p = getPos(cur);
1993                 // This code has been commented out to enable to scroll down a
1994                 // document, even if there are large insets in it (see bug #5465).
1995                 /*if (p.y_ < 0 || p.y_ > height_) {
1996                         // The cursor is off-screen so recenter before proceeding.
1997                         showCursor();
1998                         p = getPos(cur);
1999                 }*/
2000                 int const scrolled = scroll(act == LFUN_SCREEN_UP
2001                         ? -height_ : height_);
2002                 if (act == LFUN_SCREEN_UP && scrolled > -height_)
2003                         p = Point(0, 0);
2004                 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
2005                         p = Point(width_, height_);
2006                 bool const in_texted = cur.inTexted();
2007                 cur.setCursor(doc_iterator_begin(cur.buffer()));
2008                 cur.selHandle(false);
2009                 // Force an immediate computation of metrics because we need it below
2010                 if (scrolled)
2011                         processUpdateFlags(Update::Force);
2012
2013                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
2014                         true, act == LFUN_SCREEN_UP);
2015                 //FIXME: what to do with cur.x_target()?
2016                 bool update = in_texted && cur.bv().checkDepm(cur, old);
2017                 cur.finishUndo();
2018
2019                 if (update || cur.mark())
2020                         dr.screenUpdate(Update::Force | Update::FitCursor);
2021                 if (update)
2022                         dr.forceBufferUpdate();
2023                 break;
2024         }
2025
2026         case LFUN_SCROLL: {
2027                 string const scroll_type = cmd.getArg(0);
2028                 int scroll_step = 0;
2029                 if (scroll_type == "line")
2030                         scroll_step = d->scrollbarParameters_.single_step;
2031                 else if (scroll_type == "page")
2032                         scroll_step = d->scrollbarParameters_.page_step;
2033                 else
2034                         return;
2035                 string const scroll_quantity = cmd.getArg(1);
2036                 if (scroll_quantity == "up")
2037                         scrollUp(scroll_step);
2038                 else if (scroll_quantity == "down")
2039                         scrollDown(scroll_step);
2040                 else {
2041                         int const scroll_value = convert<int>(scroll_quantity);
2042                         if (scroll_value)
2043                                 scroll(scroll_step * scroll_value);
2044                 }
2045                 dr.screenUpdate(Update::ForceDraw);
2046                 dr.forceBufferUpdate();
2047                 break;
2048         }
2049
2050         case LFUN_SCREEN_UP_SELECT: {
2051                 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
2052                 cur.selHandle(true);
2053                 if (isTopScreen()) {
2054                         lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
2055                         cur.finishUndo();
2056                         break;
2057                 }
2058                 int y = getPos(cur).y_;
2059                 int const ymin = y - height_ + defaultRowHeight();
2060                 while (y > ymin && cur.up())
2061                         y = getPos(cur).y_;
2062
2063                 cur.finishUndo();
2064                 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
2065                 break;
2066         }
2067
2068         case LFUN_SCREEN_DOWN_SELECT: {
2069                 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
2070                 cur.selHandle(true);
2071                 if (isBottomScreen()) {
2072                         lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
2073                         cur.finishUndo();
2074                         break;
2075                 }
2076                 int y = getPos(cur).y_;
2077                 int const ymax = y + height_ - defaultRowHeight();
2078                 while (y < ymax && cur.down())
2079                         y = getPos(cur).y_;
2080
2081                 cur.finishUndo();
2082                 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
2083                 break;
2084         }
2085
2086
2087         case LFUN_INSET_SELECT_ALL: {
2088                 // true if all cells are selected
2089                 bool const all_selected = cur.depth() > 1
2090                     && cur.selBegin().at_begin()
2091                     && cur.selEnd().at_end();
2092                 // true if some cells are selected
2093                 bool const cells_selected = cur.depth() > 1
2094                     && cur.selBegin().at_cell_begin()
2095                         && cur.selEnd().at_cell_end();
2096                 if (all_selected || (cells_selected && !cur.inset().isTable())) {
2097                         // All the contents of the inset if selected, or only at
2098                         // least one cell but inset is not a table.
2099                         // Select the inset from outside.
2100                         cur.pop();
2101                         cur.resetAnchor();
2102                         cur.selection(true);
2103                         cur.posForward();
2104                 } else if (cells_selected) {
2105                         // At least one complete cell is selected and inset is a table.
2106                         // Select all cells
2107                         cur.idx() = 0;
2108                         cur.pit() = 0;
2109                         cur.pos() = 0;
2110                         cur.resetAnchor();
2111                         cur.selection(true);
2112                         cur.idx() = cur.lastidx();
2113                         cur.pit() = cur.lastpit();
2114                         cur.pos() = cur.lastpos();
2115                 } else {
2116                         // select current cell
2117                         cur.pit() = 0;
2118                         cur.pos() = 0;
2119                         cur.resetAnchor();
2120                         cur.selection(true);
2121                         cur.pit() = cur.lastpit();
2122                         cur.pos() = cur.lastpos();
2123                 }
2124                 cur.setCurrentFont();
2125                 dr.screenUpdate(Update::Force);
2126                 break;
2127         }
2128
2129
2130         case LFUN_UNICODE_INSERT: {
2131                 if (cmd.argument().empty())
2132                         break;
2133
2134                 FuncCode code = cur.inset().currentMode() == Inset::MATH_MODE ?
2135                         LFUN_MATH_INSERT : LFUN_SELF_INSERT;
2136                 int i = 0;
2137                 while (true) {
2138                         docstring const arg = from_utf8(cmd.getArg(i));
2139                         if (arg.empty())
2140                                 break;
2141                         if (!isHex(arg)) {
2142                                 LYXERR0("Not a hexstring: " << arg);
2143                                 ++i;
2144                                 continue;
2145                         }
2146                         char_type c = hexToInt(arg);
2147                         if (c >= 32 && c < 0x10ffff) {
2148                                 LYXERR(Debug::KEY, "Inserting c: " << c);
2149                                 lyx::dispatch(FuncRequest(code, docstring(1, c)));
2150                         }
2151                         ++i;
2152                 }
2153                 break;
2154         }
2155
2156
2157         // This would be in Buffer class if only Cursor did not
2158         // require a bufferview
2159         case LFUN_INSET_FORALL: {
2160                 docstring const name = from_utf8(cmd.getArg(0));
2161                 string const commandstr = cmd.getLongArg(1);
2162                 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
2163
2164                 // an arbitrary number to limit number of iterations
2165                 const int max_iter = 100000;
2166                 int iterations = 0;
2167                 Cursor & bvcur = d->cursor_;
2168                 Cursor const savecur = bvcur;
2169                 bvcur.reset();
2170                 if (!bvcur.nextInset())
2171                         bvcur.forwardInset();
2172                 bvcur.beginUndoGroup();
2173                 while(bvcur && iterations < max_iter) {
2174                         Inset * const ins = bvcur.nextInset();
2175                         if (!ins)
2176                                 break;
2177                         docstring insname = ins->layoutName();
2178                         while (!insname.empty()) {
2179                                 if (insname == name || name == from_utf8("*")) {
2180                                         lyx::dispatch(fr, dr);
2181                                         // we do not want to remember selection here
2182                                         bvcur.clearSelection();
2183                                         ++iterations;
2184                                         break;
2185                                 }
2186                                 size_t const i = insname.rfind(':');
2187                                 if (i == string::npos)
2188                                         break;
2189                                 insname = insname.substr(0, i);
2190                         }
2191                         // if we did not delete the inset, skip it
2192                         if (!bvcur.nextInset() || bvcur.nextInset() == ins)
2193                                 bvcur.forwardInset();
2194                 }
2195                 bvcur = savecur;
2196                 bvcur.fixIfBroken();
2197                 /** This is a dummy undo record only to remember the cursor
2198                  * that has just been set; this will be used on a redo action
2199                  * (see ticket #10097)
2200
2201                  * FIXME: a better fix would be to have a way to set the
2202                  * cursor value directly, but I am not sure it is worth it.
2203                  */
2204                 bvcur.recordUndo();
2205                 bvcur.endUndoGroup();
2206                 dr.screenUpdate(Update::Force);
2207                 dr.forceBufferUpdate();
2208
2209                 if (iterations >= max_iter) {
2210                         dr.setError(true);
2211                         dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
2212                 } else
2213                         dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
2214                 break;
2215         }
2216
2217
2218         case LFUN_BRANCH_ADD_INSERT: {
2219                 docstring branch_name = from_utf8(cmd.getArg(0));
2220                 if (branch_name.empty())
2221                         if (!Alert::askForText(branch_name, _("Branch name")) ||
2222                                                 branch_name.empty())
2223                                 break;
2224
2225                 DispatchResult drtmp;
2226                 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
2227                 if (drtmp.error()) {
2228                         Alert::warning(_("Branch already exists"), drtmp.message());
2229                         break;
2230                 }
2231                 docstring const sep = buffer_.params().branchlist().separator();
2232                 for (docstring const & branch : getVectorFromString(branch_name, sep))
2233                         lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch));
2234                 break;
2235         }
2236
2237         case LFUN_KEYMAP_OFF:
2238                 getIntl().keyMapOn(false);
2239                 break;
2240
2241         case LFUN_KEYMAP_PRIMARY:
2242                 getIntl().keyMapPrim();
2243                 break;
2244
2245         case LFUN_KEYMAP_SECONDARY:
2246                 getIntl().keyMapSec();
2247                 break;
2248
2249         case LFUN_KEYMAP_TOGGLE:
2250                 getIntl().toggleKeyMap();
2251                 break;
2252
2253         case LFUN_DIALOG_SHOW_NEW_INSET: {
2254                 string const name = cmd.getArg(0);
2255                 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2256                 if (decodeInsetParam(name, data, buffer_))
2257                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
2258                 else
2259                         lyxerr << "Inset type '" << name <<
2260                         "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" <<  endl;
2261                 break;
2262         }
2263
2264         case LFUN_CITATION_INSERT: {
2265                 if (argument.empty()) {
2266                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
2267                         break;
2268                 }
2269                 // we can have one optional argument, delimited by '|'
2270                 // citation-insert <key>|<text_before>
2271                 // this should be enhanced to also support text_after
2272                 // and citation style
2273                 string arg = argument;
2274                 string opt1;
2275                 if (contains(argument, "|")) {
2276                         arg = token(argument, '|', 0);
2277                         opt1 = token(argument, '|', 1);
2278                 }
2279
2280                 // if our cursor is directly in front of or behind a citation inset,
2281                 // we will instead add the new key to it.
2282                 Inset * inset = cur.nextInset();
2283                 if (!inset || inset->lyxCode() != CITE_CODE)
2284                         inset = cur.prevInset();
2285                 if (inset && inset->lyxCode() == CITE_CODE) {
2286                         InsetCitation * icite = static_cast<InsetCitation *>(inset);
2287                         if (icite->addKey(arg)) {
2288                                 dr.forceBufferUpdate();
2289                                 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
2290                                 if (!opt1.empty())
2291                                         LYXERR0("Discarding optional argument to citation-insert.");
2292                         }
2293                         dispatched = true;
2294                         break;
2295                 }
2296                 InsetCommandParams icp(CITE_CODE);
2297                 icp["key"] = from_utf8(arg);
2298                 if (!opt1.empty())
2299                         icp["before"] = from_utf8(opt1);
2300                 icp["literal"] = 
2301                         from_ascii(InsetCitation::last_literal ? "true" : "false");
2302                 string icstr = InsetCommand::params2string(icp);
2303                 FuncRequest fr(LFUN_INSET_INSERT, icstr);
2304                 lyx::dispatch(fr);
2305
2306                 // if the request comes from the LyX server, then we
2307                 // return a list of the undefined keys, in case some
2308                 // action could be taken.
2309                 if (cmd.origin() != FuncRequest::LYXSERVER)
2310                         break;
2311
2312                 vector<docstring> keys = getVectorFromString(from_utf8(arg));
2313                 vector<docstring>::iterator it = keys.begin();
2314                 vector<docstring>::const_iterator end = keys.end();
2315
2316                 BiblioInfo const & bibInfo = buffer_.masterBibInfo();
2317                 const BiblioInfo::const_iterator bibEnd = bibInfo.end();
2318                 while (it != end) {
2319                         if (bibInfo.find(*it) != bibEnd) {
2320                                 it = keys.erase(it);
2321                                 end = keys.end();
2322                         } else
2323                                 ++it;
2324                 }
2325                 dr.setMessage(getStringFromVector(keys));
2326
2327                 break;
2328         }
2329
2330         case LFUN_INSET_APPLY: {
2331                 string const name = cmd.getArg(0);
2332                 Inset * inset = editedInset(name);
2333                 if (!inset) {
2334                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2335                         lyx::dispatch(fr);
2336                         break;
2337                 }
2338                 // put cursor in front of inset.
2339                 if (!setCursorFromInset(inset)) {
2340                         LASSERT(false, break);
2341                 }
2342                 cur.recordUndo();
2343                 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2344                 inset->dispatch(cur, fr);
2345                 dr.screenUpdate(cur.result().screenUpdate());
2346                 if (cur.result().needBufferUpdate())
2347                         dr.forceBufferUpdate();
2348                 break;
2349         }
2350
2351         // FIXME:
2352         // The change of language of buffer belongs to the Buffer class.
2353         // We have to do it here because we need a cursor for Undo.
2354         // When Undo::recordUndoBufferParams() is implemented someday
2355         // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
2356         case LFUN_BUFFER_LANGUAGE: {
2357                 Language const * oldL = buffer_.params().language;
2358                 Language const * newL = languages.getLanguage(argument);
2359                 if (!newL || oldL == newL)
2360                         break;
2361                 if (oldL->rightToLeft() == newL->rightToLeft()) {
2362                         cur.recordUndoFullBuffer();
2363                         buffer_.changeLanguage(oldL, newL);
2364                         cur.setCurrentFont();
2365                         dr.forceBufferUpdate();
2366                 }
2367                 break;
2368         }
2369
2370         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2371         case LFUN_FILE_INSERT_PLAINTEXT: {
2372                 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
2373                 string const fname = to_utf8(cmd.argument());
2374                 if (!FileName::isAbsolute(fname))
2375                         dr.setMessage(_("Absolute filename expected."));
2376                 else
2377                         insertPlaintextFile(FileName(fname), as_paragraph);
2378                 break;
2379         }
2380
2381         case LFUN_COPY:
2382                 // With multi-cell table content, we pass down to the inset
2383                 if (cur.inTexted() && cur.selection()
2384                     && cur.selectionBegin().idx() != cur.selectionEnd().idx()) {
2385                         buffer_.dispatch(cmd, dr);
2386                         dispatched = dr.dispatched();
2387                         break;
2388                 }
2389                 cap::copySelection(cur);
2390                 cur.message(_("Copy"));
2391                 break;
2392
2393         default:
2394                 // OK, so try the Buffer itself...
2395                 buffer_.dispatch(cmd, dr);
2396                 dispatched = dr.dispatched();
2397                 break;
2398         }
2399
2400         buffer_.undo().endUndoGroup();
2401         dr.dispatched(dispatched);
2402
2403         // NOTE: The code below is copied from Cursor::dispatch. If you
2404         // need to modify this, please update the other one too.
2405
2406         // notify insets we just entered/left
2407         if (cursor() != old) {
2408                 old.beginUndoGroup();
2409                 old.fixIfBroken();
2410                 bool badcursor = notifyCursorLeavesOrEnters(old, cursor());
2411                 if (badcursor) {
2412                         cursor().fixIfBroken();
2413                         resetInlineCompletionPos();
2414                 }
2415                 old.endUndoGroup();
2416         }
2417 }
2418
2419
2420 docstring BufferView::requestSelection()
2421 {
2422         Cursor & cur = d->cursor_;
2423
2424         LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2425         if (!cur.selection()) {
2426                 d->xsel_cache_.set = false;
2427                 return docstring();
2428         }
2429
2430         LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2431         if (!d->xsel_cache_.set ||
2432             cur.top() != d->xsel_cache_.cursor ||
2433             cur.realAnchor().top() != d->xsel_cache_.anchor)
2434         {
2435                 d->xsel_cache_.cursor = cur.top();
2436                 d->xsel_cache_.anchor = cur.realAnchor().top();
2437                 d->xsel_cache_.set = cur.selection();
2438                 return cur.selectionAsString(false);
2439         }
2440         return docstring();
2441 }
2442
2443
2444 void BufferView::clearSelection()
2445 {
2446         d->cursor_.clearSelection();
2447         // Clear the selection buffer. Otherwise a subsequent
2448         // middle-mouse-button paste would use the selection buffer,
2449         // not the more current external selection.
2450         cap::clearSelection();
2451         d->xsel_cache_.set = false;
2452         // The buffer did not really change, but this causes the
2453         // redraw we need because we cleared the selection above.
2454         buffer_.changed(false);
2455 }
2456
2457
2458 void BufferView::resize(int width, int height)
2459 {
2460         // Update from work area
2461         width_ = width;
2462         height_ = height;
2463
2464         // Clear the paragraph height cache.
2465         d->par_height_.clear();
2466         // Redo the metrics.
2467         updateMetrics();
2468 }
2469
2470
2471 Inset const * BufferView::getCoveringInset(Text const & text,
2472                 int x, int y) const
2473 {
2474         TextMetrics & tm = d->text_metrics_[&text];
2475         Inset * inset = tm.checkInsetHit(x, y);
2476         if (!inset)
2477                 return nullptr;
2478
2479         if (!inset->descendable(*this))
2480                 // No need to go further down if the inset is not
2481                 // descendable.
2482                 return inset;
2483
2484         size_t cell_number = inset->nargs();
2485         // Check all the inner cell.
2486         for (size_t i = 0; i != cell_number; ++i) {
2487                 Text const * inner_text = inset->getText(i);
2488                 if (inner_text) {
2489                         // Try deeper.
2490                         Inset const * inset_deeper =
2491                                 getCoveringInset(*inner_text, x, y);
2492                         if (inset_deeper)
2493                                 return inset_deeper;
2494                 }
2495         }
2496
2497         return inset;
2498 }
2499
2500
2501 Inset const * BufferView::clickableMathInset(InsetMathNest const * inset,
2502                 CoordCache::Insets const & inset_cache, int x, int y) const
2503 {
2504         for (size_t i = 0; i < inset->nargs(); ++i) {
2505                 MathData const & ar = inset->cell(i);
2506                 for (size_t j = 0; j < ar.size(); ++j) {
2507                         string const name = lyxerr.debugging(Debug::MATHED)
2508                                 ? insetName(ar[j].nucleus()->lyxCode())
2509                                 : string();
2510                         LYXERR(Debug::MATHED, "Checking inset: " << name);
2511                         if (ar[j].nucleus()->clickable(*this, x, y)) {
2512                                 if (inset_cache.covers(ar[j].nucleus(), x, y)) {
2513                                         LYXERR(Debug::MATHED, "Clickable inset: "
2514                                                << name);
2515                                         return ar[j].nucleus();
2516                                 }
2517                         }
2518                         InsetMathNest const * imn =
2519                                 ar[j].nucleus()->asNestInset();
2520                         if (imn) {
2521                                 Inset const * inner =
2522                                         clickableMathInset(imn, inset_cache, x, y);
2523                                 if (inner)
2524                                         return inner;
2525                         }
2526                 }
2527         }
2528         return nullptr;
2529 }
2530
2531
2532 void BufferView::updateHoveredInset() const
2533 {
2534         // Get inset under mouse, if there is one.
2535         int const x = d->mouse_position_cache_.x_;
2536         int const y = d->mouse_position_cache_.y_;
2537         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2538         if (covering_inset && covering_inset->asInsetMath()) {
2539                 Inset const * inner_inset = clickableMathInset(
2540                                 covering_inset->asInsetMath()->asNestInset(),
2541                                 coordCache().getInsets(), x, y);
2542                 if (inner_inset)
2543                         covering_inset = inner_inset;
2544         }
2545
2546         d->clickable_inset_ = covering_inset && covering_inset->clickable(*this, x, y);
2547
2548         if (covering_inset == d->last_inset_)
2549                 // Same inset, no need to do anything...
2550                 return;
2551
2552         bool need_redraw = false;
2553         if (d->last_inset_) {
2554                 // Remove the hint on the last hovered inset (if any).
2555                 need_redraw |= d->last_inset_->setMouseHover(this, false);
2556                 d->last_inset_ = nullptr;
2557         }
2558
2559         if (covering_inset && covering_inset->setMouseHover(this, true)) {
2560                 need_redraw = true;
2561                 // Only the insets that accept the hover state, do
2562                 // clear the last_inset_, so only set the last_inset_
2563                 // member if the hovered setting is accepted.
2564                 d->last_inset_ = covering_inset;
2565         }
2566
2567         if (need_redraw) {
2568                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2569                                 << d->mouse_position_cache_.x_ << ", "
2570                                 << d->mouse_position_cache_.y_ << ")");
2571
2572                 d->update_strategy_ = DecorationUpdate;
2573
2574                 // This event (moving without mouse click) is not passed further.
2575                 // This should be changed if it is further utilized.
2576                 buffer_.changed(false);
2577         }
2578 }
2579
2580
2581 void BufferView::clearLastInset(Inset * inset) const
2582 {
2583         if (d->last_inset_ != inset) {
2584                 LYXERR0("Wrong last_inset!");
2585                 LATTEST(false);
2586         }
2587         d->last_inset_ = nullptr;
2588 }
2589
2590
2591 bool BufferView::mouseSelecting() const
2592 {
2593         return d->mouse_selecting_;
2594 }
2595
2596
2597 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2598 {
2599         //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2600
2601         // This is only called for mouse related events including
2602         // LFUN_FILE_OPEN generated by drag-and-drop.
2603         FuncRequest cmd = cmd0;
2604
2605         Cursor old = cursor();
2606         Cursor cur(*this);
2607         cur.push(buffer_.inset());
2608         cur.selection(d->cursor_.selection());
2609
2610         // Either the inset under the cursor or the
2611         // surrounding Text will handle this event.
2612
2613         // make sure we stay within the screen...
2614         cmd.set_y(min(max(cmd.y(), -1), height_));
2615
2616         d->mouse_position_cache_.x_ = cmd.x();
2617         d->mouse_position_cache_.y_ = cmd.y();
2618
2619         d->mouse_selecting_ =
2620                 cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::button1;
2621
2622         if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2623                 updateHoveredInset();
2624                 return;
2625         }
2626
2627         // Build temporary cursor.
2628         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2629         if (inset) {
2630                 // If inset is not editable, cur.pos() might point behind the
2631                 // inset (depending on cmd.x(), cmd.y()). This is needed for
2632                 // editing to fix bug 9628, but e.g. the context menu needs a
2633                 // cursor in front of the inset.
2634                 if ((inset->hasSettings() || !inset->contextMenuName().empty()
2635                      || inset->lyxCode() == SEPARATOR_CODE) &&
2636                     cur.nextInset() != inset && cur.prevInset() == inset)
2637                         cur.posBackward();
2638         } else if (cur.inTexted() && cur.pos()
2639                         && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
2640                 // Always place cursor in front of a separator inset.
2641                 cur.posBackward();
2642         }
2643
2644         // Put anchor at the same position.
2645         cur.resetAnchor();
2646
2647         cur.beginUndoGroup();
2648
2649         // Try to dispatch to an non-editable inset near this position
2650         // via the temp cursor. If the inset wishes to change the real
2651         // cursor it has to do so explicitly by using
2652         //  cur.bv().cursor() = cur;  (or similar)
2653         if (inset)
2654                 inset->dispatch(cur, cmd);
2655
2656         // Now dispatch to the temporary cursor. If the real cursor should
2657         // be modified, the inset's dispatch has to do so explicitly.
2658         if (!inset || !cur.result().dispatched())
2659                 cur.dispatch(cmd);
2660
2661         // Notify left insets
2662         if (cur != old) {
2663                 bool badcursor = old.fixIfBroken() || cur.fixIfBroken();
2664                 badcursor = badcursor || notifyCursorLeavesOrEnters(old, cur);
2665                 if (badcursor)
2666                         cursor().fixIfBroken();
2667         }
2668
2669         cur.endUndoGroup();
2670
2671         // Do we have a selection?
2672         theSelection().haveSelection(cursor().selection());
2673
2674         if (cur.needBufferUpdate() || buffer().needUpdate()) {
2675                 cur.clearBufferUpdate();
2676                 buffer().updateBuffer();
2677         }
2678
2679         // If the command has been dispatched,
2680         if (cur.result().dispatched() || cur.result().screenUpdate())
2681                 processUpdateFlags(cur.result().screenUpdate());
2682 }
2683
2684
2685 int BufferView::minVisiblePart()
2686 {
2687         return 2 * defaultRowHeight();
2688 }
2689
2690
2691 int BufferView::scroll(int pixels)
2692 {
2693         if (pixels > 0)
2694                 return scrollDown(pixels);
2695         if (pixels < 0)
2696                 return scrollUp(-pixels);
2697         return 0;
2698 }
2699
2700
2701 int BufferView::scrollDown(int pixels)
2702 {
2703         Text * text = &buffer_.text();
2704         TextMetrics & tm = d->text_metrics_[text];
2705         int const ymax = height_ + pixels;
2706         while (true) {
2707                 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2708                 int bottom_pos = last.second->position() + last.second->descent();
2709                 if (lyxrc.scroll_below_document)
2710                         bottom_pos += height_ - minVisiblePart();
2711                 if (last.first + 1 == int(text->paragraphs().size())) {
2712                         if (bottom_pos <= height_)
2713                                 return 0;
2714                         pixels = min(pixels, bottom_pos - height_);
2715                         break;
2716                 }
2717                 if (bottom_pos > ymax)
2718                         break;
2719                 tm.newParMetricsDown();
2720         }
2721         d->anchor_ypos_ -= pixels;
2722         return -pixels;
2723 }
2724
2725
2726 int BufferView::scrollUp(int pixels)
2727 {
2728         Text * text = &buffer_.text();
2729         TextMetrics & tm = d->text_metrics_[text];
2730         int ymin = - pixels;
2731         while (true) {
2732                 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2733                 int top_pos = first.second->position() - first.second->ascent();
2734                 if (first.first == 0) {
2735                         if (top_pos >= 0)
2736                                 return 0;
2737                         pixels = min(pixels, - top_pos);
2738                         break;
2739                 }
2740                 if (top_pos < ymin)
2741                         break;
2742                 tm.newParMetricsUp();
2743         }
2744         d->anchor_ypos_ += pixels;
2745         return pixels;
2746 }
2747
2748
2749 bool BufferView::setCursorFromRow(int row)
2750 {
2751         TexRow::TextEntry start, end;
2752         tie(start,end) = buffer_.texrow().getEntriesFromRow(row);
2753         LYXERR(Debug::OUTFILE,
2754                "setCursorFromRow: for row " << row << ", TexRow has found "
2755                "start (id=" << start.id << ",pos=" << start.pos << "), "
2756                "end (id=" << end.id << ",pos=" << end.pos << ")");
2757         return setCursorFromEntries(start, end);
2758 }
2759
2760
2761 bool BufferView::setCursorFromEntries(TexRow::TextEntry start,
2762                                       TexRow::TextEntry end)
2763 {
2764         DocIterator dit_start, dit_end;
2765         tie(dit_start,dit_end) =
2766                 TexRow::getDocIteratorsFromEntries(start, end, buffer_);
2767         if (!dit_start)
2768                 return false;
2769         // Setting selection start
2770         d->cursor_.clearSelection();
2771         setCursor(dit_start);
2772         // Setting selection end
2773         if (dit_end) {
2774                 d->cursor_.resetAnchor();
2775                 setCursorSelectionTo(dit_end);
2776         }
2777         return true;
2778 }
2779
2780
2781 bool BufferView::setCursorFromInset(Inset const * inset)
2782 {
2783         // are we already there?
2784         if (cursor().nextInset() == inset)
2785                 return true;
2786
2787         // Inset is not at cursor position. Find it in the document.
2788         Cursor cur(*this);
2789         cur.reset();
2790         while (cur && cur.nextInset() != inset)
2791                 cur.forwardInset();
2792
2793         if (cur) {
2794                 setCursor(cur);
2795                 return true;
2796         }
2797         return false;
2798 }
2799
2800
2801 void BufferView::gotoLabel(docstring const & label)
2802 {
2803         FuncRequest action;
2804         bool have_inactive = false;
2805         for (Buffer const * buf : buffer().allRelatives()) {
2806                 // find label
2807                 for (TocItem const & item : *buf->tocBackend().toc("label")) {
2808                         if (label == item.str() && item.isOutput()) {
2809                                 lyx::dispatch(item.action());
2810                                 return;
2811                         }
2812                         // If we find an inactive label, save it for the case
2813                         // that no active one is there
2814                         if (label == item.str() && !have_inactive) {
2815                                 have_inactive = true;
2816                                 action = item.action();
2817                         }
2818                 }
2819         }
2820         // We only found an inactive label. Go there.
2821         if (have_inactive)
2822                 lyx::dispatch(action);
2823 }
2824
2825
2826 TextMetrics const & BufferView::textMetrics(Text const * t) const
2827 {
2828         return const_cast<BufferView *>(this)->textMetrics(t);
2829 }
2830
2831
2832 TextMetrics & BufferView::textMetrics(Text const * t)
2833 {
2834         LBUFERR(t);
2835         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
2836         if (tmc_it == d->text_metrics_.end()) {
2837                 tmc_it = d->text_metrics_.emplace(std::piecewise_construct,
2838                                 std::forward_as_tuple(t),
2839                                 std::forward_as_tuple(this, const_cast<Text *>(t))).first;
2840         }
2841         return tmc_it->second;
2842 }
2843
2844
2845 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2846                 pit_type pit) const
2847 {
2848         return textMetrics(t).parMetrics(pit);
2849 }
2850
2851
2852 int BufferView::workHeight() const
2853 {
2854         return height_;
2855 }
2856
2857
2858 void BufferView::setCursor(DocIterator const & dit)
2859 {
2860         d->cursor_.reset();
2861         size_t const n = dit.depth();
2862         for (size_t i = 0; i < n; ++i)
2863                 dit[i].inset().edit(d->cursor_, true);
2864
2865         d->cursor_.setCursor(dit);
2866         d->cursor_.selection(false);
2867         d->cursor_.setCurrentFont();
2868         // FIXME
2869         // It seems on general grounds as if this is probably needed, but
2870         // it is not yet clear.
2871         // See bug #7394 and r38388.
2872         // d->cursor.resetAnchor();
2873 }
2874
2875
2876 void BufferView::setCursorSelectionTo(DocIterator const & dit)
2877 {
2878         size_t const n = dit.depth();
2879         for (size_t i = 0; i < n; ++i)
2880                 dit[i].inset().edit(d->cursor_, true);
2881
2882         d->cursor_.selection(true);
2883         d->cursor_.setCursorSelectionTo(dit);
2884         d->cursor_.setCurrentFont();
2885 }
2886
2887
2888 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2889 {
2890         // Would be wrong to delete anything if we have a selection.
2891         if (cur.selection())
2892                 return false;
2893
2894         bool need_anchor_change = false;
2895         bool changed = Text::deleteEmptyParagraphMechanism(cur, old,
2896                 need_anchor_change);
2897
2898         if (need_anchor_change)
2899                 cur.resetAnchor();
2900
2901         if (!changed)
2902                 return false;
2903
2904         d->cursor_ = cur;
2905
2906         // we would rather not do this here, but it needs to be done before
2907         // the changed() signal is sent.
2908         buffer_.updateBuffer();
2909
2910         buffer_.changed(true);
2911         return true;
2912 }
2913
2914
2915 bool BufferView::mouseSetCursor(Cursor & cur, bool const select)
2916 {
2917         LASSERT(&cur.bv() == this, return false);
2918
2919         if (!select)
2920                 // this event will clear selection so we save selection for
2921                 // persistent selection
2922                 cap::saveSelection(cursor());
2923
2924         d->cursor_.macroModeClose();
2925         // If a macro has been finalized, the cursor might have been broken
2926         cur.fixIfBroken();
2927
2928         // Has the cursor just left the inset?
2929         bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2930         if (leftinset)
2931                 d->cursor_.fixIfBroken();
2932
2933         // do the dEPM magic if needed
2934         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2935         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2936         // the leftinset bool would not be necessary (badcursor instead).
2937         bool update = leftinset;
2938
2939         if (select) {
2940                 d->cursor_.setSelection();
2941                 d->cursor_.setCursorSelectionTo(cur);
2942         } else {
2943                 if (d->cursor_.inTexted())
2944                         update |= checkDepm(cur, d->cursor_);
2945                 d->cursor_.resetAnchor();
2946                 d->cursor_.setCursor(cur);
2947                 d->cursor_.clearSelection();
2948         }
2949         d->cursor_.boundary(cur.boundary());
2950         d->cursor_.finishUndo();
2951         d->cursor_.setCurrentFont();
2952         if (update)
2953                 cur.forceBufferUpdate();
2954         return update;
2955 }
2956
2957
2958 void BufferView::putSelectionAt(DocIterator const & cur,
2959                                 int length, bool backwards)
2960 {
2961         d->cursor_.clearSelection();
2962
2963         setCursor(cur);
2964
2965         if (length) {
2966                 if (backwards) {
2967                         d->cursor_.pos() += length;
2968                         d->cursor_.setSelection(d->cursor_, -length);
2969                 } else
2970                         d->cursor_.setSelection(d->cursor_, length);
2971         }
2972 }
2973
2974
2975 bool BufferView::selectIfEmpty(DocIterator & cur)
2976 {
2977         if ((cur.inTexted() && !cur.paragraph().empty())
2978             || (cur.inMathed() && !cur.cell().empty()))
2979                 return false;
2980
2981         pit_type const beg_pit = cur.pit();
2982         if (beg_pit > 0) {
2983                 // The paragraph associated to this item isn't
2984                 // the first one, so it can be selected
2985                 cur.backwardPos();
2986         } else {
2987                 // We have to resort to select the space between the
2988                 // end of this item and the begin of the next one
2989                 cur.forwardPos();
2990         }
2991         if (cur.empty()) {
2992                 // If it is the only item in the document,
2993                 // nothing can be selected
2994                 return false;
2995         }
2996         pit_type const end_pit = cur.pit();
2997         pos_type const end_pos = cur.pos();
2998         d->cursor_.clearSelection();
2999         d->cursor_.reset();
3000         d->cursor_.setCursor(cur);
3001         d->cursor_.pit() = beg_pit;
3002         d->cursor_.pos() = 0;
3003         d->cursor_.selection(false);
3004         d->cursor_.resetAnchor();
3005         d->cursor_.pit() = end_pit;
3006         d->cursor_.pos() = end_pos;
3007         d->cursor_.setSelection();
3008         return true;
3009 }
3010
3011
3012 Cursor & BufferView::cursor()
3013 {
3014         return d->cursor_;
3015 }
3016
3017
3018 Cursor const & BufferView::cursor() const
3019 {
3020         return d->cursor_;
3021 }
3022
3023
3024 bool BufferView::singleParUpdate()
3025 {
3026         Text & buftext = buffer_.text();
3027         pit_type const bottom_pit = d->cursor_.bottom().pit();
3028         TextMetrics & tm = textMetrics(&buftext);
3029         Dimension const old_dim = tm.parMetrics(bottom_pit).dim();
3030
3031         // make sure inline completion pointer is ok
3032         if (d->inlineCompletionPos_.fixIfBroken())
3033                 d->inlineCompletionPos_ = DocIterator();
3034
3035         // In Single Paragraph mode, rebreak only
3036         // the (main text, not inset!) paragraph containing the cursor.
3037         // (if this paragraph contains insets etc., rebreaking will
3038         // recursively descend)
3039         tm.redoParagraph(bottom_pit);
3040         ParagraphMetrics & pm = tm.parMetrics(bottom_pit);
3041         if (pm.height() != old_dim.height()) {
3042                 // Paragraph height has changed so we cannot proceed to
3043                 // the singlePar optimisation.
3044                 return false;
3045         }
3046         // Since position() points to the baseline of the first row, we
3047         // may have to update it. See ticket #11601 for an example where
3048         // the height does not change but the ascent does.
3049         pm.setPosition(pm.position() - old_dim.ascent() + pm.ascent());
3050
3051         tm.updatePosCache(bottom_pit);
3052
3053         LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
3054                 << " y2: " << pm.position() + pm.descent()
3055                 << " pit: " << bottom_pit
3056                 << " singlepar: 1");
3057         return true;
3058 }
3059
3060
3061 void BufferView::updateMetrics()
3062 {
3063         updateMetrics(d->update_flags_);
3064         d->update_strategy_ = FullScreenUpdate;
3065 }
3066
3067
3068 void BufferView::updateMetrics(Update::flags & update_flags)
3069 {
3070         if (height_ == 0 || width_ == 0)
3071                 return;
3072
3073         Text & buftext = buffer_.text();
3074         pit_type const npit = int(buftext.paragraphs().size());
3075
3076         // Clear out the position cache in case of full screen redraw,
3077         d->coord_cache_.clear();
3078         d->math_rows_.clear();
3079
3080         // Clear out paragraph metrics to avoid having invalid metrics
3081         // in the cache from paragraphs not relayouted below
3082         // The complete text metrics will be redone.
3083         d->text_metrics_.clear();
3084
3085         TextMetrics & tm = textMetrics(&buftext);
3086
3087         // make sure inline completion pointer is ok
3088         if (d->inlineCompletionPos_.fixIfBroken())
3089                 d->inlineCompletionPos_ = DocIterator();
3090
3091         if (d->anchor_pit_ >= npit)
3092                 // The anchor pit must have been deleted...
3093                 d->anchor_pit_ = npit - 1;
3094
3095         // Rebreak anchor paragraph.
3096         tm.redoParagraph(d->anchor_pit_);
3097         ParagraphMetrics & anchor_pm = tm.parMetrics(d->anchor_pit_);
3098
3099         // position anchor
3100         if (d->anchor_pit_ == 0) {
3101                 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
3102
3103                 // Complete buffer visible? Then it's easy.
3104                 if (scrollRange == 0)
3105                         d->anchor_ypos_ = anchor_pm.ascent();
3106                 else {
3107                         // avoid empty space above the first row
3108                         d->anchor_ypos_ = min(d->anchor_ypos_, anchor_pm.ascent());
3109                 }
3110         }
3111         anchor_pm.setPosition(d->anchor_ypos_);
3112         tm.updatePosCache(d->anchor_pit_);
3113
3114         LYXERR(Debug::PAINTING, "metrics: "
3115                 << " anchor pit = " << d->anchor_pit_
3116                 << " anchor ypos = " << d->anchor_ypos_);
3117
3118         // Redo paragraphs above anchor if necessary.
3119         int y1 = d->anchor_ypos_ - anchor_pm.ascent();
3120         // We are now just above the anchor paragraph.
3121         pit_type pit1 = d->anchor_pit_ - 1;
3122         for (; pit1 >= 0 && y1 >= 0; --pit1) {
3123                 tm.redoParagraph(pit1);
3124                 ParagraphMetrics & pm = tm.parMetrics(pit1);
3125                 y1 -= pm.descent();
3126                 // Save the paragraph position in the cache.
3127                 pm.setPosition(y1);
3128                 tm.updatePosCache(pit1);
3129                 y1 -= pm.ascent();
3130         }
3131
3132         // Redo paragraphs below the anchor if necessary.
3133         int y2 = d->anchor_ypos_ + anchor_pm.descent();
3134         // We are now just below the anchor paragraph.
3135         pit_type pit2 = d->anchor_pit_ + 1;
3136         for (; pit2 < npit && y2 <= height_; ++pit2) {
3137                 tm.redoParagraph(pit2);
3138                 ParagraphMetrics & pm = tm.parMetrics(pit2);
3139                 y2 += pm.ascent();
3140                 // Save the paragraph position in the cache.
3141                 pm.setPosition(y2);
3142                 tm.updatePosCache(pit2);
3143                 y2 += pm.descent();
3144         }
3145
3146         LYXERR(Debug::PAINTING, "Metrics: "
3147                 << " anchor pit = " << d->anchor_pit_
3148                 << " anchor ypos = " << d->anchor_ypos_
3149                 << " y1 = " << y1
3150                 << " y2 = " << y2
3151                 << " pit1 = " << pit1
3152                 << " pit2 = " << pit2);
3153
3154         // metrics is done, full drawing is necessary now
3155         update_flags = (update_flags & ~Update::Force) | Update::ForceDraw;
3156
3157         // Now update the positions of insets in the cache.
3158         updatePosCache();
3159
3160         if (lyxerr.debugging(Debug::WORKAREA)) {
3161                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
3162                 d->coord_cache_.dump();
3163         }
3164 }
3165
3166
3167 void BufferView::updatePosCache()
3168 {
3169         // this is the "nodraw" drawing stage: only set the positions of the
3170         // insets in metrics cache.
3171         frontend::NullPainter np;
3172         draw(np, false);
3173 }
3174
3175
3176 void BufferView::insertLyXFile(FileName const & fname, bool const ignorelang)
3177 {
3178         LASSERT(d->cursor_.inTexted(), return);
3179
3180         // Get absolute path of file and add ".lyx"
3181         // to the filename if necessary
3182         FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
3183
3184         docstring const disp_fn = makeDisplayPath(filename.absFileName());
3185         // emit message signal.
3186         message(bformat(_("Inserting document %1$s..."), disp_fn));
3187
3188         docstring res;
3189         Buffer buf(filename.absFileName(), false);
3190         if (buf.loadLyXFile() == Buffer::ReadSuccess) {
3191                 ErrorList & el = buffer_.errorList("Parse");
3192                 // Copy the inserted document error list into the current buffer one.
3193                 el = buf.errorList("Parse");
3194                 ParagraphList & pars = buf.paragraphs();
3195                 if (ignorelang)
3196                         // set main language of imported file to context language
3197                         buf.changeLanguage(buf.language(), d->cursor_.getFont().language());
3198                 buffer_.undo().recordUndo(d->cursor_);
3199                 cap::replaceSelection(d->cursor_);
3200                 cap::pasteParagraphList(d->cursor_, pars,
3201                                         buf.params().documentClassPtr(),
3202                                         buf.params().authors(), el);
3203                 res = _("Document %1$s inserted.");
3204         } else {
3205                 res = _("Could not insert document %1$s");
3206         }
3207
3208         buffer_.changed(true);
3209         // emit message signal.
3210         message(bformat(res, disp_fn));
3211 }
3212
3213
3214 Point BufferView::coordOffset(DocIterator const & dit) const
3215 {
3216         int x = 0;
3217         int y = 0;
3218         int lastw = 0;
3219
3220         // Addup contribution of nested insets, from inside to outside,
3221         // keeping the outer paragraph for a special handling below
3222         for (size_t i = dit.depth() - 1; i >= 1; --i) {
3223                 CursorSlice const & sl = dit[i];
3224                 int xx = 0;
3225                 int yy = 0;
3226
3227                 // get relative position inside sl.inset()
3228                 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
3229
3230                 // Make relative position inside of the edited inset relative to sl.inset()
3231                 x += xx;
3232                 y += yy;
3233
3234                 // In case of an RTL inset, the edited inset will be positioned to the left
3235                 // of xx:yy
3236                 if (sl.text()) {
3237                         bool boundary_i = dit.boundary() && i + 1 == dit.depth();
3238                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
3239                         if (rtl)
3240                                 x -= lastw;
3241                 }
3242
3243                 // remember width for the case that sl.inset() is positioned in an RTL inset
3244                 lastw = sl.inset().dimension(*this).wid;
3245
3246                 //lyxerr << "Cursor::getPos, i: "
3247                 // << i << " x: " << xx << " y: " << y << endl;
3248         }
3249
3250         // Add contribution of initial rows of outermost paragraph
3251         CursorSlice const & sl = dit[0];
3252         TextMetrics const & tm = textMetrics(sl.text());
3253         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
3254
3255         LBUFERR(!pm.rows().empty());
3256         y -= pm.rows()[0].ascent();
3257 #if 1
3258         // FIXME: document this mess
3259         size_t rend;
3260         if (sl.pos() > 0 && dit.depth() == 1) {
3261                 int pos = sl.pos();
3262                 if (pos && dit.boundary())
3263                         --pos;
3264 //              lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
3265                 rend = pm.pos2row(pos);
3266         } else
3267                 rend = pm.pos2row(sl.pos());
3268 #else
3269         size_t rend = pm.pos2row(sl.pos());
3270 #endif
3271         for (size_t rit = 0; rit != rend; ++rit)
3272                 y += pm.rows()[rit].height();
3273         y += pm.rows()[rend].ascent();
3274
3275         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
3276
3277         // Make relative position from the nested inset now bufferview absolute.
3278         int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
3279         x += xx;
3280
3281         // In the RTL case place the nested inset at the left of the cursor in
3282         // the outer paragraph
3283         bool boundary_1 = dit.boundary() && 1 == dit.depth();
3284         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
3285         if (rtl)
3286                 x -= lastw;
3287
3288         return Point(x, y);
3289 }
3290
3291
3292 Point BufferView::getPos(DocIterator const & dit) const
3293 {
3294         if (!paragraphVisible(dit))
3295                 return Point(-1, -1);
3296
3297         CursorSlice const & bot = dit.bottom();
3298         TextMetrics const & tm = textMetrics(bot.text());
3299
3300         // offset from outer paragraph
3301         Point p = coordOffset(dit);
3302         p.y_ += tm.parMetrics(bot.pit()).position();
3303         return p;
3304 }
3305
3306
3307 bool BufferView::paragraphVisible(DocIterator const & dit) const
3308 {
3309         CursorSlice const & bot = dit.bottom();
3310         TextMetrics const & tm = textMetrics(bot.text());
3311
3312         return tm.contains(bot.pit());
3313 }
3314
3315
3316 void BufferView::caretPosAndDim(Point & p, Dimension & dim) const
3317 {
3318         Cursor const & cur = cursor();
3319         if (cur.inMathed()) {
3320                 MathRow const & mrow = mathRow(&cur.cell());
3321                 dim = mrow.caret_dim;
3322         } else {
3323                 Font const font = cur.real_current_font;
3324                 frontend::FontMetrics const & fm = theFontMetrics(font);
3325                 // lineWidth() can be 0 to mean 'thin line' on HiDpi, but the
3326                 // caret drawing code is not prepared for that.
3327                 dim.wid = max(fm.lineWidth(), 1);
3328                 dim.asc = fm.maxAscent();
3329                 dim.des = fm.maxDescent();
3330         }
3331         if (lyxrc.cursor_width > 0)
3332                 dim.wid = lyxrc.cursor_width;
3333
3334         p = getPos(cur);
3335         // center fat carets horizontally
3336         p.x_ -= dim.wid / 2;
3337         // p is top-left
3338         p.y_ -= dim.asc;
3339 }
3340
3341
3342 void BufferView::buildCaretGeometry(bool complet)
3343 {
3344         Point p;
3345         Dimension dim;
3346         caretPosAndDim(p, dim);
3347
3348         Cursor const & cur = d->cursor_;
3349         Font const & realfont = cur.real_current_font;
3350         frontend::FontMetrics const & fm = theFontMetrics(realfont.fontInfo());
3351         bool const isrtl = realfont.isVisibleRightToLeft();
3352         int const dir = isrtl ? -1 : 1;
3353
3354         frontend::CaretGeometry & cg = d->caret_geometry_;
3355         cg.shapes.clear();
3356
3357         // The caret itself, slanted for italics in text edit mode except
3358         // for selections because the selection rect does not slant
3359         bool const slant = fm.italic() && cur.inTexted() && !cur.selection();
3360         double const slope = slant ? fm.italicSlope() : 0;
3361         cg.shapes.push_back(
3362                 {{iround(p.x_ + dim.asc * slope),                 p.y_},
3363                  {iround(p.x_ - dim.des * slope),                 p.y_ + dim.height()},
3364                  {iround(p.x_ + dir * dim.wid - dim.des * slope), p.y_ + dim.height()},
3365                  {iround(p.x_ + dir * dim.wid + dim.asc * slope), p.y_}}
3366                 );
3367
3368         // The language indicator _| (if needed)
3369         Language const * doclang = buffer().params().language;
3370         if (!((realfont.language() == doclang && isrtl == doclang->rightToLeft())
3371                   || realfont.language() == latex_language)) {
3372                 int const lx = dim.height() / 3;
3373                 int const xx = iround(p.x_ - dim.des * slope);
3374                 int const yy = p.y_ + dim.height();
3375                 cg.shapes.push_back(
3376                         {{xx,                            yy - dim.wid},
3377                          {xx + dir * (dim.wid + lx - 1), yy - dim.wid},
3378                          {xx + dir * (dim.wid + lx - 1), yy},
3379                          {xx,                            yy}}
3380                         );
3381         }
3382
3383         // The completion triangle |> (if needed)
3384         if (complet) {
3385                 int const m = p.y_ + dim.height() / 2;
3386                 int const d = dim.height() / 8;
3387                 // offset for slanted carret
3388                 int const sx = iround((dim.asc - (dim.height() / 2 - d)) * slope);
3389                 // starting position x
3390                 int const xx = p.x_ + dir * dim.wid + sx;
3391                 cg.shapes.push_back(
3392                         {{xx,                     m - d},
3393                          {xx + dir * d,           m},
3394                          {xx,                     m + d},
3395                          {xx,                     m + d - dim.wid},
3396                          {xx + dir * d - dim.wid, m},
3397                          {xx,                     m - d + dim.wid}}
3398                         );
3399         }
3400
3401         // compute extremal x values
3402         cg.left = 1000000;
3403         cg.right = -1000000;
3404         cg.top = 1000000;
3405         cg.bottom = -1000000;
3406         for (auto const & shape : cg.shapes)
3407                 for (Point const & p : shape) {
3408                         cg.left = min(cg.left, p.x_);
3409                         cg.right = max(cg.right, p.x_);
3410                         cg.top = min(cg.top, p.y_);
3411                         cg.bottom = max(cg.bottom, p.y_);
3412                 }
3413 }
3414
3415
3416 frontend::CaretGeometry const &  BufferView::caretGeometry() const
3417 {
3418         return d->caret_geometry_;
3419 }
3420
3421
3422 bool BufferView::caretInView() const
3423 {
3424         if (!paragraphVisible(cursor()))
3425                 return false;
3426         Point p;
3427         Dimension dim;
3428         caretPosAndDim(p, dim);
3429
3430         // does the cursor touch the screen ?
3431         if (p.y_ + dim.height() < 0 || p.y_ >= workHeight())
3432                 return false;
3433         return true;
3434 }
3435
3436
3437 int BufferView::horizScrollOffset() const
3438 {
3439         return d->horiz_scroll_offset_;
3440 }
3441
3442
3443 int BufferView::horizScrollOffset(Text const * text,
3444                                   pit_type pit, pos_type pos) const
3445 {
3446         // Is this a row that is currently scrolled?
3447         if (!d->current_row_slice_.empty()
3448             && &text->inset() == d->current_row_slice_.inset().asInsetText()
3449             && pit ==  d->current_row_slice_.pit()
3450             && pos ==  d->current_row_slice_.pos())
3451                 return d->horiz_scroll_offset_;
3452         return 0;
3453 }
3454
3455
3456 void BufferView::setCurrentRowSlice(CursorSlice const & rowSlice)
3457 {
3458         // nothing to do if the cursor was already on this row
3459         if (d->current_row_slice_ == rowSlice)
3460                 return;
3461
3462         // if the (previous) current row was scrolled, we have to
3463         // remember it in order to repaint it next time.
3464         if (d->horiz_scroll_offset_ != 0) {
3465                 // search the old row in cache and mark it changed
3466                 for (auto & tm_pair : d->text_metrics_) {
3467                         if (&tm_pair.first->inset() == rowSlice.inset().asInsetText()) {
3468                                 tm_pair.second.setRowChanged(rowSlice.pit(), rowSlice.pos());
3469                                 // We found it, no need to continue.
3470                                 break;
3471                         }
3472                 }
3473         }
3474
3475         // Since we changed row, the scroll offset is not valid anymore
3476         d->horiz_scroll_offset_ = 0;
3477         d->current_row_slice_ = rowSlice;
3478 }
3479
3480
3481 void BufferView::checkCursorScrollOffset()
3482 {
3483         CursorSlice rowSlice = d->cursor_.bottom();
3484         TextMetrics const & tm = textMetrics(rowSlice.text());
3485
3486         // Stop if metrics have not been computed yet, since it means
3487         // that there is nothing to do.
3488         if (!tm.contains(rowSlice.pit()))
3489                 return;
3490         ParagraphMetrics const & pm = tm.parMetrics(rowSlice.pit());
3491         Row const & row = pm.getRow(rowSlice.pos(),
3492                                     d->cursor_.boundary() && rowSlice == d->cursor_.top());
3493         rowSlice.pos() = row.pos();
3494
3495         // Set the row on which the cursor lives.
3496         setCurrentRowSlice(rowSlice);
3497
3498         // Current x position of the cursor in pixels
3499         int cur_x = getPos(d->cursor_).x_;
3500
3501         // Horizontal scroll offset of the cursor row in pixels
3502         int offset = d->horiz_scroll_offset_;
3503         int const MARGIN = 2 * theFontMetrics(d->cursor_.real_current_font).em()
3504                            + row.right_margin;
3505         if (row.right_x() <= workWidth() - row.right_margin) {
3506                 // Row is narrower than the work area, no offset needed.
3507                 offset = 0;
3508         } else {
3509                 if (cur_x - offset < MARGIN) {
3510                         // cursor would be too far right
3511                         offset = cur_x - MARGIN;
3512                 } else if (cur_x - offset > workWidth() - MARGIN) {
3513                         // cursor would be too far left
3514                         offset = cur_x - workWidth() + MARGIN;
3515                 }
3516                 // Correct the offset to make sure that we do not scroll too much
3517                 if (offset < 0)
3518                         offset = 0;
3519                 if (row.right_x() - offset < workWidth() - row.right_margin)
3520                         offset = row.right_x() - workWidth() + row.right_margin;
3521         }
3522
3523         //lyxerr << "cur_x=" << cur_x << ", offset=" << offset << ", row.wid=" << row.width() << ", margin=" << MARGIN << endl;
3524
3525         if (offset != d->horiz_scroll_offset_) {
3526                 LYXERR(Debug::PAINTING, "Horiz. scroll offset changed from "
3527                        << d->horiz_scroll_offset_ << " to " << offset);
3528                 row.changed(true);
3529                 if (d->update_strategy_ == NoScreenUpdate)
3530                         d->update_strategy_ = SingleParUpdate;
3531         }
3532
3533         d->horiz_scroll_offset_ = offset;
3534 }
3535
3536
3537 bool BufferView::busy() const
3538 {
3539         return buffer().undo().activeUndoGroup();
3540 }
3541
3542
3543 void BufferView::draw(frontend::Painter & pain, bool paint_caret)
3544 {
3545         if (height_ == 0 || width_ == 0)
3546                 return;
3547         LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t--- START NODRAW ---"
3548                                  : "\t\t*** START DRAWING ***"));
3549         Text & text = buffer_.text();
3550         TextMetrics const & tm = d->text_metrics_[&text];
3551         int const y = tm.first().second->position();
3552         PainterInfo pi(this, pain);
3553
3554         // Check whether the row where the cursor lives needs to be scrolled.
3555         // Update the drawing strategy if needed.
3556         checkCursorScrollOffset();
3557
3558         switch (d->update_strategy_) {
3559
3560         case NoScreenUpdate:
3561                 // no screen painting is actually needed. In nodraw stage
3562                 // however, the different coordinates of insets and paragraphs
3563                 // needs to be updated.
3564                 LYXERR(Debug::PAINTING, "Strategy: NoScreenUpdate");
3565                 if (pain.isNull()) {
3566                         pi.full_repaint = true;
3567                         tm.draw(pi, 0, y);
3568                 } else {
3569                         pi.full_repaint = false;
3570                         tm.draw(pi, 0, y);
3571                 }
3572                 break;
3573
3574         case SingleParUpdate:
3575                 pi.full_repaint = false;
3576                 LYXERR(Debug::PAINTING, "Strategy: SingleParUpdate");
3577                 // In general, only the current row of the outermost paragraph
3578                 // will be redrawn. Particular cases where selection spans
3579                 // multiple paragraph are correctly detected in TextMetrics.
3580                 tm.draw(pi, 0, y);
3581                 break;
3582
3583         case DecorationUpdate:
3584                 // FIXME: We should also distinguish DecorationUpdate to avoid text
3585                 // drawing if possible. This is not possible to do easily right now
3586                 // because of the single backing pixmap.
3587
3588         case FullScreenUpdate:
3589
3590                 LYXERR(Debug::PAINTING,
3591                        ((d->update_strategy_ == FullScreenUpdate)
3592                         ? "Strategy: FullScreenUpdate"
3593                         : "Strategy: DecorationUpdate"));
3594
3595                 // The whole screen, including insets, will be refreshed.
3596                 pi.full_repaint = true;
3597
3598                 // Clear background.
3599                 pain.fillRectangle(0, 0, width_, height_,
3600                         pi.backgroundColor(&buffer_.inset()));
3601
3602                 // Draw everything.
3603                 tm.draw(pi, 0, y);
3604
3605                 // and possibly grey out below
3606                 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3607                 int const y2 = lastpm.second->position() + lastpm.second->descent();
3608
3609                 if (y2 < height_) {
3610                         Color color = buffer().isInternal()
3611                                 ? Color_background : Color_bottomarea;
3612                         pain.fillRectangle(0, y2, width_, height_ - y2, color);
3613                 }
3614                 break;
3615         }
3616         LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t --- END NODRAW ---"
3617                                 : "\t\t *** END DRAWING ***"));
3618
3619         // The scrollbar needs an update.
3620         // FIXME: does it always? see ticket #11947.
3621         updateScrollbarParameters();
3622
3623         // Normalize anchor for next time
3624         pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
3625         pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3626         for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
3627                 ParagraphMetrics const & pm = tm.parMetrics(pit);
3628                 if (pm.position() + pm.descent() > 0) {
3629                         if (d->anchor_pit_ != pit
3630                             || d->anchor_ypos_ != pm.position())
3631                                 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
3632                                        << "  anchor ypos = " << d->anchor_ypos_);
3633                         d->anchor_pit_ = pit;
3634                         d->anchor_ypos_ = pm.position();
3635                         break;
3636                 }
3637         }
3638         if (!pain.isNull()) {
3639                 // reset the update flags, everything has been done
3640                 d->update_flags_ = Update::None;
3641         }
3642
3643         // If a caret has to be painted, mark its text row as dirty to
3644         //make sure that it will be repainted on next redraw.
3645         /* FIXME: investigate whether this can be avoided when the cursor did not
3646          * move at all
3647          */
3648         if (paint_caret) {
3649                 Cursor cur(d->cursor_);
3650                 while (cur.depth() > 1) {
3651                         if (!cur.inTexted())
3652                                 break;
3653                         TextMetrics const & tm = textMetrics(cur.text());
3654                         if (d->caret_geometry_.left >= tm.origin().x_
3655                                 && d->caret_geometry_.right <= tm.origin().x_ + tm.dim().width())
3656                                 break;
3657                         cur.pop();
3658                 }
3659                 cur.textRow().changed(true);
3660         }
3661 }
3662
3663
3664 void BufferView::message(docstring const & msg)
3665 {
3666         if (d->gui_)
3667                 d->gui_->message(msg);
3668 }
3669
3670
3671 void BufferView::showDialog(string const & name)
3672 {
3673         if (d->gui_)
3674                 d->gui_->showDialog(name, string());
3675 }
3676
3677
3678 void BufferView::showDialog(string const & name,
3679         string const & data, Inset * inset)
3680 {
3681         if (d->gui_)
3682                 d->gui_->showDialog(name, data, inset);
3683 }
3684
3685
3686 void BufferView::updateDialog(string const & name, string const & data)
3687 {
3688         if (d->gui_)
3689                 d->gui_->updateDialog(name, data);
3690 }
3691
3692
3693 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
3694 {
3695         d->gui_ = gui;
3696 }
3697
3698
3699 // FIXME: Move this out of BufferView again
3700 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
3701 {
3702         if (!fname.isReadableFile()) {
3703                 docstring const error = from_ascii(strerror(errno));
3704                 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3705                 docstring const text =
3706                   bformat(_("Could not read the specified document\n"
3707                             "%1$s\ndue to the error: %2$s"), file, error);
3708                 Alert::error(_("Could not read file"), text);
3709                 return docstring();
3710         }
3711
3712         if (!fname.isReadableFile()) {
3713                 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3714                 docstring const text =
3715                   bformat(_("%1$s\n is not readable."), file);
3716                 Alert::error(_("Could not open file"), text);
3717                 return docstring();
3718         }
3719
3720         // FIXME UNICODE: We don't know the encoding of the file
3721         docstring file_content = fname.fileContents("UTF-8");
3722         if (file_content.empty()) {
3723                 Alert::error(_("Reading not UTF-8 encoded file"),
3724                              _("The file is not UTF-8 encoded.\n"
3725                                "It will be read as local 8Bit-encoded.\n"
3726                                "If this does not give the correct result\n"
3727                                "then please change the encoding of the file\n"
3728                                "to UTF-8 with a program other than LyX.\n"));
3729                 file_content = fname.fileContents("local8bit");
3730         }
3731
3732         return normalize_c(file_content);
3733 }
3734
3735
3736 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
3737 {
3738         docstring const tmpstr = contentsOfPlaintextFile(f);
3739
3740         if (tmpstr.empty())
3741                 return;
3742
3743         Cursor & cur = cursor();
3744         cap::replaceSelection(cur);
3745         buffer_.undo().recordUndo(cur);
3746         if (asParagraph)
3747                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3748         else
3749                 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3750
3751         buffer_.changed(true);
3752 }
3753
3754
3755 docstring const & BufferView::inlineCompletion() const
3756 {
3757         return d->inlineCompletion_;
3758 }
3759
3760
3761 size_t BufferView::inlineCompletionUniqueChars() const
3762 {
3763         return d->inlineCompletionUniqueChars_;
3764 }
3765
3766
3767 DocIterator const & BufferView::inlineCompletionPos() const
3768 {
3769         return d->inlineCompletionPos_;
3770 }
3771
3772
3773 void BufferView::resetInlineCompletionPos()
3774 {
3775         d->inlineCompletionPos_ = DocIterator();
3776 }
3777
3778
3779 bool samePar(DocIterator const & a, DocIterator const & b)
3780 {
3781         if (a.empty() && b.empty())
3782                 return true;
3783         if (a.empty() || b.empty())
3784                 return false;
3785         if (a.depth() != b.depth())
3786                 return false;
3787         return &a.innerParagraph() == &b.innerParagraph();
3788 }
3789
3790
3791 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3792         docstring const & completion, size_t uniqueChars)
3793 {
3794         uniqueChars = min(completion.size(), uniqueChars);
3795         bool changed = d->inlineCompletion_ != completion
3796                 || d->inlineCompletionUniqueChars_ != uniqueChars;
3797         bool singlePar = true;
3798         d->inlineCompletion_ = completion;
3799         d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3800
3801         //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3802
3803         // at new position?
3804         DocIterator const & old = d->inlineCompletionPos_;
3805         if (old != pos) {
3806                 //lyxerr << "inlineCompletionPos changed" << std::endl;
3807                 // old or pos are in another paragraph?
3808                 if ((!samePar(cur, pos) && !pos.empty())
3809                     || (!samePar(cur, old) && !old.empty())) {
3810                         singlePar = false;
3811                         //lyxerr << "different paragraph" << std::endl;
3812                 }
3813                 d->inlineCompletionPos_ = pos;
3814         }
3815
3816         // set update flags
3817         if (changed) {
3818                 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3819                         cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3820                 else
3821                         cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3822         }
3823 }
3824
3825
3826 bool BufferView::clickableInset() const
3827 {
3828         return d->clickable_inset_;
3829 }
3830
3831 } // namespace lyx