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