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