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