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