3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
19 #include "BranchList.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BiblioInfo.h"
24 #include "CoordCache.h"
26 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
29 #include "FuncRequest.h"
30 #include "FuncStatus.h"
33 #include "LayoutFile.h"
36 #include "LyXAction.h"
39 #include "MetricsInfo.h"
40 #include "Paragraph.h"
42 #include "texstream.h"
44 #include "TextMetrics.h"
46 #include "TocBackend.h"
48 #include "insets/InsetBibtex.h"
49 #include "insets/InsetCitation.h"
50 #include "insets/InsetCommand.h" // ChangeRefs
51 #include "insets/InsetGraphics.h"
52 #include "insets/InsetIndex.h"
53 #include "insets/InsetRef.h"
54 #include "insets/InsetText.h"
56 #include "mathed/InsetMathNest.h"
57 #include "mathed/InsetMathRef.h"
58 #include "mathed/MathData.h"
59 #include "mathed/MathRow.h"
61 #include "frontends/alert.h"
62 #include "frontends/CaretGeometry.h"
63 #include "frontends/Delegates.h"
64 #include "frontends/FontMetrics.h"
65 #include "frontends/NullPainter.h"
66 #include "frontends/Painter.h"
67 #include "frontends/Selection.h"
68 #include "frontends/Clipboard.h"
70 #include "support/convert.h"
71 #include "support/debug.h"
72 #include "support/docstring.h"
73 #include "support/docstring_list.h"
74 #include "support/filetools.h"
75 #include "support/gettext.h"
76 #include "support/lassert.h"
77 #include "support/Length.h"
78 #include "support/lstrings.h"
79 #include "support/lyxlib.h"
80 #include "support/types.h"
92 using namespace lyx::support;
96 namespace Alert = frontend::Alert;
100 /// Return an inset of this class if it exists at the current cursor position
102 T * getInsetByCode(Cursor const & cur, InsetCode code)
104 DocIterator it = cur;
105 Inset * inset = it.nextInset();
106 if (inset && inset->lyxCode() == code)
107 return static_cast<T*>(inset);
112 /// Note that comparing contents can only be used for InsetCommand
113 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
114 docstring const & contents)
116 DocIterator tmpdit = dit;
119 Inset const * inset = tmpdit.nextInset();
121 bool const valid_code = std::find(codes.begin(), codes.end(),
122 inset->lyxCode()) != codes.end();
123 InsetCommand const * ic = inset->asInsetCommand();
124 bool const same_or_no_contents = contents.empty()
125 || (ic && (ic->getFirstNonOptParam() == contents));
127 if (valid_code && same_or_no_contents) {
132 tmpdit.forwardInset();
139 /// Looks for next inset with one of the given codes.
140 /// Note that same_content can only be used for InsetCommand
141 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
145 DocIterator tmpdit = dit;
146 tmpdit.forwardInset();
150 Inset const * inset = tmpdit.nextInset();
151 if (same_content && inset) {
152 InsetCommand const * ic = inset->asInsetCommand();
154 bool const valid_code = std::find(codes.begin(), codes.end(),
155 ic->lyxCode()) != codes.end();
157 contents = ic->getFirstNonOptParam();
161 if (!findNextInset(tmpdit, codes, contents)) {
162 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
163 inset = &tmpdit.bottom().inset();
164 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
165 if (!findNextInset(tmpdit, codes, contents))
177 /// Moves cursor to the next inset with one of the given codes.
178 bool gotoInset(BufferView * bv, vector<InsetCode> const & codes,
181 Cursor tmpcur = bv->cursor();
182 if (!findInset(tmpcur, codes, same_content)) {
183 bv->cursor().message(_("No more insets"));
187 tmpcur.clearSelection();
188 bv->setCursor(tmpcur);
189 return bv->scrollToCursor(bv->cursor(), SCROLL_TOP);
193 /// A map from a Text to the associated text metrics
194 typedef map<Text const *, TextMetrics> TextMetricsCache;
196 enum ScreenUpdateStrategy {
206 /////////////////////////////////////////////////////////////////////
210 /////////////////////////////////////////////////////////////////////
212 struct BufferView::Private
214 Private(BufferView & bv) :
215 update_strategy_(FullScreenUpdate),
216 update_flags_(Update::Force),
217 cursor_(bv), anchor_pit_(0), anchor_ypos_(0),
218 wh_(0), inlineCompletionUniqueChars_(0),
219 last_inset_(nullptr), mouse_position_cache_(),
220 gui_(nullptr), bookmark_edit_position_(-1),
221 horiz_scroll_offset_(0), clickable_inset_(false)
223 xsel_cache_.set = false;
227 ScrollbarParameters scrollbarParameters_;
229 ScreenUpdateStrategy update_strategy_;
231 Update::flags update_flags_;
233 CoordCache coord_cache_;
235 typedef unordered_map<MathData const *, MathRow> MathRows;
238 /// this is used to handle XSelection events in the right manner.
247 pit_type anchor_pit_;
250 /// Estimated average par height for scrollbar.
253 vector<int> par_height_;
256 DocIterator inlineCompletionPos_;
258 docstring inlineCompletion_;
260 size_t inlineCompletionUniqueChars_;
262 /// keyboard mapping object.
265 /// last visited inset.
266 /** kept to send setMouseHover(false).
267 * Not owned, so don't delete.
269 Inset const * last_inset_;
271 /// position of the mouse at the time of the last mouse move
272 /// This is used to update the hovering status of inset in
273 /// cases where the buffer is scrolled, but the mouse didn't move.
274 Point mouse_position_cache_;
276 mutable TextMetricsCache text_metrics_;
279 /** Not owned, so don't delete.
281 frontend::GuiBufferViewDelegate * gui_;
284 map<string, Inset *> edited_insets_;
286 /// When the row where the cursor lies is scrolled, this
287 /// contains the scroll offset
288 // cache for id of the paragraph which was edited the last time
289 int bookmark_edit_position_;
291 int horiz_scroll_offset_;
292 /// a slice pointing to the start of the row where the cursor
293 /// is (at last draw time)
294 CursorSlice current_row_slice_;
295 /// are we hovering something that we can click
296 bool clickable_inset_;
297 /// shape of the caret
298 frontend::CaretGeometry caret_geometry_;
300 bool mouse_selecting_ = false;
304 BufferView::BufferView(Buffer & buf)
305 : width_(0), height_(0), full_screen_(false), buffer_(buf),
306 d(new Private(*this))
308 d->xsel_cache_.set = false;
309 d->intl_.initKeyMapper(lyxrc.use_kbmap);
311 d->cursor_.setBuffer(&buf);
312 d->cursor_.push(buffer_.inset());
313 d->cursor_.resetAnchor();
314 d->cursor_.setCurrentFont();
316 buffer_.updatePreviews();
320 BufferView::~BufferView()
322 // current buffer is going to be switched-off, save cursor pos
323 // Ideally, the whole cursor stack should be saved, but session
324 // currently can only handle bottom (whole document) level pit and pos.
325 // That is to say, if a cursor is in a nested inset, it will be
326 // restore to the left of the top level inset.
327 LastFilePosSection::FilePos fp;
328 fp.file = buffer_.fileName();
329 fp.pit = d->cursor_.bottom().pit();
330 fp.pos = d->cursor_.bottom().pos();
331 theSession().lastFilePos().save(fp);
334 d->last_inset_->setMouseHover(this, false);
340 int BufferView::defaultMargin() const
342 // The value used to be hardcoded to 10
343 return zoomedPixels(20);
347 int BufferView::rightMargin() const
349 const int screen_width = inPixels(lyxrc.screen_width);
351 // The additional test for the case the outliner is opened.
352 if (!lyxrc.screen_limit || width_ < screen_width + 2 * defaultMargin()) {
353 return defaultMargin();
355 return (width_ - screen_width) / 2;
360 int BufferView::leftMargin() const
362 return rightMargin();
366 int BufferView::topMargin() const
368 // Original value was 20px at 100dpi. For internal buffers like in
369 // advanced search and replace, a value of 5px is enough.
370 return zoomedPixels(buffer().isInternal() ? 5 : 20);
374 int BufferView::bottomMargin() const
380 int BufferView::inPixels(Length const & len) const
382 Font const font = buffer().params().getFont();
383 return len.inPixels(workWidth(), theFontMetrics(font).em());
387 int BufferView::zoomedPixels(int pix) const
389 // FIXME: the dpi setting should really depend on the BufferView
390 // (think different monitors).
392 // Zoom factor specified by user in percent
393 double const zoom = lyxrc.currentZoom / 100.0; // [percent]
395 // DPI setting for monitor relative to 100dpi
396 double const dpizoom = lyxrc.dpi / 100.0; // [per 100dpi]
398 return support::iround(pix * zoom * dpizoom);
402 bool BufferView::isTopScreen() const
404 return 0 == d->scrollbarParameters_.min;
408 bool BufferView::isBottomScreen() const
410 return 0 == d->scrollbarParameters_.max;
414 Intl & BufferView::getIntl()
420 Intl const & BufferView::getIntl() const
426 CoordCache & BufferView::coordCache()
428 return d->coord_cache_;
432 CoordCache const & BufferView::coordCache() const
434 return d->coord_cache_;
438 MathRow const & BufferView::mathRow(MathData const * cell) const
440 auto it = d->math_rows_.find(cell);
441 LATTEST(it != d->math_rows_.end());
446 void BufferView::setMathRow(MathData const * cell, MathRow const & mrow)
448 d->math_rows_[cell] = mrow;
452 Buffer & BufferView::buffer()
458 Buffer const & BufferView::buffer() const
464 docstring const & BufferView::searchRequestCache() const
466 return theClipboard().getFindBuffer();
470 void BufferView::setSearchRequestCache(docstring const & text)
478 docstring const search = string2find(text, casesensitive, matchword,
479 forward, wrap, instant, onlysel);
480 theClipboard().setFindBuffer(search);
484 bool BufferView::needsFitCursor() const
486 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
487 frontend::FontMetrics const & fm =
488 theFontMetrics(d->cursor_.getFont().fontInfo());
489 int const asc = fm.maxAscent();
490 int const des = fm.maxDescent();
491 Point const p = getPos(d->cursor_);
492 if (p.y_ - asc >= 0 && p.y_ + des < height_)
501 // this is for debugging only.
502 string flagsAsString(Update::flags flags)
504 if (flags == Update::None)
506 return string((flags & Update::FitCursor) ? "FitCursor " : "")
507 + ((flags & Update::Force) ? "Force " : "")
508 + ((flags & Update::ForceDraw) ? "ForceDraw " : "")
509 + ((flags & Update::SinglePar) ? "SinglePar " : "")
510 + ((flags & Update::Decoration) ? "Decoration " : "");
515 void BufferView::processUpdateFlags(Update::flags flags)
517 LYXERR(Debug::PAINTING, "BufferView::processUpdateFlags( "
518 << flagsAsString(flags) << ") buffer: " << &buffer_);
520 // Case when no explicit update is requested.
521 if (flags == Update::None)
524 /* FIXME We would like to avoid doing this here, since it is very
525 * expensive and is called in updateBuffer already. However, even
526 * inserting a plain character can invalidate the overly fragile
527 * tables of child documents built by updateMacros. Some work is
528 * needed to avoid doing that when not necessary.
530 buffer_.updateMacros();
532 // First check whether the metrics and inset positions should be updated
533 if (flags & Update::Force) {
534 // This will update the CoordCache items and replace Force
535 // with ForceDraw in flags.
536 updateMetrics(flags);
539 // Detect whether we can only repaint a single paragraph (if we
540 // are not already redrawing all).
541 // We handle this before FitCursor because the later will require
542 // correct metrics at cursor position.
543 if (!(flags & Update::ForceDraw)
544 && (flags & Update::SinglePar)
545 && !singleParUpdate())
546 updateMetrics(flags);
548 // Then make sure that the screen contains the cursor if needed
549 if (flags & Update::FitCursor) {
550 if (needsFitCursor()) {
551 // First try to make the selection start visible
552 // (which is just the cursor when there is no selection)
553 scrollToCursor(d->cursor_.selectionBegin(), SCROLL_VISIBLE);
554 // Metrics have to be recomputed (maybe again)
556 // Is the cursor visible? (only useful if cursor is at end of selection)
557 if (needsFitCursor()) {
558 // then try to make cursor visible instead
559 scrollToCursor(d->cursor_, SCROLL_VISIBLE);
560 // Metrics have to be recomputed (maybe again)
561 updateMetrics(flags);
564 flags = flags & ~Update::FitCursor;
567 // Add flags to the the update flags. These will be reset to None
568 // after the redraw is actually done
569 d->update_flags_ = d->update_flags_ | flags;
570 LYXERR(Debug::PAINTING, "Cumulative flags: " << flagsAsString(flags));
572 // Now compute the update strategy
573 // Possibly values in flag are None, SinglePar, Decoration, ForceDraw
574 LATTEST((d->update_flags_ & ~(Update::None | Update::SinglePar
575 | Update::Decoration | Update::ForceDraw)) == 0);
577 if (d->update_flags_ & Update::ForceDraw)
578 d->update_strategy_ = FullScreenUpdate;
579 else if (d->update_flags_ & Update::Decoration)
580 d->update_strategy_ = DecorationUpdate;
581 else if (d->update_flags_ & Update::SinglePar)
582 d->update_strategy_ = SingleParUpdate;
584 // no need to redraw anything.
585 d->update_strategy_ = NoScreenUpdate;
588 updateHoveredInset();
591 buffer_.changed(false);
595 void BufferView::updateScrollbarParameters()
597 if (height_ == 0 && width_ == 0)
600 // We prefer fixed size line scrolling.
601 d->scrollbarParameters_.single_step = defaultRowHeight();
602 // We prefer full screen page scrolling.
603 d->scrollbarParameters_.page_step = height_;
605 Text & t = buffer_.text();
606 TextMetrics & tm = d->text_metrics_[&t];
608 LYXERR(Debug::SCROLLING, " Updating scrollbar: height: "
609 << t.paragraphs().size()
610 << " curr par: " << d->cursor_.bottom().pit()
611 << " default height " << defaultRowHeight());
613 size_t const parsize = t.paragraphs().size();
614 if (d->par_height_.size() != parsize) {
615 d->par_height_.clear();
616 // FIXME: We assume a default paragraph height of 2 rows. This
617 // should probably be pondered with the screen width.
618 d->par_height_.resize(parsize, defaultRowHeight() * 2);
621 // Look at paragraph heights on-screen
622 pair<pit_type, ParagraphMetrics const *> first = tm.first();
623 pair<pit_type, ParagraphMetrics const *> last = tm.last();
624 for (pit_type pit = first.first; pit <= last.first; ++pit) {
625 d->par_height_[pit] = tm.parMetrics(pit).height();
626 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
627 << d->par_height_[pit]);
630 int top_pos = first.second->position() - first.second->ascent();
631 int bottom_pos = last.second->position() + last.second->descent();
632 bool first_visible = first.first == 0 && top_pos >= 0;
633 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
634 if (first_visible && last_visible) {
635 d->scrollbarParameters_.min = 0;
636 d->scrollbarParameters_.max = 0;
640 d->scrollbarParameters_.min = top_pos;
641 for (size_t i = 0; i != size_t(first.first); ++i)
642 d->scrollbarParameters_.min -= d->par_height_[i];
643 d->scrollbarParameters_.max = bottom_pos;
644 for (size_t i = last.first + 1; i != parsize; ++i)
645 d->scrollbarParameters_.max += d->par_height_[i];
647 // The reference is the top position so we remove one page.
648 if (lyxrc.scroll_below_document)
649 d->scrollbarParameters_.max -= minVisiblePart();
651 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
653 // 0 must be inside the range as it denotes the current position
654 if (d->scrollbarParameters_.max < 0)
655 d->scrollbarParameters_.max = 0;
656 if (d->scrollbarParameters_.min > 0)
657 d->scrollbarParameters_.min = 0;
661 ScrollbarParameters const & BufferView::scrollbarParameters() const
663 return d->scrollbarParameters_;
667 docstring BufferView::toolTip(int x, int y) const
669 // Get inset under mouse, if there is one.
670 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
672 // No inset, no tooltip...
674 return covering_inset->toolTip(*this, x, y);
678 string BufferView::contextMenu(int x, int y) const
680 //If there is a selection, return the containing inset menu
681 if (d->cursor_.selection())
682 return d->cursor_.inset().contextMenu(*this, x, y);
684 // Get inset under mouse, if there is one.
685 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
686 if (covering_inset) {
687 if (covering_inset->asInsetMath()) {
688 CoordCache::Insets const & inset_cache =
689 coordCache().getInsets();
690 Inset const * inner_inset = mathContextMenu(
691 covering_inset->asInsetMath()->asNestInset(),
694 return inner_inset->contextMenu(*this, x, y);
696 return covering_inset->contextMenu(*this, x, y);
699 return buffer_.inset().contextMenu(*this, x, y);
703 Inset const * BufferView::mathContextMenu(InsetMathNest const * inset,
704 CoordCache::Insets const & inset_cache, int x, int y) const
706 for (size_t i = 0; i < inset->nargs(); ++i) {
707 MathData const & ar = inset->cell(i);
708 for (size_t j = 0; j < ar.size(); ++j) {
709 string const name = lyxerr.debugging(Debug::MATHED)
710 ? insetName(ar[j].nucleus()->lyxCode())
712 LYXERR(Debug::MATHED, "Examining inset: " << name);
713 if (!ar[j].nucleus()->contextMenuName().empty()) {
714 if (inset_cache.covers(ar[j].nucleus(), x, y)) {
715 LYXERR(Debug::MATHED, "Hit inset: "
717 return ar[j].nucleus();
720 InsetMathNest const * imn =
721 ar[j].nucleus()->asNestInset();
723 Inset const * inner =
724 mathContextMenu(imn, inset_cache, x, y);
734 void BufferView::scrollDocView(int const pixels, bool update)
736 // The scrollbar values are relative to the top of the screen, therefore the
737 // offset is equal to the target value.
739 // No scrolling at all? No need to redraw anything
743 // If the offset is less than 2 screen height, prefer to scroll instead.
744 if (abs(pixels) <= 2 * height_) {
745 d->anchor_ypos_ -= pixels;
746 processUpdateFlags(Update::Force);
750 // cut off at the top
751 if (pixels <= d->scrollbarParameters_.min) {
752 DocIterator dit = doc_iterator_begin(&buffer_);
753 showCursor(dit, SCROLL_VISIBLE, update);
754 LYXERR(Debug::SCROLLING, "scroll to top");
758 // cut off at the bottom
759 if (pixels >= d->scrollbarParameters_.max) {
760 DocIterator dit = doc_iterator_end(&buffer_);
762 showCursor(dit, SCROLL_VISIBLE, update);
763 LYXERR(Debug::SCROLLING, "scroll to bottom");
767 // find paragraph at target position
768 int par_pos = d->scrollbarParameters_.min;
770 for (; i != int(d->par_height_.size()); ++i) {
771 par_pos += d->par_height_[i];
772 if (par_pos >= pixels)
776 if (par_pos < pixels) {
777 // It seems we didn't find the correct pit so stay on the safe side and
779 LYXERR0("scrolling position not found!");
780 scrollDocView(d->scrollbarParameters_.max, update);
784 DocIterator dit = doc_iterator_begin(&buffer_);
786 LYXERR(Debug::SCROLLING, "pixels = " << pixels << " -> scroll to pit " << i);
787 showCursor(dit, SCROLL_VISIBLE, update);
791 // FIXME: this method is not working well.
792 void BufferView::setCursorFromScrollbar()
794 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
796 int const height = 2 * defaultRowHeight();
797 int const first = height;
798 int const last = height_ - height;
800 Cursor const & oldcur = d->cursor_;
802 switch (cursorStatus(oldcur)) {
810 int const y = getPos(oldcur).y_;
811 newy = min(last, max(y, first));
815 // We reset the cursor because cursorStatus() does not
816 // work when the cursor is within mathed.
819 tm.setCursorFromCoordinates(cur, 0, newy);
821 // update the bufferview cursor and notify insets
822 // FIXME: Care about the d->cursor_ flags to redraw if needed
823 Cursor old = d->cursor_;
825 // the DEPM call in mouseSetCursor() might have destroyed the
826 // paragraph the cursor is in.
827 bool badcursor = old.fixIfBroken();
828 badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
830 d->cursor_.fixIfBroken();
834 Change const BufferView::getCurrentChange() const
836 if (!d->cursor_.selection())
837 return Change(Change::UNCHANGED);
839 DocIterator dit = d->cursor_.selectionBegin();
840 // The selected content might have been changed (see #7685)
841 dit = dit.getInnerText();
842 return dit.paragraph().lookupChange(dit.pos());
846 // this could be used elsewhere as well?
847 // FIXME: This does not work within mathed!
848 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
850 Point const p = getPos(dit);
853 if (p.y_ > workHeight())
859 void BufferView::bookmarkEditPosition()
861 // Don't eat cpu time for each keystroke
862 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
865 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
869 void BufferView::saveBookmark(unsigned int idx)
871 if (buffer().isInternal())
874 // tentatively save bookmark, id and pos will be used to
875 // acturately locate a bookmark in a 'live' lyx session.
876 // pit and pos will be updated with bottom level pit/pos
878 theSession().bookmarks().save(
880 d->cursor_.bottom().pit(),
881 d->cursor_.bottom().pos(),
882 d->cursor_.paragraph().id(),
887 // emit message signal.
888 message(_("Save bookmark"));
892 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
893 int top_id, pos_type top_pos)
895 bool success = false;
898 d->cursor_.clearSelection();
900 // if a valid par_id is given, try it first
901 // This is the case for a 'live' bookmark when unique paragraph ID
902 // is used to track bookmarks.
904 dit = buffer_.getParFromID(top_id);
906 dit.pos() = min(dit.paragraph().size(), top_pos);
907 // Some slices of the iterator may not be
908 // reachable (e.g. closed collapsible inset)
909 // so the dociterator may need to be
910 // shortened. Otherwise, setCursor may crash
911 // lyx when the cursor can not be set to these
913 size_t const n = dit.depth();
914 for (size_t i = 0; i < n; ++i)
915 if (!dit[i].inset().editable()) {
923 // if top_id == 0, or searching through top_id failed
924 // This is the case for a 'restored' bookmark when only bottom
925 // (document level) pit was saved. Because of this, bookmark
926 // restoration is inaccurate. If a bookmark was within an inset,
927 // it will be restored to the left of the outmost inset that contains
929 if (!success && bottom_pit < int(buffer_.paragraphs().size())) {
930 dit = doc_iterator_begin(&buffer_);
932 dit.pit() = bottom_pit;
933 dit.pos() = min(bottom_pos, dit.paragraph().size());
938 // Note: only bottom (document) level pit is set.
940 // set the current font.
941 d->cursor_.setCurrentFont();
942 // Do not forget to reset the anchor (see #9912)
943 d->cursor_.resetAnchor();
944 processUpdateFlags(Update::Force | Update::FitCursor);
951 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
953 if (d->cursor_.real_current_font.isRightToLeft()) {
954 if (d->intl_.keymap == Intl::PRIMARY)
955 d->intl_.keyMapSec();
957 if (d->intl_.keymap == Intl::SECONDARY)
958 d->intl_.keyMapPrim();
961 d->intl_.getTransManager().translateAndInsert(c, t, cur);
965 int BufferView::workWidth() const
971 void BufferView::recenter()
973 showCursor(d->cursor_, SCROLL_CENTER, true);
977 void BufferView::showCursor()
979 showCursor(d->cursor_, SCROLL_VISIBLE, true);
983 void BufferView::showCursor(DocIterator const & dit, ScrollType how,
986 if (scrollToCursor(dit, how) && update)
987 processUpdateFlags(Update::Force);
991 bool BufferView::scrollToCursor(DocIterator const & dit, ScrollType how)
993 // We are not properly started yet, delay until resizing is done.
997 if (how == SCROLL_CENTER)
998 LYXERR(Debug::SCROLLING, "Centering cursor in workarea");
999 else if (how == SCROLL_TOP)
1000 LYXERR(Debug::SCROLLING, "Setting cursor to top of workarea");
1002 LYXERR(Debug::SCROLLING, "Making sure cursor is visible in workarea");
1004 CursorSlice const & bot = dit.bottom();
1005 TextMetrics & tm = textMetrics(bot.text());
1007 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
1008 pos_type bot_pit = bot.pit();
1009 if (bot_pit > max_pit) {
1010 // FIXME: Why does this happen?
1011 LYXERR0("bottom pit is greater that max pit: "
1012 << bot_pit << " > " << max_pit);
1016 if (bot_pit == tm.first().first - 1)
1017 tm.newParMetricsUp();
1018 else if (bot_pit == tm.last().first + 1)
1019 tm.newParMetricsDown();
1021 if (tm.contains(bot_pit) && how == SCROLL_VISIBLE) {
1022 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
1023 LBUFERR(!pm.rows().empty());
1024 // FIXME: smooth scrolling doesn't work in mathed.
1025 CursorSlice const & cs = dit.innerTextSlice();
1026 int const ypos = pm.position() + coordOffset(dit).y_;
1027 ParagraphMetrics const & inner_pm =
1028 textMetrics(cs.text()).parMetrics(cs.pit());
1029 Dimension const & row_dim =
1030 inner_pm.getRow(cs.pos(), dit.boundary()).dim();
1033 // We try to visualize the whole row, if the row height is larger than
1034 // the screen height, we scroll to a heuristic value of height_ / 4.
1035 // FIXME: This heuristic value should be replaced by a recursive search
1036 // for a row in the inset that can be visualized completely.
1037 if (row_dim.height() > height_) {
1038 if (ypos < defaultRowHeight())
1039 scrolled = scroll(ypos - height_ / 4);
1040 else if (ypos > height_ - defaultRowHeight())
1041 scrolled = scroll(ypos - 3 * height_ / 4);
1044 // If the top part of the row falls of the screen, we scroll
1045 // up to align the top of the row with the top of the screen.
1046 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
1047 int const ynew = row_dim.ascent();
1048 scrolled = scrollUp(ynew - ypos);
1051 // If the bottom of the row falls of the screen, we scroll down.
1052 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
1053 int const ynew = height_ - row_dim.descent();
1054 scrolled = scrollDown(ypos - ynew);
1057 // else, nothing to do, the cursor is already visible so we just return.
1058 return scrolled != 0;
1061 // fix inline completion position
1062 if (d->inlineCompletionPos_.fixIfBroken())
1063 d->inlineCompletionPos_ = DocIterator();
1065 tm.redoParagraph(bot_pit);
1066 int const offset = coordOffset(dit).y_;
1067 pit_type const old_pit = d->anchor_pit_;
1068 d->anchor_pit_ = bot_pit;
1070 CursorSlice const & cs = dit.innerTextSlice();
1071 ParagraphMetrics const & inner_pm =
1072 textMetrics(cs.text()).parMetrics(cs.pit());
1073 Dimension const & row_dim =
1074 inner_pm.getRow(cs.pos(), dit.boundary()).dim();
1076 int const old_ypos = d->anchor_ypos_;
1077 d->anchor_ypos_ = - offset + row_dim.ascent();
1078 if (how == SCROLL_CENTER)
1079 d->anchor_ypos_ += height_/2 - row_dim.height() / 2;
1080 else if (!lyxrc.scroll_below_document && d->anchor_pit_ == max_pit)
1081 d->anchor_ypos_ = height_ - offset - row_dim.descent();
1082 else if (offset > height_)
1083 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
1085 d->anchor_ypos_ = defaultRowHeight() * 2;
1087 return d->anchor_ypos_ != old_ypos || d->anchor_pit_ != old_pit;
1091 void BufferView::makeDocumentClass()
1093 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1094 buffer_.params().makeDocumentClass(buffer_.isClone(), buffer_.isInternal());
1095 updateDocumentClass(olddc);
1099 void BufferView::updateDocumentClass(DocumentClassConstPtr olddc)
1101 StableDocIterator backcur(d->cursor_);
1102 ErrorList & el = buffer_.errorList("Class Switch");
1103 cap::switchBetweenClasses(
1104 olddc, buffer_.params().documentClassPtr(),
1105 static_cast<InsetText &>(buffer_.inset()), el);
1107 setCursor(backcur.asDocIterator(&buffer_));
1109 buffer_.errors("Class Switch");
1113 /** Return the change status at cursor position, taking into account the
1114 * status at each level of the document iterator (a table in a deleted
1115 * footnote is deleted).
1116 * When \param outer is true, the top slice is not looked at.
1118 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
1120 size_t const depth = dit.depth() - (outer ? 1 : 0);
1122 for (size_t i = 0 ; i < depth ; ++i) {
1123 CursorSlice const & slice = dit[i];
1124 if (!slice.inset().inMathed()
1125 && slice.pos() < slice.paragraph().size()) {
1126 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
1127 if (ch != Change::UNCHANGED)
1131 return Change::UNCHANGED;
1135 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1137 FuncCode const act = cmd.action();
1139 // Can we use a readonly buffer?
1140 if (buffer_.isReadonly()
1141 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1142 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1143 if (buffer_.hasReadonlyFlag())
1144 flag.message(from_utf8(N_("Document is read-only")));
1146 flag.message(from_utf8(N_("Document has been modified externally")));
1147 flag.setEnabled(false);
1151 // Are we in a DELETED change-tracking region?
1152 if (lookupChangeType(d->cursor_, true) == Change::DELETED
1153 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1154 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1155 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1156 flag.setEnabled(false);
1160 Cursor & cur = d->cursor_;
1162 if (cur.getStatus(cmd, flag))
1167 // FIXME: This is a bit problematic because we don't check if this is
1168 // a document BufferView or not for these LFUNs. We probably have to
1169 // dispatch both to currentBufferView() and, if that fails,
1170 // to documentBufferView(); same as we do now for current Buffer and
1171 // document Buffer. Ideally those LFUN should go to Buffer as they
1172 // operate on the full Buffer and the cursor is only needed either for
1173 // an Undo record or to restore a cursor position. But we don't know
1174 // how to do that inside Buffer of course.
1175 case LFUN_BUFFER_PARAMS_APPLY:
1176 case LFUN_LAYOUT_MODULES_CLEAR:
1177 case LFUN_LAYOUT_MODULE_ADD:
1178 case LFUN_LAYOUT_RELOAD:
1179 case LFUN_TEXTCLASS_APPLY:
1180 case LFUN_TEXTCLASS_LOAD:
1181 flag.setEnabled(!buffer_.isReadonly());
1185 // We do not use the LyXAction flag for readonly because Undo sets the
1186 // buffer clean/dirty status by itself.
1187 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1190 // We do not use the LyXAction flag for readonly because Redo sets the
1191 // buffer clean/dirty status by itself.
1192 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1194 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1195 case LFUN_FILE_INSERT_PLAINTEXT: {
1196 docstring const & fname = cmd.argument();
1197 if (!FileName::isAbsolute(to_utf8(fname))) {
1198 flag.message(_("Absolute filename expected."));
1201 flag.setEnabled(cur.inTexted());
1204 case LFUN_FILE_INSERT:
1205 case LFUN_BOOKMARK_SAVE:
1206 // FIXME: Actually, these LFUNS should be moved to Text
1207 flag.setEnabled(cur.inTexted());
1210 case LFUN_FONT_STATE:
1211 case LFUN_LABEL_INSERT:
1212 case LFUN_INFO_INSERT:
1213 case LFUN_PARAGRAPH_GOTO:
1214 case LFUN_NOTE_NEXT:
1215 case LFUN_REFERENCE_NEXT:
1216 case LFUN_WORD_FIND:
1217 case LFUN_WORD_FIND_FORWARD:
1218 case LFUN_WORD_FIND_BACKWARD:
1219 case LFUN_WORD_REPLACE:
1222 case LFUN_MARK_TOGGLE:
1223 case LFUN_SEARCH_STRING_SET:
1224 case LFUN_SCREEN_RECENTER:
1225 case LFUN_SCREEN_SHOW_CURSOR:
1226 case LFUN_BIBTEX_DATABASE_ADD:
1227 case LFUN_BIBTEX_DATABASE_DEL:
1228 case LFUN_BIBTEX_DATABASE_LIST:
1229 case LFUN_STATISTICS:
1230 case LFUN_KEYMAP_OFF:
1231 case LFUN_KEYMAP_PRIMARY:
1232 case LFUN_KEYMAP_SECONDARY:
1233 case LFUN_KEYMAP_TOGGLE:
1234 case LFUN_INSET_SELECT_ALL:
1235 flag.setEnabled(true);
1238 case LFUN_GRAPHICS_UNIFY:
1239 flag.setEnabled(cur.countInsetsInSelection(GRAPHICS_CODE)>1);
1242 case LFUN_WORD_FINDADV: {
1243 FindAndReplaceOptions opt;
1244 istringstream iss(to_utf8(cmd.argument()));
1246 flag.setEnabled(opt.repl_buf_name.empty()
1247 || !buffer_.isReadonly());
1251 case LFUN_LABEL_GOTO:
1252 flag.setEnabled(!cmd.argument().empty()
1253 || getInsetByCode<InsetRef>(cur, REF_CODE)
1254 || getInsetByCode<InsetMathRef>(cur, MATH_REF_CODE));
1257 case LFUN_CHANGES_MERGE:
1258 case LFUN_CHANGE_NEXT:
1259 case LFUN_CHANGE_PREVIOUS:
1260 case LFUN_ALL_CHANGES_ACCEPT:
1261 case LFUN_ALL_CHANGES_REJECT:
1262 flag.setEnabled(buffer_.areChangesPresent());
1265 case LFUN_SCREEN_UP:
1266 case LFUN_SCREEN_DOWN:
1268 case LFUN_SCREEN_UP_SELECT:
1269 case LFUN_SCREEN_DOWN_SELECT:
1270 case LFUN_INSET_FORALL:
1271 flag.setEnabled(true);
1274 case LFUN_LAYOUT_TABULAR:
1275 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1279 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1282 case LFUN_LAYOUT_PARAGRAPH:
1283 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1286 case LFUN_BRANCH_ADD_INSERT:
1287 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1290 case LFUN_DIALOG_SHOW_NEW_INSET:
1291 // FIXME: this is wrong, but I do not understand the
1293 if (cur.inset().lyxCode() == CAPTION_CODE)
1294 return cur.inset().getStatus(cur, cmd, flag);
1295 // FIXME we should consider passthru paragraphs too.
1296 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1299 case LFUN_CITATION_INSERT: {
1300 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1301 // FIXME: This could turn in a recursive hell.
1302 // Shouldn't we use Buffer::getStatus() instead?
1303 flag.setEnabled(lyx::getStatus(fr).enabled());
1306 case LFUN_INSET_APPLY: {
1307 string const name = cmd.getArg(0);
1308 Inset * inset = editedInset(name);
1310 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1311 if (!inset->getStatus(cur, fr, flag)) {
1312 // Every inset is supposed to handle this
1313 LASSERT(false, break);
1316 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1317 flag = lyx::getStatus(fr);
1323 flag.setEnabled(cur.selection());
1334 Inset * BufferView::editedInset(string const & name) const
1336 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1337 return it == d->edited_insets_.end() ? nullptr : it->second;
1341 void BufferView::editInset(string const & name, Inset * inset)
1344 d->edited_insets_[name] = inset;
1346 d->edited_insets_.erase(name);
1350 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1352 LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1354 string const argument = to_utf8(cmd.argument());
1355 Cursor & cur = d->cursor_;
1358 // Don't dispatch function that does not apply to internal buffers.
1359 if (buffer_.isInternal()
1360 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1363 // We'll set this back to false if need be.
1364 bool dispatched = true;
1365 buffer_.undo().beginUndoGroup();
1367 FuncCode const act = cmd.action();
1370 case LFUN_BUFFER_PARAMS_APPLY: {
1371 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1372 cur.recordUndoBufferParams();
1373 istringstream ss(to_utf8(cmd.argument()));
1376 int const unknown_tokens = buffer_.readHeader(lex);
1377 if (unknown_tokens != 0) {
1378 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1379 << unknown_tokens << " unknown token"
1380 << (unknown_tokens == 1 ? "" : "s"));
1382 updateDocumentClass(olddc);
1384 // We are most certainly here because of a change in the document
1385 // It is then better to make sure that all dialogs are in sync with
1386 // current document settings.
1387 dr.screenUpdate(Update::Force | Update::FitCursor);
1388 dr.forceBufferUpdate();
1392 case LFUN_LAYOUT_MODULES_CLEAR: {
1393 // FIXME: this modifies the document in cap::switchBetweenClasses
1394 // without calling recordUndo. Fix this before using
1395 // recordUndoBufferParams().
1396 cur.recordUndoFullBuffer();
1397 buffer_.params().clearLayoutModules();
1398 makeDocumentClass();
1399 dr.screenUpdate(Update::Force);
1400 dr.forceBufferUpdate();
1404 case LFUN_LAYOUT_MODULE_ADD: {
1405 BufferParams const & params = buffer_.params();
1406 if (!params.layoutModuleCanBeAdded(argument)) {
1407 LYXERR0("Module `" << argument <<
1408 "' cannot be added due to failed requirements or "
1409 "conflicts with installed modules.");
1412 // FIXME: this modifies the document in cap::switchBetweenClasses
1413 // without calling recordUndo. Fix this before using
1414 // recordUndoBufferParams().
1415 cur.recordUndoFullBuffer();
1416 buffer_.params().addLayoutModule(argument);
1417 makeDocumentClass();
1418 dr.screenUpdate(Update::Force);
1419 dr.forceBufferUpdate();
1423 case LFUN_TEXTCLASS_APPLY: {
1424 // since this shortcircuits, the second call is made only if
1426 bool const success =
1427 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1428 LayoutFileList::get().load(argument, buffer_.filePath());
1430 docstring s = bformat(_("The document class `%1$s' "
1431 "could not be loaded."), from_utf8(argument));
1432 frontend::Alert::error(_("Could not load class"), s);
1436 LayoutFile const * old_layout = buffer_.params().baseClass();
1437 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1439 if (old_layout == new_layout)
1443 // Save the old, possibly modular, layout for use in conversion.
1444 // FIXME: this modifies the document in cap::switchBetweenClasses
1445 // without calling recordUndo. Fix this before using
1446 // recordUndoBufferParams().
1447 cur.recordUndoFullBuffer();
1448 buffer_.params().setBaseClass(argument, buffer_.layoutPos());
1449 makeDocumentClass();
1450 dr.screenUpdate(Update::Force);
1451 dr.forceBufferUpdate();
1455 case LFUN_TEXTCLASS_LOAD: {
1456 // since this shortcircuits, the second call is made only if
1458 bool const success =
1459 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1460 LayoutFileList::get().load(argument, buffer_.filePath());
1462 docstring s = bformat(_("The document class `%1$s' "
1463 "could not be loaded."), from_utf8(argument));
1464 frontend::Alert::error(_("Could not load class"), s);
1469 case LFUN_LAYOUT_RELOAD: {
1470 LayoutFileIndex bc = buffer_.params().baseClassID();
1471 LayoutFileList::get().reset(bc);
1472 buffer_.params().setBaseClass(bc, buffer_.layoutPos());
1473 makeDocumentClass();
1474 dr.screenUpdate(Update::Force);
1475 dr.forceBufferUpdate();
1480 dr.setMessage(_("Undo"));
1481 cur.clearSelection();
1482 // We need to find out if the bibliography information
1483 // has changed. See bug #11055.
1484 // So these should not be references...
1485 string const engine = buffer().params().citeEngine();
1486 CiteEngineType const enginetype = buffer().params().citeEngineType();
1487 if (!cur.undoAction())
1488 dr.setMessage(_("No further undo information"));
1490 dr.screenUpdate(Update::Force | Update::FitCursor);
1491 dr.forceBufferUpdate();
1492 resetInlineCompletionPos();
1493 if (buffer().params().citeEngine() != engine ||
1494 buffer().params().citeEngineType() != enginetype)
1495 buffer().invalidateCiteLabels();
1501 dr.setMessage(_("Redo"));
1502 cur.clearSelection();
1503 // We need to find out if the bibliography information
1504 // has changed. See bug #11055.
1505 // So these should not be references...
1506 string const engine = buffer().params().citeEngine();
1507 CiteEngineType const enginetype = buffer().params().citeEngineType();
1508 if (!cur.redoAction())
1509 dr.setMessage(_("No further redo information"));
1511 dr.screenUpdate(Update::Force | Update::FitCursor);
1512 dr.forceBufferUpdate();
1513 resetInlineCompletionPos();
1514 if (buffer().params().citeEngine() != engine ||
1515 buffer().params().citeEngineType() != enginetype)
1516 buffer().invalidateCiteLabels();
1521 case LFUN_FONT_STATE:
1522 dr.setMessage(cur.currentState(false));
1525 case LFUN_BOOKMARK_SAVE:
1526 dr.screenUpdate(Update::Force);
1527 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1530 case LFUN_LABEL_GOTO: {
1531 docstring label = cmd.argument();
1532 if (label.empty()) {
1534 getInsetByCode<InsetRef>(cur, REF_CODE);
1536 label = inset->getParam("reference");
1537 // persistent=false: use temp_bookmark
1541 if (!label.empty()) {
1543 // at the moment, this is redundant, since gotoLabel will
1544 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1546 dr.screenUpdate(Update::Force | Update::FitCursor);
1548 InsetMathRef * minset =
1549 getInsetByCode<InsetMathRef>(cur, MATH_REF_CODE);
1551 lyx::dispatch(FuncRequest(LFUN_LABEL_GOTO,
1552 minset->getTarget()));
1557 case LFUN_PARAGRAPH_GOTO: {
1558 int const id = convert<int>(cmd.getArg(0));
1559 pos_type const pos = convert<int>(cmd.getArg(1));
1562 string const str_id_end = cmd.getArg(2);
1563 string const str_pos_end = cmd.getArg(3);
1565 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1566 b = theBufferList().next(b)) {
1569 curs.setCursor(b->getParFromID(id));
1571 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1575 LYXERR(Debug::INFO, "Paragraph " << curs.paragraph().id()
1576 << " found in buffer `"
1577 << b->absFileName() << "'.");
1579 if (b == &buffer_) {
1581 if (str_id_end.empty() || str_pos_end.empty()) {
1584 mouseSetCursor(curs);
1587 int const id_end = convert<int>(str_id_end);
1588 pos_type const pos_end = convert<int>(str_pos_end);
1589 success = setCursorFromEntries({id, pos},
1592 if (success && scrollToCursor(d->cursor_, SCROLL_TOP))
1593 dr.screenUpdate(Update::Force);
1595 // Switch to other buffer view and resend cmd
1596 lyx::dispatch(FuncRequest(
1597 LFUN_BUFFER_SWITCH, b->absFileName()));
1605 case LFUN_NOTE_NEXT:
1606 if (gotoInset(this, { NOTE_CODE }, false))
1607 dr.screenUpdate(Update::Force);
1610 case LFUN_REFERENCE_NEXT: {
1611 if (gotoInset(this, { LABEL_CODE, REF_CODE }, true))
1612 dr.screenUpdate(Update::Force);
1616 case LFUN_CHANGE_NEXT:
1617 findNextChange(this);
1618 if (cur.inset().isTable())
1619 // In tables, there might be whole changed rows or columns
1621 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1622 dr.screenUpdate(Update::Force | Update::FitCursor);
1625 case LFUN_CHANGE_PREVIOUS:
1626 findPreviousChange(this);
1627 if (cur.inset().isTable())
1628 // In tables, there might be whole changed rows or columns
1630 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1631 dr.screenUpdate(Update::Force | Update::FitCursor);
1634 case LFUN_CHANGES_MERGE:
1635 if (findNextChange(this) || findPreviousChange(this)) {
1636 dr.screenUpdate(Update::Force | Update::FitCursor);
1637 dr.forceBufferUpdate();
1638 showDialog("changes");
1642 case LFUN_ALL_CHANGES_ACCEPT: {
1643 // select complete document
1645 cur.selHandle(true);
1646 buffer_.text().cursorBottom(cur);
1647 // accept everything in a single step to support atomic undo
1648 // temporarily disable track changes in order to end with really
1649 // no new (e.g., DPSM-caused) changes (see #7487)
1650 bool const track = buffer_.params().track_changes;
1651 buffer_.params().track_changes = false;
1652 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1653 buffer_.params().track_changes = track;
1655 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1656 dr.screenUpdate(Update::Force | Update::FitCursor);
1657 dr.forceBufferUpdate();
1661 case LFUN_ALL_CHANGES_REJECT: {
1662 // select complete document
1664 cur.selHandle(true);
1665 buffer_.text().cursorBottom(cur);
1666 // reject everything in a single step to support atomic undo
1667 // temporarily disable track changes in order to end with really
1668 // no new (e.g., DPSM-caused) changes (see #7487)
1669 bool const track = buffer_.params().track_changes;
1670 buffer_.params().track_changes = false;
1671 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1672 buffer_.params().track_changes = track;
1674 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1675 dr.screenUpdate(Update::Force | Update::FitCursor);
1676 dr.forceBufferUpdate();
1680 case LFUN_WORD_FIND_FORWARD:
1681 case LFUN_WORD_FIND_BACKWARD: {
1682 docstring searched_string;
1684 if (!cmd.argument().empty()) {
1685 setSearchRequestCache(cmd.argument());
1686 searched_string = cmd.argument();
1688 searched_string = searchRequestCache();
1691 if (searched_string.empty())
1694 docstring const data =
1695 find2string(searched_string, false, false,
1696 act == LFUN_WORD_FIND_FORWARD, false, false, false);
1697 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1699 dr.screenUpdate(Update::Force | Update::FitCursor);
1701 dr.setMessage(_("Search string not found!"));
1705 case LFUN_WORD_FIND: {
1706 docstring arg = cmd.argument();
1708 arg = searchRequestCache();
1710 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1713 if (lyxfind(this, FuncRequest(act, arg)))
1714 dr.screenUpdate(Update::Force | Update::FitCursor);
1716 dr.setMessage(_("Search string not found!"));
1718 setSearchRequestCache(arg);
1722 case LFUN_SEARCH_STRING_SET: {
1723 docstring pattern = cmd.argument();
1724 if (!pattern.empty()) {
1725 setSearchRequestCache(pattern);
1728 if (cur.selection())
1729 pattern = cur.selectionAsString(false);
1730 else if (!cur.inTexted())
1731 break; // not suitable for selectWord at cursor
1733 pos_type spos = cur.pos();
1734 cur.innerText()->selectWord(cur, WHOLE_WORD);
1735 pattern = cur.selectionAsString(false);
1736 cur.selection(false);
1739 setSearchRequestCache(pattern);
1743 case LFUN_WORD_REPLACE: {
1744 if (lyxreplace(this, cmd)) {
1745 dr.forceBufferUpdate();
1746 dr.screenUpdate(Update::Force | Update::FitCursor);
1749 dr.setMessage(_("Search string not found!"));
1753 case LFUN_WORD_FINDADV: {
1754 FindAndReplaceOptions opt;
1755 istringstream iss(to_utf8(cmd.argument()));
1757 if (findAdv(this, opt)) {
1758 dr.screenUpdate(Update::Force | Update::FitCursor);
1768 case LFUN_INDEX_TAG_ALL: {
1773 Inset * ins = cur.nextInset();
1774 if (!ins || ins->lyxCode() != INDEX_CODE)
1775 // not at index inset
1778 // clone the index inset
1780 new InsetIndex(static_cast<InsetIndex &>(*cur.nextInset()));
1781 // In order to avoid duplication, we compare the
1782 // LaTeX output if we find another index inset after
1784 odocstringstream oilatex;
1785 otexstream oits(oilatex);
1786 OutputParams rp(&cur.buffer()->params().encoding());
1787 ins->latex(oits, rp);
1788 cap::copyInsetToTemp(cur, cins);
1790 // move backwards into preceding word
1791 // skip over other index insets
1792 cur.backwardPosIgnoreCollapsed();
1794 if (cur.inset().lyxCode() == INDEX_CODE)
1796 else if (cur.prevInset() && cur.prevInset()->lyxCode() == INDEX_CODE)
1797 cur.backwardPosIgnoreCollapsed();
1801 if (!cur.inTexted()) {
1802 // Nothing to do here.
1803 setCursorFromInset(ins);
1806 // Get word or selection
1807 cur.text()->selectWord(cur, WHOLE_WORD);
1808 docstring const searched_string = cur.selectionAsString(false);
1809 if (searched_string.empty())
1811 // Start from the beginning
1812 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
1813 while (findOne(this, searched_string,
1814 false,// case sensitive
1815 true,// match whole word only
1817 false,//find deleted
1821 false// only selection
1823 cur.clearSelection();
1824 Inset * ains = cur.nextInset();
1825 if (ains && ains->lyxCode() == INDEX_CODE) {
1826 // We have an index inset.
1827 // Check whether it has the same
1828 // LaTeX content and move on if so.
1829 odocstringstream filatex;
1830 otexstream fits(filatex);
1831 ains->latex(fits, rp);
1832 if (oilatex.str() == filatex.str())
1835 // Paste the inset and possibly continue
1836 cap::pasteFromTemp(cursor(), cursor().buffer()->errorList("Paste"));
1838 // Go back to start position.
1839 setCursorFromInset(ins);
1840 dr.screenUpdate(cur.result().screenUpdate());
1841 if (cur.result().needBufferUpdate())
1842 dr.forceBufferUpdate();
1847 cur.clearSelection();
1848 dr.setMessage(from_utf8(N_("Mark off")));
1852 cur.clearSelection();
1854 dr.setMessage(from_utf8(N_("Mark on")));
1857 case LFUN_MARK_TOGGLE:
1858 cur.selection(false);
1861 dr.setMessage(from_utf8(N_("Mark removed")));
1864 dr.setMessage(from_utf8(N_("Mark set")));
1869 case LFUN_SCREEN_SHOW_CURSOR:
1873 case LFUN_SCREEN_RECENTER:
1877 case LFUN_BIBTEX_DATABASE_ADD: {
1878 Cursor tmpcur = cur;
1879 findInset(tmpcur, { BIBTEX_CODE }, false);
1880 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1883 if (inset->addDatabase(cmd.argument()))
1884 dr.forceBufferUpdate();
1889 case LFUN_BIBTEX_DATABASE_DEL: {
1890 Cursor tmpcur = cur;
1891 findInset(tmpcur, { BIBTEX_CODE }, false);
1892 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1895 if (inset->delDatabase(cmd.argument()))
1896 dr.forceBufferUpdate();
1901 case LFUN_GRAPHICS_UNIFY: {
1903 cur.recordUndoFullBuffer();
1905 DocIterator from, to;
1906 from = cur.selectionBegin();
1907 to = cur.selectionEnd();
1909 string const newId = cmd.getArg(0);
1910 bool fetchId = newId.empty(); //if we wait for groupId from first graphics inset
1912 InsetGraphicsParams grp_par;
1914 InsetGraphics::string2params(graphics::getGroupParams(buffer_, newId), buffer_, grp_par);
1916 if (!from.nextInset()) //move to closest inset
1917 from.forwardInset();
1919 while (!from.empty() && from < to) {
1920 Inset * inset = from.nextInset();
1923 InsetGraphics * ig = inset->asInsetGraphics();
1925 InsetGraphicsParams inspar = ig->getParams();
1930 grp_par.filename = inspar.filename;
1931 ig->setParams(grp_par);
1934 from.forwardInset();
1936 dr.screenUpdate(Update::Force); //needed if triggered from context menu
1940 case LFUN_BIBTEX_DATABASE_LIST: {
1941 docstring_list const & files = buffer_.getBibfiles();
1944 char const separator(os::path_separator());
1945 for (auto const & file : files) {
1949 result += separator;
1951 FileName const fn = buffer_.getBibfilePath(file);
1952 string const path = fn.realPath();
1953 result += from_utf8(os::external_path(path));
1955 dr.setMessage(result);
1959 case LFUN_STATISTICS: {
1960 DocIterator from, to;
1961 if (cur.selection()) {
1962 from = cur.selectionBegin();
1963 to = cur.selectionEnd();
1965 from = doc_iterator_begin(&buffer_);
1966 to = doc_iterator_end(&buffer_);
1968 buffer_.updateStatistics(from, to);
1969 int const words = buffer_.wordCount();
1970 int const chars = buffer_.charCount(false);
1971 int const chars_blanks = buffer_.charCount(true);
1973 if (cur.selection())
1974 message = _("Statistics for the selection:");
1976 message = _("Statistics for the document:");
1979 message += bformat(_("%1$d words"), words);
1981 message += _("One word");
1983 if (chars_blanks != 1)
1984 message += bformat(_("%1$d characters"), chars_blanks);
1986 message += _("One character");
1989 message += bformat(_("%1$d characters (no blanks)"), chars);
1991 message += _("One character (no blanks)");
1993 Alert::information(_("Statistics"), message);
1997 case LFUN_SCREEN_UP:
1998 case LFUN_SCREEN_DOWN: {
1999 Point p = getPos(cur);
2000 // This code has been commented out to enable to scroll down a
2001 // document, even if there are large insets in it (see bug #5465).
2002 /*if (p.y_ < 0 || p.y_ > height_) {
2003 // The cursor is off-screen so recenter before proceeding.
2007 int const scrolled = scroll(act == LFUN_SCREEN_UP
2008 ? -height_ : height_);
2009 if (act == LFUN_SCREEN_UP && scrolled > -height_)
2011 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
2012 p = Point(width_, height_);
2013 bool const in_texted = cur.inTexted();
2014 cur.setCursor(doc_iterator_begin(cur.buffer()));
2015 cur.selHandle(false);
2016 // Force an immediate computation of metrics because we need it below
2018 processUpdateFlags(Update::Force);
2020 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
2021 true, act == LFUN_SCREEN_UP);
2022 //FIXME: what to do with cur.x_target()?
2023 bool update = in_texted && cur.bv().checkDepm(cur, old);
2026 if (update || cur.mark())
2027 dr.screenUpdate(Update::Force | Update::FitCursor);
2029 dr.forceBufferUpdate();
2034 string const scroll_type = cmd.getArg(0);
2035 int scroll_step = 0;
2036 if (scroll_type == "line")
2037 scroll_step = d->scrollbarParameters_.single_step;
2038 else if (scroll_type == "page")
2039 scroll_step = d->scrollbarParameters_.page_step;
2042 string const scroll_quantity = cmd.getArg(1);
2043 if (scroll_quantity == "up")
2044 scrollUp(scroll_step);
2045 else if (scroll_quantity == "down")
2046 scrollDown(scroll_step);
2048 int const scroll_value = convert<int>(scroll_quantity);
2050 scroll(scroll_step * scroll_value);
2052 dr.screenUpdate(Update::ForceDraw);
2053 dr.forceBufferUpdate();
2057 case LFUN_SCREEN_UP_SELECT: {
2058 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
2059 cur.selHandle(true);
2060 if (isTopScreen()) {
2061 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
2065 int y = getPos(cur).y_;
2066 int const ymin = y - height_ + defaultRowHeight();
2067 while (y > ymin && cur.up())
2071 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
2075 case LFUN_SCREEN_DOWN_SELECT: {
2076 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
2077 cur.selHandle(true);
2078 if (isBottomScreen()) {
2079 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
2083 int y = getPos(cur).y_;
2084 int const ymax = y + height_ - defaultRowHeight();
2085 while (y < ymax && cur.down())
2089 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
2094 case LFUN_INSET_SELECT_ALL: {
2095 // true if all cells are selected
2096 bool const all_selected = cur.depth() > 1
2097 && cur.selBegin().at_begin()
2098 && cur.selEnd().at_end();
2099 // true if some cells are selected
2100 bool const cells_selected = cur.depth() > 1
2101 && cur.selBegin().at_cell_begin()
2102 && cur.selEnd().at_cell_end();
2103 if (all_selected || (cells_selected && !cur.inset().isTable())) {
2104 // All the contents of the inset if selected, or only at
2105 // least one cell but inset is not a table.
2106 // Select the inset from outside.
2109 cur.selection(true);
2111 } else if (cells_selected) {
2112 // At least one complete cell is selected and inset is a table.
2118 cur.selection(true);
2119 cur.idx() = cur.lastidx();
2120 cur.pit() = cur.lastpit();
2121 cur.pos() = cur.lastpos();
2123 // select current cell
2127 cur.selection(true);
2128 cur.pit() = cur.lastpit();
2129 cur.pos() = cur.lastpos();
2131 cur.setCurrentFont();
2132 dr.screenUpdate(Update::Force);
2137 case LFUN_UNICODE_INSERT: {
2138 if (cmd.argument().empty())
2141 FuncCode code = cur.inset().currentMode() == Inset::MATH_MODE ?
2142 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
2145 docstring const arg = from_utf8(cmd.getArg(i));
2149 LYXERR0("Not a hexstring: " << arg);
2153 char_type c = hexToInt(arg);
2154 if (c >= 32 && c < 0x10ffff) {
2155 LYXERR(Debug::KEY, "Inserting c: " << c);
2156 lyx::dispatch(FuncRequest(code, docstring(1, c)));
2164 // This would be in Buffer class if only Cursor did not
2165 // require a bufferview
2166 case LFUN_INSET_FORALL: {
2167 docstring const name = from_utf8(cmd.getArg(0));
2168 string const commandstr = cmd.getLongArg(1);
2169 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
2171 // an arbitrary number to limit number of iterations
2172 const int max_iter = 100000;
2174 Cursor & bvcur = d->cursor_;
2175 Cursor const savecur = bvcur;
2177 if (!bvcur.nextInset())
2178 bvcur.forwardInset();
2179 bvcur.beginUndoGroup();
2180 while(bvcur && iterations < max_iter) {
2181 Inset * const ins = bvcur.nextInset();
2184 docstring insname = ins->layoutName();
2185 while (!insname.empty()) {
2186 if (insname == name || name == from_utf8("*")) {
2187 lyx::dispatch(fr, dr);
2188 // we do not want to remember selection here
2189 bvcur.clearSelection();
2193 size_t const i = insname.rfind(':');
2194 if (i == string::npos)
2196 insname = insname.substr(0, i);
2198 // if we did not delete the inset, skip it
2199 if (!bvcur.nextInset() || bvcur.nextInset() == ins)
2200 bvcur.forwardInset();
2203 bvcur.fixIfBroken();
2204 /** This is a dummy undo record only to remember the cursor
2205 * that has just been set; this will be used on a redo action
2206 * (see ticket #10097)
2208 * FIXME: a better fix would be to have a way to set the
2209 * cursor value directly, but I am not sure it is worth it.
2212 bvcur.endUndoGroup();
2213 dr.screenUpdate(Update::Force);
2214 dr.forceBufferUpdate();
2216 if (iterations >= max_iter) {
2218 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
2220 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
2225 case LFUN_BRANCH_ADD_INSERT: {
2226 docstring branch_name = from_utf8(cmd.getArg(0));
2227 if (branch_name.empty())
2228 if (!Alert::askForText(branch_name, _("Branch name")) ||
2229 branch_name.empty())
2232 DispatchResult drtmp;
2233 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
2234 if (drtmp.error()) {
2235 Alert::warning(_("Branch already exists"), drtmp.message());
2238 docstring const sep = buffer_.params().branchlist().separator();
2239 for (docstring const & branch : getVectorFromString(branch_name, sep))
2240 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch));
2244 case LFUN_KEYMAP_OFF:
2245 getIntl().keyMapOn(false);
2248 case LFUN_KEYMAP_PRIMARY:
2249 getIntl().keyMapPrim();
2252 case LFUN_KEYMAP_SECONDARY:
2253 getIntl().keyMapSec();
2256 case LFUN_KEYMAP_TOGGLE:
2257 getIntl().toggleKeyMap();
2260 case LFUN_DIALOG_SHOW_NEW_INSET: {
2261 string const name = cmd.getArg(0);
2262 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2263 if (decodeInsetParam(name, data, buffer_))
2264 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
2266 lyxerr << "Inset type '" << name <<
2267 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
2271 case LFUN_CITATION_INSERT: {
2272 if (argument.empty()) {
2273 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
2276 // we can have one optional argument, delimited by '|'
2277 // citation-insert <key>|<text_before>
2278 // this should be enhanced to also support text_after
2279 // and citation style
2280 string arg = argument;
2282 if (contains(argument, "|")) {
2283 arg = token(argument, '|', 0);
2284 opt1 = token(argument, '|', 1);
2287 // if our cursor is directly in front of or behind a citation inset,
2288 // we will instead add the new key to it.
2289 Inset * inset = cur.nextInset();
2290 if (!inset || inset->lyxCode() != CITE_CODE)
2291 inset = cur.prevInset();
2292 if (inset && inset->lyxCode() == CITE_CODE) {
2293 InsetCitation * icite = static_cast<InsetCitation *>(inset);
2294 if (icite->addKey(arg)) {
2295 dr.forceBufferUpdate();
2296 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
2298 LYXERR0("Discarding optional argument to citation-insert.");
2303 InsetCommandParams icp(CITE_CODE);
2304 icp["key"] = from_utf8(arg);
2306 icp["before"] = from_utf8(opt1);
2308 from_ascii(InsetCitation::last_literal ? "true" : "false");
2309 string icstr = InsetCommand::params2string(icp);
2310 FuncRequest fr(LFUN_INSET_INSERT, icstr);
2313 // if the request comes from the LyX server, then we
2314 // return a list of the undefined keys, in case some
2315 // action could be taken.
2316 if (cmd.origin() != FuncRequest::LYXSERVER)
2319 vector<docstring> keys = getVectorFromString(from_utf8(arg));
2320 vector<docstring>::iterator it = keys.begin();
2321 vector<docstring>::const_iterator end = keys.end();
2323 BiblioInfo const & bibInfo = buffer_.masterBibInfo();
2324 const BiblioInfo::const_iterator bibEnd = bibInfo.end();
2326 if (bibInfo.find(*it) != bibEnd) {
2327 it = keys.erase(it);
2332 dr.setMessage(getStringFromVector(keys));
2337 case LFUN_INSET_APPLY: {
2338 string const name = cmd.getArg(0);
2339 Inset * inset = editedInset(name);
2341 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2345 // put cursor in front of inset.
2346 if (!setCursorFromInset(inset)) {
2347 LASSERT(false, break);
2350 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2351 inset->dispatch(cur, fr);
2352 dr.screenUpdate(cur.result().screenUpdate());
2353 if (cur.result().needBufferUpdate())
2354 dr.forceBufferUpdate();
2359 // The change of language of buffer belongs to the Buffer class.
2360 // We have to do it here because we need a cursor for Undo.
2361 // When Undo::recordUndoBufferParams() is implemented someday
2362 // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
2363 case LFUN_BUFFER_LANGUAGE: {
2364 Language const * oldL = buffer_.params().language;
2365 Language const * newL = languages.getLanguage(argument);
2366 if (!newL || oldL == newL)
2368 if (oldL->rightToLeft() == newL->rightToLeft()) {
2369 cur.recordUndoFullBuffer();
2370 buffer_.changeLanguage(oldL, newL);
2371 cur.setCurrentFont();
2372 dr.forceBufferUpdate();
2377 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2378 case LFUN_FILE_INSERT_PLAINTEXT: {
2379 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
2380 string const fname = to_utf8(cmd.argument());
2381 if (!FileName::isAbsolute(fname))
2382 dr.setMessage(_("Absolute filename expected."));
2384 insertPlaintextFile(FileName(fname), as_paragraph);
2389 // With multi-cell table content, we pass down to the inset
2390 if (cur.inTexted() && cur.selection()
2391 && cur.selectionBegin().idx() != cur.selectionEnd().idx()) {
2392 buffer_.dispatch(cmd, dr);
2393 dispatched = dr.dispatched();
2396 cap::copySelection(cur);
2397 cur.message(_("Copy"));
2401 // OK, so try the Buffer itself...
2402 buffer_.dispatch(cmd, dr);
2403 dispatched = dr.dispatched();
2407 buffer_.undo().endUndoGroup();
2408 dr.dispatched(dispatched);
2410 // NOTE: The code below is copied from Cursor::dispatch. If you
2411 // need to modify this, please update the other one too.
2413 // notify insets we just entered/left
2414 if (cursor() != old) {
2415 old.beginUndoGroup();
2417 bool badcursor = notifyCursorLeavesOrEnters(old, cursor());
2419 cursor().fixIfBroken();
2420 resetInlineCompletionPos();
2427 docstring BufferView::requestSelection()
2429 Cursor & cur = d->cursor_;
2431 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2432 if (!cur.selection()) {
2433 d->xsel_cache_.set = false;
2437 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2438 if (!d->xsel_cache_.set ||
2439 cur.top() != d->xsel_cache_.cursor ||
2440 cur.realAnchor().top() != d->xsel_cache_.anchor)
2442 d->xsel_cache_.cursor = cur.top();
2443 d->xsel_cache_.anchor = cur.realAnchor().top();
2444 d->xsel_cache_.set = cur.selection();
2445 return cur.selectionAsString(false);
2451 void BufferView::clearSelection()
2453 d->cursor_.clearSelection();
2454 // Clear the selection buffer. Otherwise a subsequent
2455 // middle-mouse-button paste would use the selection buffer,
2456 // not the more current external selection.
2457 cap::clearSelection();
2458 d->xsel_cache_.set = false;
2459 // The buffer did not really change, but this causes the
2460 // redraw we need because we cleared the selection above.
2461 buffer_.changed(false);
2465 void BufferView::resize(int width, int height)
2467 // Update from work area
2471 // Clear the paragraph height cache.
2472 d->par_height_.clear();
2473 // Redo the metrics.
2478 Inset const * BufferView::getCoveringInset(Text const & text,
2481 TextMetrics & tm = d->text_metrics_[&text];
2482 Inset * inset = tm.checkInsetHit(x, y);
2486 if (!inset->descendable(*this))
2487 // No need to go further down if the inset is not
2491 size_t cell_number = inset->nargs();
2492 // Check all the inner cell.
2493 for (size_t i = 0; i != cell_number; ++i) {
2494 Text const * inner_text = inset->getText(i);
2497 Inset const * inset_deeper =
2498 getCoveringInset(*inner_text, x, y);
2500 return inset_deeper;
2508 Inset const * BufferView::clickableMathInset(InsetMathNest const * inset,
2509 CoordCache::Insets const & inset_cache, int x, int y) const
2511 for (size_t i = 0; i < inset->nargs(); ++i) {
2512 MathData const & ar = inset->cell(i);
2513 for (size_t j = 0; j < ar.size(); ++j) {
2514 string const name = lyxerr.debugging(Debug::MATHED)
2515 ? insetName(ar[j].nucleus()->lyxCode())
2517 LYXERR(Debug::MATHED, "Checking inset: " << name);
2518 if (ar[j].nucleus()->clickable(*this, x, y)) {
2519 if (inset_cache.covers(ar[j].nucleus(), x, y)) {
2520 LYXERR(Debug::MATHED, "Clickable inset: "
2522 return ar[j].nucleus();
2525 InsetMathNest const * imn =
2526 ar[j].nucleus()->asNestInset();
2528 Inset const * inner =
2529 clickableMathInset(imn, inset_cache, x, y);
2539 void BufferView::updateHoveredInset() const
2541 // Get inset under mouse, if there is one.
2542 int const x = d->mouse_position_cache_.x_;
2543 int const y = d->mouse_position_cache_.y_;
2544 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2545 if (covering_inset && covering_inset->asInsetMath()) {
2546 Inset const * inner_inset = clickableMathInset(
2547 covering_inset->asInsetMath()->asNestInset(),
2548 coordCache().getInsets(), x, y);
2550 covering_inset = inner_inset;
2553 d->clickable_inset_ = covering_inset && covering_inset->clickable(*this, x, y);
2555 if (covering_inset == d->last_inset_)
2556 // Same inset, no need to do anything...
2559 bool need_redraw = false;
2560 if (d->last_inset_) {
2561 // Remove the hint on the last hovered inset (if any).
2562 need_redraw |= d->last_inset_->setMouseHover(this, false);
2563 d->last_inset_ = nullptr;
2566 if (covering_inset && covering_inset->setMouseHover(this, true)) {
2568 // Only the insets that accept the hover state, do
2569 // clear the last_inset_, so only set the last_inset_
2570 // member if the hovered setting is accepted.
2571 d->last_inset_ = covering_inset;
2575 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2576 << d->mouse_position_cache_.x_ << ", "
2577 << d->mouse_position_cache_.y_ << ")");
2579 d->update_strategy_ = DecorationUpdate;
2581 // This event (moving without mouse click) is not passed further.
2582 // This should be changed if it is further utilized.
2583 buffer_.changed(false);
2588 void BufferView::clearLastInset(Inset * inset) const
2590 if (d->last_inset_ != inset) {
2591 LYXERR0("Wrong last_inset!");
2594 d->last_inset_ = nullptr;
2598 bool BufferView::mouseSelecting() const
2600 return d->mouse_selecting_;
2604 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2606 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2608 // This is only called for mouse related events including
2609 // LFUN_FILE_OPEN generated by drag-and-drop.
2610 FuncRequest cmd = cmd0;
2612 Cursor old = cursor();
2614 cur.push(buffer_.inset());
2615 cur.selection(d->cursor_.selection());
2617 // Either the inset under the cursor or the
2618 // surrounding Text will handle this event.
2620 // make sure we stay within the screen...
2621 cmd.set_y(min(max(cmd.y(), -1), height_));
2623 d->mouse_position_cache_.x_ = cmd.x();
2624 d->mouse_position_cache_.y_ = cmd.y();
2626 d->mouse_selecting_ =
2627 cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::button1;
2629 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2630 updateHoveredInset();
2634 // Build temporary cursor.
2635 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2637 // If inset is not editable, cur.pos() might point behind the
2638 // inset (depending on cmd.x(), cmd.y()). This is needed for
2639 // editing to fix bug 9628, but e.g. the context menu needs a
2640 // cursor in front of the inset.
2641 if ((inset->hasSettings() || !inset->contextMenuName().empty()
2642 || inset->lyxCode() == SEPARATOR_CODE) &&
2643 cur.nextInset() != inset && cur.prevInset() == inset)
2645 } else if (cur.inTexted() && cur.pos()
2646 && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
2647 // Always place cursor in front of a separator inset.
2651 // Put anchor at the same position.
2654 cur.beginUndoGroup();
2656 // Try to dispatch to an non-editable inset near this position
2657 // via the temp cursor. If the inset wishes to change the real
2658 // cursor it has to do so explicitly by using
2659 // cur.bv().cursor() = cur; (or similar)
2661 inset->dispatch(cur, cmd);
2663 // Now dispatch to the temporary cursor. If the real cursor should
2664 // be modified, the inset's dispatch has to do so explicitly.
2665 if (!inset || !cur.result().dispatched())
2668 // Notify left insets
2670 bool badcursor = old.fixIfBroken() || cur.fixIfBroken();
2671 badcursor = badcursor || notifyCursorLeavesOrEnters(old, cur);
2673 cursor().fixIfBroken();
2678 // Do we have a selection?
2679 theSelection().haveSelection(cursor().selection());
2681 if (cur.needBufferUpdate() || buffer().needUpdate()) {
2682 cur.clearBufferUpdate();
2683 buffer().updateBuffer();
2686 // If the command has been dispatched,
2687 if (cur.result().dispatched() || cur.result().screenUpdate())
2688 processUpdateFlags(cur.result().screenUpdate());
2692 int BufferView::minVisiblePart()
2694 return 2 * defaultRowHeight();
2698 int BufferView::scroll(int pixels)
2701 return scrollDown(pixels);
2703 return scrollUp(-pixels);
2708 int BufferView::scrollDown(int pixels)
2710 Text * text = &buffer_.text();
2711 TextMetrics & tm = d->text_metrics_[text];
2712 int const ymax = height_ + pixels;
2714 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2715 int bottom_pos = last.second->position() + last.second->descent();
2716 if (lyxrc.scroll_below_document)
2717 bottom_pos += height_ - minVisiblePart();
2718 if (last.first + 1 == int(text->paragraphs().size())) {
2719 if (bottom_pos <= height_)
2721 pixels = min(pixels, bottom_pos - height_);
2724 if (bottom_pos > ymax)
2726 tm.newParMetricsDown();
2728 d->anchor_ypos_ -= pixels;
2733 int BufferView::scrollUp(int pixels)
2735 Text * text = &buffer_.text();
2736 TextMetrics & tm = d->text_metrics_[text];
2737 int ymin = - pixels;
2739 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2740 int top_pos = first.second->position() - first.second->ascent();
2741 if (first.first == 0) {
2744 pixels = min(pixels, - top_pos);
2749 tm.newParMetricsUp();
2751 d->anchor_ypos_ += pixels;
2756 bool BufferView::setCursorFromRow(int row)
2758 TexRow::TextEntry start, end;
2759 tie(start,end) = buffer_.texrow().getEntriesFromRow(row);
2760 LYXERR(Debug::OUTFILE,
2761 "setCursorFromRow: for row " << row << ", TexRow has found "
2762 "start (id=" << start.id << ",pos=" << start.pos << "), "
2763 "end (id=" << end.id << ",pos=" << end.pos << ")");
2764 return setCursorFromEntries(start, end);
2768 bool BufferView::setCursorFromEntries(TexRow::TextEntry start,
2769 TexRow::TextEntry end)
2771 DocIterator dit_start, dit_end;
2772 tie(dit_start,dit_end) =
2773 TexRow::getDocIteratorsFromEntries(start, end, buffer_);
2776 // Setting selection start
2777 d->cursor_.clearSelection();
2778 setCursor(dit_start);
2779 // Setting selection end
2781 d->cursor_.resetAnchor();
2782 setCursorSelectionTo(dit_end);
2788 bool BufferView::setCursorFromInset(Inset const * inset)
2790 // are we already there?
2791 if (cursor().nextInset() == inset)
2794 // Inset is not at cursor position. Find it in the document.
2797 while (cur && cur.nextInset() != inset)
2808 void BufferView::gotoLabel(docstring const & label)
2811 bool have_inactive = false;
2812 for (Buffer const * buf : buffer().allRelatives()) {
2814 for (TocItem const & item : *buf->tocBackend().toc("label")) {
2815 if (label == item.str() && item.isOutput()) {
2816 lyx::dispatch(item.action());
2819 // If we find an inactive label, save it for the case
2820 // that no active one is there
2821 if (label == item.str() && !have_inactive) {
2822 have_inactive = true;
2823 action = item.action();
2827 // We only found an inactive label. Go there.
2829 lyx::dispatch(action);
2833 TextMetrics const & BufferView::textMetrics(Text const * t) const
2835 return const_cast<BufferView *>(this)->textMetrics(t);
2839 TextMetrics & BufferView::textMetrics(Text const * t)
2842 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2843 if (tmc_it == d->text_metrics_.end()) {
2844 tmc_it = d->text_metrics_.emplace(std::piecewise_construct,
2845 std::forward_as_tuple(t),
2846 std::forward_as_tuple(this, const_cast<Text *>(t))).first;
2848 return tmc_it->second;
2852 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2855 return textMetrics(t).parMetrics(pit);
2859 int BufferView::workHeight() const
2865 void BufferView::setCursor(DocIterator const & dit)
2868 size_t const n = dit.depth();
2869 for (size_t i = 0; i < n; ++i)
2870 dit[i].inset().edit(d->cursor_, true);
2872 d->cursor_.setCursor(dit);
2873 d->cursor_.selection(false);
2874 d->cursor_.setCurrentFont();
2876 // It seems on general grounds as if this is probably needed, but
2877 // it is not yet clear.
2878 // See bug #7394 and r38388.
2879 // d->cursor.resetAnchor();
2883 void BufferView::setCursorSelectionTo(DocIterator const & dit)
2885 size_t const n = dit.depth();
2886 for (size_t i = 0; i < n; ++i)
2887 dit[i].inset().edit(d->cursor_, true);
2889 d->cursor_.selection(true);
2890 d->cursor_.setCursorSelectionTo(dit);
2891 d->cursor_.setCurrentFont();
2895 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2897 // Would be wrong to delete anything if we have a selection.
2898 if (cur.selection())
2901 bool need_anchor_change = false;
2902 bool changed = Text::deleteEmptyParagraphMechanism(cur, old,
2903 need_anchor_change);
2905 if (need_anchor_change)
2913 // we would rather not do this here, but it needs to be done before
2914 // the changed() signal is sent.
2915 buffer_.updateBuffer();
2917 buffer_.changed(true);
2922 bool BufferView::mouseSetCursor(Cursor & cur, bool const select)
2924 LASSERT(&cur.bv() == this, return false);
2927 // this event will clear selection so we save selection for
2928 // persistent selection
2929 cap::saveSelection(cursor());
2931 d->cursor_.macroModeClose();
2932 // If a macro has been finalized, the cursor might have been broken
2935 // Has the cursor just left the inset?
2936 bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2938 d->cursor_.fixIfBroken();
2940 // do the dEPM magic if needed
2941 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2942 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2943 // the leftinset bool would not be necessary (badcursor instead).
2944 bool update = leftinset;
2947 d->cursor_.setSelection();
2948 d->cursor_.setCursorSelectionTo(cur);
2950 if (d->cursor_.inTexted())
2951 update |= checkDepm(cur, d->cursor_);
2952 d->cursor_.resetAnchor();
2953 d->cursor_.setCursor(cur);
2954 d->cursor_.clearSelection();
2956 d->cursor_.boundary(cur.boundary());
2957 d->cursor_.finishUndo();
2958 d->cursor_.setCurrentFont();
2960 cur.forceBufferUpdate();
2965 void BufferView::putSelectionAt(DocIterator const & cur,
2966 int length, bool backwards)
2968 d->cursor_.clearSelection();
2974 d->cursor_.pos() += length;
2975 d->cursor_.setSelection(d->cursor_, -length);
2977 d->cursor_.setSelection(d->cursor_, length);
2982 bool BufferView::selectIfEmpty(DocIterator & cur)
2984 if ((cur.inTexted() && !cur.paragraph().empty())
2985 || (cur.inMathed() && !cur.cell().empty()))
2988 pit_type const beg_pit = cur.pit();
2990 // The paragraph associated to this item isn't
2991 // the first one, so it can be selected
2994 // We have to resort to select the space between the
2995 // end of this item and the begin of the next one
2999 // If it is the only item in the document,
3000 // nothing can be selected
3003 pit_type const end_pit = cur.pit();
3004 pos_type const end_pos = cur.pos();
3005 d->cursor_.clearSelection();
3007 d->cursor_.setCursor(cur);
3008 d->cursor_.pit() = beg_pit;
3009 d->cursor_.pos() = 0;
3010 d->cursor_.selection(false);
3011 d->cursor_.resetAnchor();
3012 d->cursor_.pit() = end_pit;
3013 d->cursor_.pos() = end_pos;
3014 d->cursor_.setSelection();
3019 Cursor & BufferView::cursor()
3025 Cursor const & BufferView::cursor() const
3031 bool BufferView::singleParUpdate()
3033 Text & buftext = buffer_.text();
3034 pit_type const bottom_pit = d->cursor_.bottom().pit();
3035 TextMetrics & tm = textMetrics(&buftext);
3036 Dimension const old_dim = tm.parMetrics(bottom_pit).dim();
3038 // make sure inline completion pointer is ok
3039 if (d->inlineCompletionPos_.fixIfBroken())
3040 d->inlineCompletionPos_ = DocIterator();
3042 // In Single Paragraph mode, rebreak only
3043 // the (main text, not inset!) paragraph containing the cursor.
3044 // (if this paragraph contains insets etc., rebreaking will
3045 // recursively descend)
3046 tm.redoParagraph(bottom_pit);
3047 ParagraphMetrics & pm = tm.parMetrics(bottom_pit);
3048 if (pm.height() != old_dim.height()) {
3049 // Paragraph height has changed so we cannot proceed to
3050 // the singlePar optimisation.
3053 // Since position() points to the baseline of the first row, we
3054 // may have to update it. See ticket #11601 for an example where
3055 // the height does not change but the ascent does.
3056 pm.setPosition(pm.position() - old_dim.ascent() + pm.ascent());
3058 tm.updatePosCache(bottom_pit);
3060 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
3061 << " y2: " << pm.position() + pm.descent()
3062 << " pit: " << bottom_pit
3063 << " singlepar: 1");
3068 void BufferView::updateMetrics()
3070 updateMetrics(d->update_flags_);
3071 d->update_strategy_ = FullScreenUpdate;
3075 void BufferView::updateMetrics(Update::flags & update_flags)
3077 if (height_ == 0 || width_ == 0)
3080 Text & buftext = buffer_.text();
3081 pit_type const npit = int(buftext.paragraphs().size());
3083 // Clear out the position cache in case of full screen redraw,
3084 d->coord_cache_.clear();
3085 d->math_rows_.clear();
3087 // Clear out paragraph metrics to avoid having invalid metrics
3088 // in the cache from paragraphs not relayouted below
3089 // The complete text metrics will be redone.
3090 d->text_metrics_.clear();
3092 TextMetrics & tm = textMetrics(&buftext);
3094 // make sure inline completion pointer is ok
3095 if (d->inlineCompletionPos_.fixIfBroken())
3096 d->inlineCompletionPos_ = DocIterator();
3098 if (d->anchor_pit_ >= npit)
3099 // The anchor pit must have been deleted...
3100 d->anchor_pit_ = npit - 1;
3102 // Rebreak anchor paragraph.
3103 tm.redoParagraph(d->anchor_pit_);
3104 ParagraphMetrics & anchor_pm = tm.parMetrics(d->anchor_pit_);
3107 if (d->anchor_pit_ == 0) {
3108 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
3110 // Complete buffer visible? Then it's easy.
3111 if (scrollRange == 0)
3112 d->anchor_ypos_ = anchor_pm.ascent();
3114 // avoid empty space above the first row
3115 d->anchor_ypos_ = min(d->anchor_ypos_, anchor_pm.ascent());
3118 anchor_pm.setPosition(d->anchor_ypos_);
3119 tm.updatePosCache(d->anchor_pit_);
3121 LYXERR(Debug::PAINTING, "metrics: "
3122 << " anchor pit = " << d->anchor_pit_
3123 << " anchor ypos = " << d->anchor_ypos_);
3125 // Redo paragraphs above anchor if necessary.
3126 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
3127 // We are now just above the anchor paragraph.
3128 pit_type pit1 = d->anchor_pit_ - 1;
3129 for (; pit1 >= 0 && y1 >= 0; --pit1) {
3130 tm.redoParagraph(pit1);
3131 ParagraphMetrics & pm = tm.parMetrics(pit1);
3133 // Save the paragraph position in the cache.
3135 tm.updatePosCache(pit1);
3139 // Redo paragraphs below the anchor if necessary.
3140 int y2 = d->anchor_ypos_ + anchor_pm.descent();
3141 // We are now just below the anchor paragraph.
3142 pit_type pit2 = d->anchor_pit_ + 1;
3143 for (; pit2 < npit && y2 <= height_; ++pit2) {
3144 tm.redoParagraph(pit2);
3145 ParagraphMetrics & pm = tm.parMetrics(pit2);
3147 // Save the paragraph position in the cache.
3149 tm.updatePosCache(pit2);
3153 LYXERR(Debug::PAINTING, "Metrics: "
3154 << " anchor pit = " << d->anchor_pit_
3155 << " anchor ypos = " << d->anchor_ypos_
3158 << " pit1 = " << pit1
3159 << " pit2 = " << pit2);
3161 // metrics is done, full drawing is necessary now
3162 update_flags = (update_flags & ~Update::Force) | Update::ForceDraw;
3164 // Now update the positions of insets in the cache.
3167 if (lyxerr.debugging(Debug::WORKAREA)) {
3168 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
3169 d->coord_cache_.dump();
3174 void BufferView::updatePosCache()
3176 // this is the "nodraw" drawing stage: only set the positions of the
3177 // insets in metrics cache.
3178 frontend::NullPainter np;
3183 void BufferView::insertLyXFile(FileName const & fname, bool const ignorelang)
3185 LASSERT(d->cursor_.inTexted(), return);
3187 // Get absolute path of file and add ".lyx"
3188 // to the filename if necessary
3189 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
3191 docstring const disp_fn = makeDisplayPath(filename.absFileName());
3192 // emit message signal.
3193 message(bformat(_("Inserting document %1$s..."), disp_fn));
3196 Buffer buf(filename.absFileName(), false);
3197 if (buf.loadLyXFile() == Buffer::ReadSuccess) {
3198 ErrorList & el = buffer_.errorList("Parse");
3199 // Copy the inserted document error list into the current buffer one.
3200 el = buf.errorList("Parse");
3201 ParagraphList & pars = buf.paragraphs();
3203 // set main language of imported file to context language
3204 buf.changeLanguage(buf.language(), d->cursor_.getFont().language());
3205 buffer_.undo().recordUndo(d->cursor_);
3206 cap::replaceSelection(d->cursor_);
3207 cap::pasteParagraphList(d->cursor_, pars,
3208 buf.params().documentClassPtr(),
3209 buf.params().authors(), el);
3210 res = _("Document %1$s inserted.");
3212 res = _("Could not insert document %1$s");
3215 buffer_.changed(true);
3216 // emit message signal.
3217 message(bformat(res, disp_fn));
3221 Point BufferView::coordOffset(DocIterator const & dit) const
3227 // Addup contribution of nested insets, from inside to outside,
3228 // keeping the outer paragraph for a special handling below
3229 for (size_t i = dit.depth() - 1; i >= 1; --i) {
3230 CursorSlice const & sl = dit[i];
3234 // get relative position inside sl.inset()
3235 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
3237 // Make relative position inside of the edited inset relative to sl.inset()
3241 // In case of an RTL inset, the edited inset will be positioned to the left
3244 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
3245 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
3250 // remember width for the case that sl.inset() is positioned in an RTL inset
3251 lastw = sl.inset().dimension(*this).wid;
3253 //lyxerr << "Cursor::getPos, i: "
3254 // << i << " x: " << xx << " y: " << y << endl;
3257 // Add contribution of initial rows of outermost paragraph
3258 CursorSlice const & sl = dit[0];
3259 TextMetrics const & tm = textMetrics(sl.text());
3260 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
3262 LBUFERR(!pm.rows().empty());
3263 y -= pm.rows()[0].ascent();
3265 // FIXME: document this mess
3267 if (sl.pos() > 0 && dit.depth() == 1) {
3269 if (pos && dit.boundary())
3271 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
3272 rend = pm.pos2row(pos);
3274 rend = pm.pos2row(sl.pos());
3276 size_t rend = pm.pos2row(sl.pos());
3278 for (size_t rit = 0; rit != rend; ++rit)
3279 y += pm.rows()[rit].height();
3280 y += pm.rows()[rend].ascent();
3282 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
3284 // Make relative position from the nested inset now bufferview absolute.
3285 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
3288 // In the RTL case place the nested inset at the left of the cursor in
3289 // the outer paragraph
3290 bool boundary_1 = dit.boundary() && 1 == dit.depth();
3291 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
3299 Point BufferView::getPos(DocIterator const & dit) const
3301 if (!paragraphVisible(dit))
3302 return Point(-1, -1);
3304 CursorSlice const & bot = dit.bottom();
3305 TextMetrics const & tm = textMetrics(bot.text());
3307 // offset from outer paragraph
3308 Point p = coordOffset(dit);
3309 p.y_ += tm.parMetrics(bot.pit()).position();
3314 bool BufferView::paragraphVisible(DocIterator const & dit) const
3316 CursorSlice const & bot = dit.bottom();
3317 TextMetrics const & tm = textMetrics(bot.text());
3319 return tm.contains(bot.pit());
3323 void BufferView::caretPosAndDim(Point & p, Dimension & dim) const
3325 Cursor const & cur = cursor();
3326 if (cur.inMathed()) {
3327 MathRow const & mrow = mathRow(&cur.cell());
3328 dim = mrow.caret_dim;
3330 Font const font = cur.real_current_font;
3331 frontend::FontMetrics const & fm = theFontMetrics(font);
3332 // lineWidth() can be 0 to mean 'thin line' on HiDpi, but the
3333 // caret drawing code is not prepared for that.
3334 dim.wid = max(fm.lineWidth(), 1);
3335 dim.asc = fm.maxAscent();
3336 dim.des = fm.maxDescent();
3338 if (lyxrc.cursor_width > 0)
3339 dim.wid = lyxrc.cursor_width;
3342 // center fat carets horizontally
3343 p.x_ -= dim.wid / 2;
3349 void BufferView::buildCaretGeometry(bool complet)
3353 caretPosAndDim(p, dim);
3355 Cursor const & cur = d->cursor_;
3356 Font const & realfont = cur.real_current_font;
3357 frontend::FontMetrics const & fm = theFontMetrics(realfont.fontInfo());
3358 bool const isrtl = realfont.isVisibleRightToLeft();
3359 int const dir = isrtl ? -1 : 1;
3361 frontend::CaretGeometry & cg = d->caret_geometry_;
3364 // The caret itself, slanted for italics in text edit mode except
3365 // for selections because the selection rect does not slant
3366 bool const slant = fm.italic() && cur.inTexted() && !cur.selection();
3367 double const slope = slant ? fm.italicSlope() : 0;
3368 cg.shapes.push_back(
3369 {{iround(p.x_ + dim.asc * slope), p.y_},
3370 {iround(p.x_ - dim.des * slope), p.y_ + dim.height()},
3371 {iround(p.x_ + dir * dim.wid - dim.des * slope), p.y_ + dim.height()},
3372 {iround(p.x_ + dir * dim.wid + dim.asc * slope), p.y_}}
3375 // The language indicator _| (if needed)
3376 Language const * doclang = buffer().params().language;
3377 if (!((realfont.language() == doclang && isrtl == doclang->rightToLeft())
3378 || realfont.language() == latex_language)) {
3379 int const lx = dim.height() / 3;
3380 int const xx = iround(p.x_ - dim.des * slope);
3381 int const yy = p.y_ + dim.height();
3382 cg.shapes.push_back(
3383 {{xx, yy - dim.wid},
3384 {xx + dir * (dim.wid + lx - 1), yy - dim.wid},
3385 {xx + dir * (dim.wid + lx - 1), yy},
3390 // The completion triangle |> (if needed)
3392 int const m = p.y_ + dim.height() / 2;
3393 int const d = dim.height() / 8;
3394 // offset for slanted carret
3395 int const sx = iround((dim.asc - (dim.height() / 2 - d)) * slope);
3396 // starting position x
3397 int const xx = p.x_ + dir * dim.wid + sx;
3398 cg.shapes.push_back(
3402 {xx, m + d - dim.wid},
3403 {xx + dir * d - dim.wid, m},
3404 {xx, m - d + dim.wid}}
3408 // compute extremal x values
3410 cg.right = -1000000;
3412 cg.bottom = -1000000;
3413 for (auto const & shape : cg.shapes)
3414 for (Point const & p : shape) {
3415 cg.left = min(cg.left, p.x_);
3416 cg.right = max(cg.right, p.x_);
3417 cg.top = min(cg.top, p.y_);
3418 cg.bottom = max(cg.bottom, p.y_);
3423 frontend::CaretGeometry const & BufferView::caretGeometry() const
3425 return d->caret_geometry_;
3429 bool BufferView::caretInView() const
3431 if (!paragraphVisible(cursor()))
3435 caretPosAndDim(p, dim);
3437 // does the cursor touch the screen ?
3438 if (p.y_ + dim.height() < 0 || p.y_ >= workHeight())
3444 int BufferView::horizScrollOffset() const
3446 return d->horiz_scroll_offset_;
3450 int BufferView::horizScrollOffset(Text const * text,
3451 pit_type pit, pos_type pos) const
3453 // Is this a row that is currently scrolled?
3454 if (!d->current_row_slice_.empty()
3455 && &text->inset() == d->current_row_slice_.inset().asInsetText()
3456 && pit == d->current_row_slice_.pit()
3457 && pos == d->current_row_slice_.pos())
3458 return d->horiz_scroll_offset_;
3463 void BufferView::setCurrentRowSlice(CursorSlice const & rowSlice)
3465 // nothing to do if the cursor was already on this row
3466 if (d->current_row_slice_ == rowSlice)
3469 // if the (previous) current row was scrolled, we have to
3470 // remember it in order to repaint it next time.
3471 if (d->horiz_scroll_offset_ != 0) {
3472 // search the old row in cache and mark it changed
3473 for (auto & tm_pair : d->text_metrics_) {
3474 if (&tm_pair.first->inset() == rowSlice.inset().asInsetText()) {
3475 tm_pair.second.setRowChanged(rowSlice.pit(), rowSlice.pos());
3476 // We found it, no need to continue.
3482 // Since we changed row, the scroll offset is not valid anymore
3483 d->horiz_scroll_offset_ = 0;
3484 d->current_row_slice_ = rowSlice;
3488 void BufferView::checkCursorScrollOffset()
3490 CursorSlice rowSlice = d->cursor_.bottom();
3491 TextMetrics const & tm = textMetrics(rowSlice.text());
3493 // Stop if metrics have not been computed yet, since it means
3494 // that there is nothing to do.
3495 if (!tm.contains(rowSlice.pit()))
3497 ParagraphMetrics const & pm = tm.parMetrics(rowSlice.pit());
3498 Row const & row = pm.getRow(rowSlice.pos(),
3499 d->cursor_.boundary() && rowSlice == d->cursor_.top());
3500 rowSlice.pos() = row.pos();
3502 // Set the row on which the cursor lives.
3503 setCurrentRowSlice(rowSlice);
3505 // Current x position of the cursor in pixels
3506 int cur_x = getPos(d->cursor_).x_;
3508 // Horizontal scroll offset of the cursor row in pixels
3509 int offset = d->horiz_scroll_offset_;
3510 int const MARGIN = 2 * theFontMetrics(d->cursor_.real_current_font).em()
3512 if (row.right_x() <= workWidth() - row.right_margin) {
3513 // Row is narrower than the work area, no offset needed.
3516 if (cur_x - offset < MARGIN) {
3517 // cursor would be too far right
3518 offset = cur_x - MARGIN;
3519 } else if (cur_x - offset > workWidth() - MARGIN) {
3520 // cursor would be too far left
3521 offset = cur_x - workWidth() + MARGIN;
3523 // Correct the offset to make sure that we do not scroll too much
3526 if (row.right_x() - offset < workWidth() - row.right_margin)
3527 offset = row.right_x() - workWidth() + row.right_margin;
3530 //lyxerr << "cur_x=" << cur_x << ", offset=" << offset << ", row.wid=" << row.width() << ", margin=" << MARGIN << endl;
3532 if (offset != d->horiz_scroll_offset_) {
3533 LYXERR(Debug::PAINTING, "Horiz. scroll offset changed from "
3534 << d->horiz_scroll_offset_ << " to " << offset);
3536 if (d->update_strategy_ == NoScreenUpdate)
3537 d->update_strategy_ = SingleParUpdate;
3540 d->horiz_scroll_offset_ = offset;
3544 bool BufferView::busy() const
3546 return buffer().undo().activeUndoGroup();
3550 void BufferView::draw(frontend::Painter & pain, bool paint_caret)
3552 if (height_ == 0 || width_ == 0)
3554 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t--- START NODRAW ---"
3555 : "\t\t*** START DRAWING ***"));
3556 Text & text = buffer_.text();
3557 TextMetrics const & tm = d->text_metrics_[&text];
3558 int const y = tm.first().second->position();
3559 PainterInfo pi(this, pain);
3561 // Check whether the row where the cursor lives needs to be scrolled.
3562 // Update the drawing strategy if needed.
3563 checkCursorScrollOffset();
3565 switch (d->update_strategy_) {
3567 case NoScreenUpdate:
3568 // no screen painting is actually needed. In nodraw stage
3569 // however, the different coordinates of insets and paragraphs
3570 // needs to be updated.
3571 LYXERR(Debug::PAINTING, "Strategy: NoScreenUpdate");
3572 if (pain.isNull()) {
3573 pi.full_repaint = true;
3576 pi.full_repaint = false;
3581 case SingleParUpdate:
3582 pi.full_repaint = false;
3583 LYXERR(Debug::PAINTING, "Strategy: SingleParUpdate");
3584 // In general, only the current row of the outermost paragraph
3585 // will be redrawn. Particular cases where selection spans
3586 // multiple paragraph are correctly detected in TextMetrics.
3590 case DecorationUpdate:
3591 // FIXME: We should also distinguish DecorationUpdate to avoid text
3592 // drawing if possible. This is not possible to do easily right now
3593 // because of the single backing pixmap.
3595 case FullScreenUpdate:
3597 LYXERR(Debug::PAINTING,
3598 ((d->update_strategy_ == FullScreenUpdate)
3599 ? "Strategy: FullScreenUpdate"
3600 : "Strategy: DecorationUpdate"));
3602 // The whole screen, including insets, will be refreshed.
3603 pi.full_repaint = true;
3605 // Clear background.
3606 pain.fillRectangle(0, 0, width_, height_,
3607 pi.backgroundColor(&buffer_.inset()));
3612 // and possibly grey out below
3613 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3614 int const y2 = lastpm.second->position() + lastpm.second->descent();
3617 Color color = buffer().isInternal()
3618 ? Color_background : Color_bottomarea;
3619 pain.fillRectangle(0, y2, width_, height_ - y2, color);
3623 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t --- END NODRAW ---"
3624 : "\t\t *** END DRAWING ***"));
3626 // The scrollbar needs an update.
3627 // FIXME: does it always? see ticket #11947.
3628 updateScrollbarParameters();
3630 // Normalize anchor for next time
3631 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
3632 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3633 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
3634 ParagraphMetrics const & pm = tm.parMetrics(pit);
3635 if (pm.position() + pm.descent() > 0) {
3636 if (d->anchor_pit_ != pit
3637 || d->anchor_ypos_ != pm.position())
3638 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
3639 << " anchor ypos = " << d->anchor_ypos_);
3640 d->anchor_pit_ = pit;
3641 d->anchor_ypos_ = pm.position();
3645 if (!pain.isNull()) {
3646 // reset the update flags, everything has been done
3647 d->update_flags_ = Update::None;
3650 // If a caret has to be painted, mark its text row as dirty to
3651 //make sure that it will be repainted on next redraw.
3652 /* FIXME: investigate whether this can be avoided when the cursor did not
3656 Cursor cur(d->cursor_);
3657 while (cur.depth() > 1) {
3658 if (!cur.inTexted())
3660 TextMetrics const & tm = textMetrics(cur.text());
3661 if (d->caret_geometry_.left >= tm.origin().x_
3662 && d->caret_geometry_.right <= tm.origin().x_ + tm.dim().width())
3666 cur.textRow().changed(true);
3671 void BufferView::message(docstring const & msg)
3674 d->gui_->message(msg);
3678 void BufferView::showDialog(string const & name)
3681 d->gui_->showDialog(name, string());
3685 void BufferView::showDialog(string const & name,
3686 string const & data, Inset * inset)
3689 d->gui_->showDialog(name, data, inset);
3693 void BufferView::updateDialog(string const & name, string const & data)
3696 d->gui_->updateDialog(name, data);
3700 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
3706 // FIXME: Move this out of BufferView again
3707 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
3709 if (!fname.isReadableFile()) {
3710 docstring const error = from_ascii(strerror(errno));
3711 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3712 docstring const text =
3713 bformat(_("Could not read the specified document\n"
3714 "%1$s\ndue to the error: %2$s"), file, error);
3715 Alert::error(_("Could not read file"), text);
3719 if (!fname.isReadableFile()) {
3720 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3721 docstring const text =
3722 bformat(_("%1$s\n is not readable."), file);
3723 Alert::error(_("Could not open file"), text);
3727 // FIXME UNICODE: We don't know the encoding of the file
3728 docstring file_content = fname.fileContents("UTF-8");
3729 if (file_content.empty()) {
3730 Alert::error(_("Reading not UTF-8 encoded file"),
3731 _("The file is not UTF-8 encoded.\n"
3732 "It will be read as local 8Bit-encoded.\n"
3733 "If this does not give the correct result\n"
3734 "then please change the encoding of the file\n"
3735 "to UTF-8 with a program other than LyX.\n"));
3736 file_content = fname.fileContents("local8bit");
3739 return normalize_c(file_content);
3743 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
3745 docstring const tmpstr = contentsOfPlaintextFile(f);
3750 Cursor & cur = cursor();
3751 cap::replaceSelection(cur);
3752 buffer_.undo().recordUndo(cur);
3754 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3756 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3758 buffer_.changed(true);
3762 docstring const & BufferView::inlineCompletion() const
3764 return d->inlineCompletion_;
3768 size_t BufferView::inlineCompletionUniqueChars() const
3770 return d->inlineCompletionUniqueChars_;
3774 DocIterator const & BufferView::inlineCompletionPos() const
3776 return d->inlineCompletionPos_;
3780 void BufferView::resetInlineCompletionPos()
3782 d->inlineCompletionPos_ = DocIterator();
3786 bool samePar(DocIterator const & a, DocIterator const & b)
3788 if (a.empty() && b.empty())
3790 if (a.empty() || b.empty())
3792 if (a.depth() != b.depth())
3794 return &a.innerParagraph() == &b.innerParagraph();
3798 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3799 docstring const & completion, size_t uniqueChars)
3801 uniqueChars = min(completion.size(), uniqueChars);
3802 bool changed = d->inlineCompletion_ != completion
3803 || d->inlineCompletionUniqueChars_ != uniqueChars;
3804 bool singlePar = true;
3805 d->inlineCompletion_ = completion;
3806 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3808 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3811 DocIterator const & old = d->inlineCompletionPos_;
3813 //lyxerr << "inlineCompletionPos changed" << std::endl;
3814 // old or pos are in another paragraph?
3815 if ((!samePar(cur, pos) && !pos.empty())
3816 || (!samePar(cur, old) && !old.empty())) {
3818 //lyxerr << "different paragraph" << std::endl;
3820 d->inlineCompletionPos_ = pos;
3825 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3826 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3828 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3833 bool BufferView::clickableInset() const
3835 return d->clickable_inset_;