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"
35 #include "LyXAction.h"
38 #include "MetricsInfo.h"
39 #include "Paragraph.h"
41 #include "texstream.h"
43 #include "TextMetrics.h"
45 #include "TocBackend.h"
47 #include "insets/InsetBibtex.h"
48 #include "insets/InsetCitation.h"
49 #include "insets/InsetCommand.h" // ChangeRefs
50 #include "insets/InsetGraphics.h"
51 #include "insets/InsetIndex.h"
52 #include "insets/InsetRef.h"
53 #include "insets/InsetText.h"
55 #include "mathed/InsetMathNest.h"
56 #include "mathed/InsetMathRef.h"
57 #include "mathed/MathData.h"
58 #include "mathed/MathRow.h"
60 #include "frontends/alert.h"
61 #include "frontends/CaretGeometry.h"
62 #include "frontends/Delegates.h"
63 #include "frontends/FontMetrics.h"
64 #include "frontends/NullPainter.h"
65 #include "frontends/Painter.h"
66 #include "frontends/Selection.h"
67 #include "frontends/Clipboard.h"
69 #include "support/convert.h"
70 #include "support/debug.h"
71 #include "support/docstring.h"
72 #include "support/docstring_list.h"
73 #include "support/filetools.h"
74 #include "support/gettext.h"
75 #include "support/lassert.h"
76 #include "support/Length.h"
77 #include "support/Lexer.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_(10000),
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 // cache for id of the paragraph which was edited the last time
287 int bookmark_edit_position_;
289 /// When the row where the cursor lies is scrolled, this
290 /// contains the scroll offset
291 int horiz_scroll_offset_;
292 /// a slice pointing to the start of the row where the cursor
293 /// is (at last draw time)
294 CursorSlice current_row_slice_;
295 /// are we hovering something that we can click
296 bool clickable_inset_;
297 /// shape of the caret
298 frontend::CaretGeometry caret_geometry_;
300 bool mouse_selecting_ = false;
301 /// Reference value for statistics (essentially subtract this from the actual value to see relative counts)
302 /// (words/chars/chars no blanks)
303 int stats_ref_value_w_ = 0;
304 int stats_ref_value_c_ = 0;
305 int stats_ref_value_nb_ = 0;
306 bool stats_update_trigger_ = false;
311 BufferView::BufferView(Buffer & buf)
312 : width_(0), height_(0), full_screen_(false), buffer_(buf),
313 d(new Private(*this))
315 d->xsel_cache_.set = false;
316 d->intl_.initKeyMapper(lyxrc.use_kbmap);
318 d->cursor_.setBuffer(&buf);
319 d->cursor_.push(buffer_.inset());
320 d->cursor_.resetAnchor();
321 d->cursor_.setCurrentFont();
323 buffer_.updatePreviews();
327 BufferView::~BufferView()
329 // current buffer is going to be switched-off, save cursor pos
330 // Ideally, the whole cursor stack should be saved, but session
331 // currently can only handle bottom (whole document) level pit and pos.
332 // That is to say, if a cursor is in a nested inset, it will be
333 // restore to the left of the top level inset.
334 LastFilePosSection::FilePos fp;
335 fp.file = buffer_.fileName();
336 fp.pit = d->cursor_.bottom().pit();
337 fp.pos = d->cursor_.bottom().pos();
338 theSession().lastFilePos().save(fp);
341 d->last_inset_->setMouseHover(this, false);
347 void BufferView::copySettingsFrom(BufferView const & bv)
349 setCursor(bv.cursor());
350 d->anchor_pit_ = bv.d->anchor_pit_;
351 d->anchor_ypos_ = bv.d->anchor_ypos_;
355 int BufferView::defaultMargin() const
357 // The value used to be hardcoded to 10
358 return zoomedPixels(20);
362 int BufferView::rightMargin() const
364 const int screen_width = inPixels(lyxrc.screen_width);
366 // The additional test for the case the outliner is opened.
367 if (!lyxrc.screen_limit || width_ < screen_width + 2 * defaultMargin()) {
368 return defaultMargin();
370 return (width_ - screen_width) / 2;
375 int BufferView::leftMargin() const
377 return rightMargin();
381 int BufferView::topMargin() const
383 // Original value was 20px at 100dpi. For internal buffers like in
384 // advanced search and replace, a value of 5px is enough.
385 return zoomedPixels(buffer().isInternal() ? 5 : 20);
389 int BufferView::bottomMargin() const
395 int BufferView::inPixels(Length const & len) const
397 Font const font = buffer().params().getFont();
398 return len.inPixels(workWidth(), theFontMetrics(font).em());
402 int BufferView::zoomedPixels(int pix) const
404 // FIXME: the dpi setting should really depend on the BufferView
405 // (think different monitors).
407 // Zoom factor specified by user in percent
408 double const zoom = lyxrc.currentZoom / 100.0; // [percent]
410 // DPI setting for monitor relative to 100dpi
411 double const dpizoom = lyxrc.dpi / 100.0; // [per 100dpi]
413 return support::iround(pix * zoom * dpizoom);
417 bool BufferView::isTopScreen() const
419 return 0 == d->scrollbarParameters_.min;
423 bool BufferView::isBottomScreen() const
425 return 0 == d->scrollbarParameters_.max;
429 Intl & BufferView::getIntl()
435 Intl const & BufferView::getIntl() const
441 CoordCache & BufferView::coordCache()
443 return d->coord_cache_;
447 CoordCache const & BufferView::coordCache() const
449 return d->coord_cache_;
453 bool BufferView::hasMathRow(MathData const * cell) const
455 return d->math_rows_.find(cell) != d->math_rows_.end();
459 MathRow const & BufferView::mathRow(MathData const * cell) const
461 auto it = d->math_rows_.find(cell);
462 LATTEST(it != d->math_rows_.end());
467 void BufferView::setMathRow(MathData const * cell, MathRow const & mrow)
469 d->math_rows_[cell] = mrow;
473 Buffer & BufferView::buffer()
479 Buffer const & BufferView::buffer() const
485 docstring const & BufferView::searchRequestCache() const
487 return theClipboard().getFindBuffer();
491 void BufferView::setSearchRequestCache(docstring const & text)
499 docstring const search = string2find(text, casesensitive, matchword,
500 forward, wrap, instant, onlysel);
501 theClipboard().setFindBuffer(search);
505 bool BufferView::needsFitCursor() const
507 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
508 frontend::FontMetrics const & fm =
509 theFontMetrics(d->cursor_.getFont().fontInfo());
510 int const asc = fm.maxAscent();
511 int const des = fm.maxDescent();
512 Point const p = getPos(d->cursor_);
513 if (p.y_ - asc >= 0 && p.y_ + des < height_)
522 // this is for debugging only.
523 string flagsAsString(Update::flags flags)
525 if (flags == Update::None)
527 return string((flags & Update::FitCursor) ? "FitCursor " : "")
528 + ((flags & Update::Force) ? "Force " : "")
529 + ((flags & Update::ForceDraw) ? "ForceDraw " : "")
530 + ((flags & Update::SinglePar) ? "SinglePar " : "")
531 + ((flags & Update::Decoration) ? "Decoration " : "");
536 void BufferView::processUpdateFlags(Update::flags flags)
538 LYXERR(Debug::PAINTING, "BufferView::processUpdateFlags( "
539 << flagsAsString(flags) << ") buffer: " << &buffer_);
541 // Case when no explicit update is requested.
542 if (flags == Update::None || !ready())
545 /* FIXME We would like to avoid doing this here, since it is very
546 * expensive and is called in updateBuffer already. However, even
547 * inserting a plain character can invalidate the overly fragile
548 * tables of child documents built by updateMacros. Some work is
549 * needed to avoid doing that when not necessary.
551 buffer_.updateMacros();
553 // First check whether the metrics and inset positions should be updated
554 if (flags & Update::Force) {
555 // This will compute all metrics and positions.
557 // metrics is done, full drawing is necessary now
558 flags = (flags & ~Update::Force) | Update::ForceDraw;
560 /* If a single paragraph update has been requested and we are not
561 * already repainting all, check whether this update changes the
562 * paragraph metrics. If it does, then compute all metrics (in
563 * case the paragraph is in an inset)
565 * We handle this before FitCursor because the later will require
566 * correct metrics at cursor position.
568 else if ((flags & Update::SinglePar) && !(flags & Update::ForceDraw)) {
569 if (!singleParUpdate())
572 else if (flags & Update::ForceDraw)
573 // This will compute only the needed metrics and update positions.
574 updateMetrics(false);
576 // Then make sure that the screen contains the cursor if needed
577 if (flags & Update::FitCursor) {
578 if (needsFitCursor()) {
579 // First try to make the selection start visible
580 // (which is just the cursor when there is no selection)
581 scrollToCursor(d->cursor_.selectionBegin(), SCROLL_VISIBLE);
582 // Metrics have to be updated
583 updateMetrics(false);
584 // Is the cursor visible? (only useful if cursor is at end of selection)
585 if (needsFitCursor()) {
586 // then try to make cursor visible instead
587 scrollToCursor(d->cursor_, SCROLL_VISIBLE);
588 // Metrics have to be recomputed (maybe again)
589 updateMetrics(false);
592 flags = (flags & ~Update::FitCursor) | Update::ForceDraw;
595 // Add flags to the the update flags. These will be reset to None
596 // after the redraw is actually done
597 d->update_flags_ = d->update_flags_ | flags;
598 LYXERR(Debug::PAINTING, "Cumulative flags: " << flagsAsString(flags));
600 // Now compute the update strategy
601 // Possibly values in flag are None, SinglePar, Decoration, ForceDraw
602 LATTEST((d->update_flags_ & ~(Update::None | Update::SinglePar
603 | Update::Decoration | Update::ForceDraw)) == 0);
605 if (d->update_flags_ & Update::ForceDraw)
606 d->update_strategy_ = FullScreenUpdate;
607 else if (d->update_flags_ & Update::Decoration)
608 d->update_strategy_ = DecorationUpdate;
609 else if (d->update_flags_ & Update::SinglePar)
610 d->update_strategy_ = SingleParUpdate;
612 // no need to redraw anything.
613 d->update_strategy_ = NoScreenUpdate;
616 updateHoveredInset();
619 buffer_.changed(false);
623 void BufferView::updateScrollbarParameters()
628 // We prefer fixed size line scrolling.
629 d->scrollbarParameters_.single_step = defaultRowHeight();
630 // We prefer full screen page scrolling.
631 d->scrollbarParameters_.page_step = height_;
633 Text & t = buffer_.text();
634 TextMetrics & tm = d->text_metrics_[&t];
636 LYXERR(Debug::SCROLLING, " Updating scrollbar: height: "
637 << t.paragraphs().size()
638 << " curr par: " << d->cursor_.bottom().pit()
639 << " default height " << defaultRowHeight());
641 size_t const parsize = t.paragraphs().size();
642 if (d->par_height_.size() != parsize) {
643 d->par_height_.clear();
644 // FIXME: We assume a default paragraph height of 2 rows. This
645 // should probably be pondered with the screen width.
646 d->par_height_.resize(parsize, defaultRowHeight() * 2);
649 // Look at paragraph heights on-screen
650 pair<pit_type, ParagraphMetrics const *> first = tm.first();
651 pair<pit_type, ParagraphMetrics const *> last = tm.last();
652 for (pit_type pit = first.first; pit <= last.first; ++pit) {
653 d->par_height_[pit] = tm.parMetrics(pit).height();
654 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
655 << d->par_height_[pit]);
658 int top_pos = first.second->top();
659 int bottom_pos = last.second->bottom();
660 bool first_visible = first.first == 0 && top_pos >= 0;
661 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
662 if (first_visible && last_visible) {
663 d->scrollbarParameters_.min = 0;
664 d->scrollbarParameters_.max = 0;
668 d->scrollbarParameters_.min = top_pos;
669 for (size_t i = 0; i != size_t(first.first); ++i)
670 d->scrollbarParameters_.min -= d->par_height_[i];
671 d->scrollbarParameters_.max = bottom_pos;
672 for (size_t i = last.first + 1; i != parsize; ++i)
673 d->scrollbarParameters_.max += d->par_height_[i];
675 // The reference is the top position so we remove one page.
676 if (lyxrc.scroll_below_document)
677 d->scrollbarParameters_.max -= minVisiblePart();
679 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
681 // 0 must be inside the range as it denotes the current position
682 if (d->scrollbarParameters_.max < 0)
683 d->scrollbarParameters_.max = 0;
684 if (d->scrollbarParameters_.min > 0)
685 d->scrollbarParameters_.min = 0;
689 ScrollbarParameters const & BufferView::scrollbarParameters() const
691 return d->scrollbarParameters_;
695 docstring BufferView::toolTip(int x, int y) const
697 // Get inset under mouse, if there is one.
698 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
700 // No inset, no tooltip...
702 return covering_inset->toolTip(*this, x, y);
706 string BufferView::contextMenu(int x, int y) const
708 //If there is a selection, return the containing inset menu
709 if (d->cursor_.selection())
710 return d->cursor_.inset().contextMenu(*this, x, y);
712 // Get inset under mouse, if there is one.
713 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
714 if (covering_inset) {
715 if (covering_inset->asInsetMath()) {
716 CoordCache::Insets const & inset_cache =
717 coordCache().getInsets();
718 Inset const * inner_inset = mathContextMenu(
719 covering_inset->asInsetMath()->asNestInset(),
722 return inner_inset->contextMenu(*this, x, y);
724 return covering_inset->contextMenu(*this, x, y);
727 return buffer_.inset().contextMenu(*this, x, y);
731 Inset const * BufferView::mathContextMenu(InsetMathNest const * inset,
732 CoordCache::Insets const & inset_cache, int x, int y) const
734 for (size_t i = 0; i < inset->nargs(); ++i) {
735 MathData const & ar = inset->cell(i);
736 for (size_t j = 0; j < ar.size(); ++j) {
737 string const name = lyxerr.debugging(Debug::MATHED)
738 ? insetName(ar[j].nucleus()->lyxCode())
740 LYXERR(Debug::MATHED, "Examining inset: " << name);
741 if (!ar[j].nucleus()->contextMenuName().empty()) {
742 if (inset_cache.covers(ar[j].nucleus(), x, y)) {
743 LYXERR(Debug::MATHED, "Hit inset: "
745 return ar[j].nucleus();
748 InsetMathNest const * imn =
749 ar[j].nucleus()->asNestInset();
751 Inset const * inner =
752 mathContextMenu(imn, inset_cache, x, y);
762 void BufferView::scrollDocView(int const pixels, bool update)
764 // The scrollbar values are relative to the top of the screen, therefore the
765 // offset is equal to the target value.
767 // No scrolling at all? No need to redraw anything
771 // If part of the existing paragraphs will remain visible, prefer to
773 TextMetrics const & tm = textMetrics(&buffer_.text());
774 if (tm.first().second->top() - pixels <= height_
775 && tm.last().second->bottom() - pixels >= 0) {
776 LYXERR(Debug::SCROLLING, "small skip");
777 d->anchor_ypos_ -= pixels;
778 processUpdateFlags(Update::ForceDraw);
782 // cut off at the top
783 if (pixels <= d->scrollbarParameters_.min) {
784 DocIterator dit = doc_iterator_begin(&buffer_);
785 showCursor(dit, SCROLL_VISIBLE, update);
786 LYXERR(Debug::SCROLLING, "scroll to top");
790 // cut off at the bottom
791 if (pixels >= d->scrollbarParameters_.max) {
792 DocIterator dit = doc_iterator_end(&buffer_);
794 showCursor(dit, SCROLL_VISIBLE, update);
795 LYXERR(Debug::SCROLLING, "scroll to bottom");
799 LYXERR(Debug::SCROLLING, "search paragraph");
800 // find paragraph at target position
801 int par_pos = d->scrollbarParameters_.min;
803 for (; i != int(d->par_height_.size()); ++i) {
804 par_pos += d->par_height_[i];
805 if (par_pos >= pixels)
809 if (par_pos < pixels) {
810 // It seems we didn't find the correct pit so stay on the safe side and
812 LYXERR0("scrolling position not found!");
813 scrollDocView(d->scrollbarParameters_.max, update);
817 DocIterator dit = doc_iterator_begin(&buffer_);
819 LYXERR(Debug::SCROLLING, "pixels = " << pixels << " -> scroll to pit " << i);
820 showCursor(dit, SCROLL_VISIBLE, update);
824 // FIXME: this method is not working well.
825 void BufferView::setCursorFromScrollbar()
827 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
829 int const height = 2 * defaultRowHeight();
830 int const first = height;
831 int const last = height_ - height;
833 Cursor const & oldcur = d->cursor_;
835 switch (cursorStatus(oldcur)) {
843 int const y = getPos(oldcur).y_;
844 newy = min(last, max(y, first));
848 // We reset the cursor because cursorStatus() does not
849 // work when the cursor is within mathed.
852 tm.setCursorFromCoordinates(cur, 0, newy);
854 // update the bufferview cursor and notify insets
855 // FIXME: Care about the d->cursor_ flags to redraw if needed
856 Cursor old = d->cursor_;
858 // the DEPM call in mouseSetCursor() might have destroyed the
859 // paragraph the cursor is in.
860 bool badcursor = old.fixIfBroken();
861 badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
863 d->cursor_.fixIfBroken();
867 Change const BufferView::getCurrentChange() const
869 if (!d->cursor_.selection())
870 return Change(Change::UNCHANGED);
872 DocIterator dit = d->cursor_.selectionBegin();
873 // The selected content might have been changed (see #7685)
874 dit = dit.getInnerText();
875 return dit.paragraph().lookupChange(dit.pos());
879 // this could be used elsewhere as well?
880 // FIXME: This does not work within mathed!
881 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
883 Point const p = getPos(dit);
886 if (p.y_ > workHeight())
892 void BufferView::bookmarkEditPosition()
894 // Don't eat cpu time for each keystroke
895 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
898 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
902 void BufferView::saveBookmark(unsigned int idx)
904 if (buffer().isInternal())
907 // tentatively save bookmark, id and pos will be used to
908 // acturately locate a bookmark in a 'live' lyx session.
909 // pit and pos will be updated with bottom level pit/pos
911 theSession().bookmarks().save(
913 d->cursor_.bottom().pit(),
914 d->cursor_.bottom().pos(),
915 d->cursor_.paragraph().id(),
920 // emit message signal.
921 message(_("Save bookmark"));
925 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
926 int top_id, pos_type top_pos)
928 bool success = false;
931 d->cursor_.clearSelection();
933 // if a valid par_id is given, try it first
934 // This is the case for a 'live' bookmark when unique paragraph ID
935 // is used to track bookmarks.
937 dit = buffer_.getParFromID(top_id);
939 dit.pos() = min(dit.paragraph().size(), top_pos);
940 // Some slices of the iterator may not be
941 // reachable (e.g. closed collapsible inset)
942 // so the dociterator may need to be
943 // shortened. Otherwise, setCursor may crash
944 // lyx when the cursor can not be set to these
946 size_t const n = dit.depth();
947 for (size_t i = 0; i < n; ++i)
948 if (!dit[i].inset().editable()) {
956 // if top_id == 0, or searching through top_id failed
957 // This is the case for a 'restored' bookmark when only bottom
958 // (document level) pit was saved. Because of this, bookmark
959 // restoration is inaccurate. If a bookmark was within an inset,
960 // it will be restored to the left of the outmost inset that contains
962 if (!success && bottom_pit < int(buffer_.paragraphs().size())) {
963 dit = doc_iterator_begin(&buffer_);
965 dit.pit() = bottom_pit;
966 dit.pos() = min(bottom_pos, dit.paragraph().size());
971 // Note: only bottom (document) level pit is set.
973 // set the current font.
974 d->cursor_.setCurrentFont();
975 // Do not forget to reset the anchor (see #9912)
976 d->cursor_.resetAnchor();
977 processUpdateFlags(Update::Force | Update::FitCursor);
984 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
986 if (d->cursor_.real_current_font.isRightToLeft()) {
987 if (d->intl_.keymap == Intl::PRIMARY)
988 d->intl_.keyMapSec();
990 if (d->intl_.keymap == Intl::SECONDARY)
991 d->intl_.keyMapPrim();
994 d->intl_.getTransManager().translateAndInsert(c, t, cur);
998 int BufferView::workWidth() const
1004 void BufferView::recenter()
1006 showCursor(d->cursor_, SCROLL_CENTER, true);
1010 void BufferView::showCursor()
1012 showCursor(d->cursor_, SCROLL_VISIBLE, true);
1016 void BufferView::showCursor(DocIterator const & dit, ScrollType how,
1019 if (scrollToCursor(dit, how) && update)
1020 processUpdateFlags(Update::ForceDraw);
1024 bool BufferView::scrollToCursor(DocIterator const & dit, ScrollType how)
1026 // We are not properly started yet, delay until resizing is done.
1030 if (how == SCROLL_CENTER)
1031 LYXERR(Debug::SCROLLING, "Centering cursor in workarea");
1032 else if (how == SCROLL_TOP)
1033 LYXERR(Debug::SCROLLING, "Setting cursor to top of workarea");
1035 LYXERR(Debug::SCROLLING, "Making sure cursor is visible in workarea");
1037 CursorSlice const & bot = dit.bottom();
1038 TextMetrics & tm = textMetrics(bot.text());
1040 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
1041 pos_type bot_pit = bot.pit();
1042 if (bot_pit > max_pit) {
1043 // FIXME: Why does this happen?
1044 LYXERR0("bottom pit is greater that max pit: "
1045 << bot_pit << " > " << max_pit);
1049 if (bot_pit == tm.first().first - 1)
1050 tm.newParMetricsUp();
1051 else if (bot_pit == tm.last().first + 1)
1052 tm.newParMetricsDown();
1054 if (tm.contains(bot_pit) && how == SCROLL_VISIBLE) {
1055 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
1056 LBUFERR(!pm.rows().empty());
1057 // FIXME: smooth scrolling doesn't work in mathed.
1058 CursorSlice const & cs = dit.innerTextSlice();
1059 int const ypos = pm.position() + coordOffset(dit).y_;
1060 ParagraphMetrics const & inner_pm =
1061 textMetrics(cs.text()).parMetrics(cs.pit());
1062 Dimension const & row_dim =
1063 inner_pm.getRow(cs.pos(), dit.boundary()).dim();
1066 // We try to visualize the whole row, if the row height is larger than
1067 // the screen height, we scroll to a heuristic value of height_ / 4.
1068 // FIXME: This heuristic value should be replaced by a recursive search
1069 // for a row in the inset that can be visualized completely.
1070 if (row_dim.height() > height_) {
1071 if (ypos < defaultRowHeight())
1072 scrolled = scroll(ypos - height_ / 4);
1073 else if (ypos > height_ - defaultRowHeight())
1074 scrolled = scroll(ypos - 3 * height_ / 4);
1077 // If the top part of the row falls of the screen, we scroll
1078 // up to align the top of the row with the top of the screen.
1079 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
1080 int const ynew = row_dim.ascent();
1081 scrolled = scrollUp(ynew - ypos);
1084 // If the bottom of the row falls of the screen, we scroll down.
1085 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
1086 int const ynew = height_ - row_dim.descent();
1087 scrolled = scrollDown(ypos - ynew);
1090 // else, nothing to do, the cursor is already visible so we just return.
1091 return scrolled != 0;
1094 // fix inline completion position
1095 if (d->inlineCompletionPos_.fixIfBroken())
1096 d->inlineCompletionPos_ = DocIterator();
1098 tm.redoParagraph(bot_pit);
1099 int const offset = coordOffset(dit).y_;
1100 pit_type const old_pit = d->anchor_pit_;
1101 d->anchor_pit_ = bot_pit;
1103 CursorSlice const & cs = dit.innerTextSlice();
1104 ParagraphMetrics const & inner_pm =
1105 textMetrics(cs.text()).parMetrics(cs.pit());
1106 Dimension const & row_dim =
1107 inner_pm.getRow(cs.pos(), dit.boundary()).dim();
1109 int const old_ypos = d->anchor_ypos_;
1110 d->anchor_ypos_ = - offset + row_dim.ascent();
1111 if (how == SCROLL_CENTER)
1112 d->anchor_ypos_ += height_/2 - row_dim.height() / 2;
1113 else if (offset > height_)
1114 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
1116 d->anchor_ypos_ = defaultRowHeight() * 2;
1118 return d->anchor_ypos_ != old_ypos || d->anchor_pit_ != old_pit;
1122 void BufferView::makeDocumentClass()
1124 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1125 buffer_.params().makeDocumentClass(buffer_.isClone(), buffer_.isInternal());
1126 updateDocumentClass(olddc);
1130 void BufferView::updateDocumentClass(DocumentClassConstPtr olddc)
1132 StableDocIterator backcur(d->cursor_);
1133 ErrorList & el = buffer_.errorList("Class Switch");
1134 cap::switchBetweenClasses(
1135 olddc, buffer_.params().documentClassPtr(),
1136 static_cast<InsetText &>(buffer_.inset()), el);
1138 setCursor(backcur.asDocIterator(&buffer_));
1140 buffer_.errors("Class Switch");
1144 /** Return the change status at cursor position, taking into account the
1145 * status at each level of the document iterator (a table in a deleted
1146 * footnote is deleted).
1147 * When \param outer is true, the top slice is not looked at.
1149 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
1151 size_t const depth = dit.depth() - (outer ? 1 : 0);
1153 for (size_t i = 0 ; i < depth ; ++i) {
1154 CursorSlice const & slice = dit[i];
1155 if (!slice.inset().inMathed()
1156 && slice.pos() < slice.paragraph().size()) {
1157 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
1158 if (ch != Change::UNCHANGED)
1162 return Change::UNCHANGED;
1166 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1168 FuncCode const act = cmd.action();
1170 // Can we use a readonly buffer?
1171 if (buffer_.isReadonly()
1172 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1173 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1174 if (buffer_.hasReadonlyFlag())
1175 flag.message(from_utf8(N_("Document is read-only")));
1177 flag.message(from_utf8(N_("Document has been modified externally")));
1178 flag.setEnabled(false);
1182 // Are we in a DELETED change-tracking region?
1183 if (lookupChangeType(d->cursor_, true) == Change::DELETED
1184 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1185 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1186 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1187 flag.setEnabled(false);
1191 Cursor & cur = d->cursor_;
1193 if (cur.getStatus(cmd, flag))
1198 // FIXME: This is a bit problematic because we don't check if this is
1199 // a document BufferView or not for these LFUNs. We probably have to
1200 // dispatch both to currentBufferView() and, if that fails,
1201 // to documentBufferView(); same as we do now for current Buffer and
1202 // document Buffer. Ideally those LFUN should go to Buffer as they
1203 // operate on the full Buffer and the cursor is only needed either for
1204 // an Undo record or to restore a cursor position. But we don't know
1205 // how to do that inside Buffer of course.
1206 case LFUN_BUFFER_PARAMS_APPLY:
1207 case LFUN_LAYOUT_MODULES_CLEAR:
1208 case LFUN_LAYOUT_MODULE_ADD:
1209 case LFUN_LAYOUT_RELOAD:
1210 case LFUN_TEXTCLASS_APPLY:
1211 case LFUN_TEXTCLASS_LOAD:
1212 flag.setEnabled(!buffer_.isReadonly());
1216 // We do not use the LyXAction flag for readonly because Undo sets the
1217 // buffer clean/dirty status by itself.
1218 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1221 // We do not use the LyXAction flag for readonly because Redo sets the
1222 // buffer clean/dirty status by itself.
1223 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1225 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1226 case LFUN_FILE_INSERT_PLAINTEXT: {
1227 docstring const & fname = cmd.argument();
1228 if (!FileName::isAbsolute(to_utf8(fname))) {
1229 flag.message(_("Absolute filename expected."));
1232 flag.setEnabled(cur.inTexted());
1235 case LFUN_FILE_INSERT:
1236 case LFUN_BOOKMARK_SAVE:
1237 // FIXME: Actually, these LFUNS should be moved to Text
1238 flag.setEnabled(cur.inTexted());
1241 case LFUN_FONT_STATE:
1242 case LFUN_LABEL_INSERT:
1243 case LFUN_INFO_INSERT:
1244 case LFUN_PARAGRAPH_GOTO:
1245 case LFUN_NOTE_NEXT:
1246 case LFUN_REFERENCE_NEXT:
1247 case LFUN_WORD_FIND:
1248 case LFUN_WORD_FIND_FORWARD:
1249 case LFUN_WORD_FIND_BACKWARD:
1250 case LFUN_WORD_REPLACE:
1253 case LFUN_MARK_TOGGLE:
1254 case LFUN_SEARCH_STRING_SET:
1255 case LFUN_SCREEN_RECENTER:
1256 case LFUN_SCREEN_SHOW_CURSOR:
1257 case LFUN_BIBTEX_DATABASE_ADD:
1258 case LFUN_BIBTEX_DATABASE_DEL:
1259 case LFUN_BIBTEX_DATABASE_LIST:
1260 case LFUN_STATISTICS:
1261 case LFUN_KEYMAP_OFF:
1262 case LFUN_KEYMAP_PRIMARY:
1263 case LFUN_KEYMAP_SECONDARY:
1264 case LFUN_KEYMAP_TOGGLE:
1265 case LFUN_INSET_SELECT_ALL:
1266 flag.setEnabled(true);
1269 case LFUN_GRAPHICS_UNIFY:
1270 flag.setEnabled(cur.countInsetsInSelection(GRAPHICS_CODE)>1);
1273 case LFUN_WORD_FINDADV: {
1274 FindAndReplaceOptions opt;
1275 istringstream iss(to_utf8(cmd.argument()));
1277 flag.setEnabled(opt.repl_buf_name.empty()
1278 || !buffer_.isReadonly());
1282 case LFUN_LABEL_GOTO:
1283 flag.setEnabled(!cmd.argument().empty()
1284 || getInsetByCode<InsetRef>(cur, REF_CODE)
1285 || getInsetByCode<InsetMathRef>(cur, MATH_REF_CODE));
1288 case LFUN_CHANGES_MERGE:
1289 case LFUN_CHANGE_NEXT:
1290 case LFUN_CHANGE_PREVIOUS:
1291 case LFUN_ALL_CHANGES_ACCEPT:
1292 case LFUN_ALL_CHANGES_REJECT:
1293 flag.setEnabled(buffer_.areChangesPresent());
1296 case LFUN_SCREEN_UP:
1297 case LFUN_SCREEN_DOWN:
1299 case LFUN_SCREEN_UP_SELECT:
1300 case LFUN_SCREEN_DOWN_SELECT:
1301 case LFUN_INSET_FORALL:
1302 flag.setEnabled(true);
1305 case LFUN_LAYOUT_TABULAR:
1306 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1310 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1313 case LFUN_LAYOUT_PARAGRAPH:
1314 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1317 case LFUN_BRANCH_ADD_INSERT:
1318 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1321 case LFUN_DIALOG_SHOW_NEW_INSET:
1322 // FIXME: this is wrong, but I do not understand the
1324 if (cur.inset().lyxCode() == CAPTION_CODE)
1325 return cur.inset().getStatus(cur, cmd, flag);
1326 // FIXME we should consider passthru paragraphs too.
1327 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1330 case LFUN_CITATION_INSERT: {
1331 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1332 // FIXME: This could turn in a recursive hell.
1333 // Shouldn't we use Buffer::getStatus() instead?
1334 flag.setEnabled(lyx::getStatus(fr).enabled());
1337 case LFUN_INSET_APPLY: {
1338 string const name = cmd.getArg(0);
1339 Inset * inset = editedInset(name);
1341 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1342 if (!inset->getStatus(cur, fr, flag)) {
1343 // Every inset is supposed to handle this
1344 LASSERT(false, break);
1347 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1348 flag = lyx::getStatus(fr);
1354 flag.setEnabled(cur.selection());
1357 case LFUN_STATISTICS_REFERENCE_CLAMP: {
1358 // disable optitem reset if clamp not used
1359 if (cmd.argument() == "reset" && d->stats_ref_value_c_ == 0) {
1360 flag.setEnabled(false);
1363 flag.setEnabled(true);
1376 Inset * BufferView::editedInset(string const & name) const
1378 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1379 return it == d->edited_insets_.end() ? nullptr : it->second;
1383 void BufferView::editInset(string const & name, Inset * inset)
1386 d->edited_insets_[name] = inset;
1388 d->edited_insets_.erase(name);
1392 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1394 LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1396 string const argument = to_utf8(cmd.argument());
1397 Cursor & cur = d->cursor_;
1400 // Don't dispatch function that does not apply to internal buffers.
1401 if (buffer_.isInternal()
1402 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1405 // We'll set this back to false if need be.
1406 bool dispatched = true;
1407 buffer_.undo().beginUndoGroup();
1409 FuncCode const act = cmd.action();
1412 case LFUN_BUFFER_PARAMS_APPLY: {
1413 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1414 cur.recordUndoBufferParams();
1415 istringstream ss(to_utf8(cmd.argument()));
1418 int const unknown_tokens = buffer_.readHeader(lex);
1419 if (unknown_tokens != 0) {
1420 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1421 << unknown_tokens << " unknown token"
1422 << (unknown_tokens == 1 ? "" : "s"));
1424 updateDocumentClass(olddc);
1426 // We are most certainly here because of a change in the document
1427 // It is then better to make sure that all dialogs are in sync with
1428 // current document settings.
1429 dr.screenUpdate(Update::Force | Update::FitCursor);
1430 dr.forceBufferUpdate();
1434 case LFUN_LAYOUT_MODULES_CLEAR: {
1435 // FIXME: this modifies the document in cap::switchBetweenClasses
1436 // without calling recordUndo. Fix this before using
1437 // recordUndoBufferParams().
1438 cur.recordUndoFullBuffer();
1439 buffer_.params().clearLayoutModules();
1440 makeDocumentClass();
1441 dr.screenUpdate(Update::Force);
1442 dr.forceBufferUpdate();
1446 case LFUN_LAYOUT_MODULE_ADD: {
1447 BufferParams const & params = buffer_.params();
1448 if (!params.layoutModuleCanBeAdded(argument)) {
1449 LYXERR0("Module `" << argument <<
1450 "' cannot be added due to failed requirements or "
1451 "conflicts with installed modules.");
1454 // FIXME: this modifies the document in cap::switchBetweenClasses
1455 // without calling recordUndo. Fix this before using
1456 // recordUndoBufferParams().
1457 cur.recordUndoFullBuffer();
1458 buffer_.params().addLayoutModule(argument);
1459 makeDocumentClass();
1460 dr.screenUpdate(Update::Force);
1461 dr.forceBufferUpdate();
1465 case LFUN_TEXTCLASS_APPLY: {
1466 // since this shortcircuits, the second call is made only if
1468 bool const success =
1469 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1470 LayoutFileList::get().load(argument, buffer_.filePath());
1472 docstring s = bformat(_("The document class `%1$s' "
1473 "could not be loaded."), from_utf8(argument));
1474 frontend::Alert::error(_("Could not load class"), s);
1478 LayoutFile const * old_layout = buffer_.params().baseClass();
1479 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1481 if (old_layout == new_layout)
1485 // Save the old, possibly modular, layout for use in conversion.
1486 // FIXME: this modifies the document in cap::switchBetweenClasses
1487 // without calling recordUndo. Fix this before using
1488 // recordUndoBufferParams().
1489 cur.recordUndoFullBuffer();
1490 buffer_.params().setBaseClass(argument, buffer_.layoutPos());
1491 makeDocumentClass();
1492 dr.screenUpdate(Update::Force);
1493 dr.forceBufferUpdate();
1497 case LFUN_TEXTCLASS_LOAD: {
1498 // since this shortcircuits, the second call is made only if
1500 bool const success =
1501 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1502 LayoutFileList::get().load(argument, buffer_.filePath());
1504 docstring s = bformat(_("The document class `%1$s' "
1505 "could not be loaded."), from_utf8(argument));
1506 frontend::Alert::error(_("Could not load class"), s);
1511 case LFUN_LAYOUT_RELOAD: {
1512 LayoutFileIndex bc = buffer_.params().baseClassID();
1513 LayoutFileList::get().reset(bc);
1514 buffer_.params().setBaseClass(bc, buffer_.layoutPos());
1515 makeDocumentClass();
1516 dr.screenUpdate(Update::Force);
1517 dr.forceBufferUpdate();
1522 dr.setMessage(_("Undo"));
1523 cur.clearSelection();
1524 // We need to find out if the bibliography information
1525 // has changed. See bug #11055.
1526 // So these should not be references...
1527 string const engine = buffer().params().citeEngine();
1528 CiteEngineType const enginetype = buffer().params().citeEngineType();
1529 if (!cur.undoAction())
1530 dr.setMessage(_("No further undo information"));
1532 dr.screenUpdate(Update::Force | Update::FitCursor);
1533 dr.forceBufferUpdate();
1534 resetInlineCompletionPos();
1535 if (buffer().params().citeEngine() != engine ||
1536 buffer().params().citeEngineType() != enginetype)
1537 buffer().invalidateCiteLabels();
1543 dr.setMessage(_("Redo"));
1544 cur.clearSelection();
1545 // We need to find out if the bibliography information
1546 // has changed. See bug #11055.
1547 // So these should not be references...
1548 string const engine = buffer().params().citeEngine();
1549 CiteEngineType const enginetype = buffer().params().citeEngineType();
1550 if (!cur.redoAction())
1551 dr.setMessage(_("No further redo information"));
1553 dr.screenUpdate(Update::Force | Update::FitCursor);
1554 dr.forceBufferUpdate();
1555 resetInlineCompletionPos();
1556 if (buffer().params().citeEngine() != engine ||
1557 buffer().params().citeEngineType() != enginetype)
1558 buffer().invalidateCiteLabels();
1563 case LFUN_FONT_STATE:
1564 dr.setMessage(cur.currentState(false));
1567 case LFUN_BOOKMARK_SAVE:
1568 dr.screenUpdate(Update::Force);
1569 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1572 case LFUN_LABEL_GOTO: {
1573 docstring label = cmd.argument();
1574 if (label.empty()) {
1576 getInsetByCode<InsetRef>(cur, REF_CODE);
1578 label = inset->getParam("reference");
1579 // persistent=false: use temp_bookmark
1583 if (!label.empty()) {
1585 // at the moment, this is redundant, since gotoLabel will
1586 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1588 dr.screenUpdate(Update::Force | Update::FitCursor);
1590 InsetMathRef * minset =
1591 getInsetByCode<InsetMathRef>(cur, MATH_REF_CODE);
1593 lyx::dispatch(FuncRequest(LFUN_LABEL_GOTO,
1594 minset->getTarget()));
1599 case LFUN_PARAGRAPH_GOTO: {
1600 int const id = convert<int>(cmd.getArg(0));
1601 pos_type const pos = convert<int>(cmd.getArg(1));
1604 string const str_id_end = cmd.getArg(2);
1605 string const str_pos_end = cmd.getArg(3);
1607 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1608 b = theBufferList().next(b)) {
1611 curs.setCursor(b->getParFromID(id));
1613 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1617 LYXERR(Debug::INFO, "Paragraph " << curs.paragraph().id()
1618 << " found in buffer `"
1619 << b->absFileName() << "'.");
1621 if (b == &buffer_) {
1623 if (str_id_end.empty() || str_pos_end.empty()) {
1626 mouseSetCursor(curs);
1629 int const id_end = convert<int>(str_id_end);
1630 pos_type const pos_end = convert<int>(str_pos_end);
1631 success = setCursorFromEntries({id, pos},
1634 if (success && scrollToCursor(d->cursor_, SCROLL_TOP))
1635 dr.screenUpdate(Update::Force);
1637 // Switch to other buffer view and resend cmd
1638 lyx::dispatch(FuncRequest(
1639 LFUN_BUFFER_SWITCH, b->absFileName()));
1647 case LFUN_NOTE_NEXT:
1648 if (gotoInset(this, { NOTE_CODE }, false))
1649 dr.screenUpdate(Update::Force);
1652 case LFUN_REFERENCE_NEXT: {
1653 if (gotoInset(this, { LABEL_CODE, REF_CODE }, true))
1654 dr.screenUpdate(Update::Force);
1658 case LFUN_CHANGE_NEXT:
1659 findNextChange(this);
1660 if (cur.inset().isTable())
1661 // In tables, there might be whole changed rows or columns
1663 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1664 dr.screenUpdate(Update::Force | Update::FitCursor);
1667 case LFUN_CHANGE_PREVIOUS:
1668 findPreviousChange(this);
1669 if (cur.inset().isTable())
1670 // In tables, there might be whole changed rows or columns
1672 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1673 dr.screenUpdate(Update::Force | Update::FitCursor);
1676 case LFUN_CHANGES_MERGE:
1677 if (findNextChange(this) || findPreviousChange(this)) {
1678 dr.screenUpdate(Update::Force | Update::FitCursor);
1679 dr.forceBufferUpdate();
1680 showDialog("changes");
1684 case LFUN_ALL_CHANGES_ACCEPT: {
1685 // select complete document
1687 cur.selHandle(true);
1688 buffer_.text().cursorBottom(cur);
1689 // accept everything in a single step to support atomic undo
1690 // temporarily disable track changes in order to end with really
1691 // no new (e.g., DPSM-caused) changes (see #7487)
1692 bool const track = buffer_.params().track_changes;
1693 buffer_.params().track_changes = false;
1694 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1695 buffer_.params().track_changes = track;
1697 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1698 dr.screenUpdate(Update::Force | Update::FitCursor);
1699 dr.forceBufferUpdate();
1703 case LFUN_ALL_CHANGES_REJECT: {
1704 // select complete document
1706 cur.selHandle(true);
1707 buffer_.text().cursorBottom(cur);
1708 // reject everything in a single step to support atomic undo
1709 // temporarily disable track changes in order to end with really
1710 // no new (e.g., DPSM-caused) changes (see #7487)
1711 bool const track = buffer_.params().track_changes;
1712 buffer_.params().track_changes = false;
1713 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1714 buffer_.params().track_changes = track;
1716 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1717 dr.screenUpdate(Update::Force | Update::FitCursor);
1718 dr.forceBufferUpdate();
1722 case LFUN_WORD_FIND_FORWARD:
1723 case LFUN_WORD_FIND_BACKWARD: {
1724 docstring searched_string;
1726 if (!cmd.argument().empty()) {
1727 setSearchRequestCache(cmd.argument());
1728 searched_string = cmd.argument();
1730 searched_string = searchRequestCache();
1733 if (searched_string.empty())
1736 docstring const data =
1737 find2string(searched_string, false, false,
1738 act == LFUN_WORD_FIND_FORWARD, false, false, false);
1739 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1741 dr.screenUpdate(Update::Force | Update::FitCursor);
1743 dr.setMessage(_("Search string not found!"));
1747 case LFUN_WORD_FIND: {
1748 docstring arg = cmd.argument();
1750 arg = searchRequestCache();
1752 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1755 if (lyxfind(this, FuncRequest(act, arg)))
1756 dr.screenUpdate(Update::Force | Update::FitCursor);
1758 dr.setMessage(_("Search string not found!"));
1760 setSearchRequestCache(arg);
1764 case LFUN_SEARCH_STRING_SET: {
1765 docstring pattern = cmd.argument();
1766 if (!pattern.empty()) {
1767 setSearchRequestCache(pattern);
1770 if (cur.selection())
1771 pattern = cur.selectionAsString(false);
1772 else if (!cur.inTexted())
1773 break; // not suitable for selectWord at cursor
1775 pos_type spos = cur.pos();
1776 cur.innerText()->selectWord(cur, WHOLE_WORD);
1777 pattern = cur.selectionAsString(false);
1778 cur.selection(false);
1781 setSearchRequestCache(pattern);
1785 case LFUN_WORD_REPLACE: {
1786 if (lyxreplace(this, cmd)) {
1787 dr.forceBufferUpdate();
1788 dr.screenUpdate(Update::Force | Update::FitCursor);
1791 dr.setMessage(_("Search string not found!"));
1795 case LFUN_WORD_FINDADV: {
1796 FindAndReplaceOptions opt;
1797 istringstream iss(to_utf8(cmd.argument()));
1799 if (findAdv(this, opt)) {
1800 dr.screenUpdate(Update::Force | Update::FitCursor);
1810 case LFUN_INDEX_TAG_ALL: {
1815 Inset * ins = cur.nextInset();
1816 if (!ins || ins->lyxCode() != INDEX_CODE)
1817 // not at index inset
1820 // clone the index inset
1822 new InsetIndex(static_cast<InsetIndex &>(*cur.nextInset()));
1823 // In order to avoid duplication, we compare the
1824 // LaTeX output if we find another index inset after
1826 odocstringstream oilatex;
1827 otexstream oits(oilatex);
1828 OutputParams rp(&cur.buffer()->params().encoding());
1829 ins->latex(oits, rp);
1830 cap::copyInsetToTemp(cur, cins);
1832 // move backwards into preceding word
1833 // skip over other index insets
1834 cur.backwardPosIgnoreCollapsed();
1836 if (cur.inset().lyxCode() == INDEX_CODE)
1838 else if (cur.prevInset() && cur.prevInset()->lyxCode() == INDEX_CODE)
1839 cur.backwardPosIgnoreCollapsed();
1843 if (!cur.inTexted()) {
1844 // Nothing to do here.
1845 setCursorFromInset(ins);
1848 // Get word or selection
1849 cur.text()->selectWord(cur, WHOLE_WORD);
1850 docstring const searched_string = cur.selectionAsString(false);
1851 if (searched_string.empty())
1853 // Start from the beginning
1854 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
1855 while (findOne(this, searched_string,
1856 false,// case sensitive
1857 true,// match whole word only
1859 false,//find deleted
1863 false// only selection
1865 cur.clearSelection();
1866 Inset * ains = cur.nextInset();
1867 if (ains && ains->lyxCode() == INDEX_CODE) {
1868 // We have an index inset.
1869 // Check whether it has the same
1870 // LaTeX content and move on if so.
1871 odocstringstream filatex;
1872 otexstream fits(filatex);
1873 ains->latex(fits, rp);
1874 if (oilatex.str() == filatex.str())
1877 // Paste the inset and possibly continue
1878 cap::pasteFromTemp(cursor(), cursor().buffer()->errorList("Paste"));
1880 // Go back to start position.
1881 setCursorFromInset(ins);
1882 dr.screenUpdate(cur.result().screenUpdate());
1883 if (cur.result().needBufferUpdate())
1884 dr.forceBufferUpdate();
1889 cur.clearSelection();
1890 dr.setMessage(from_utf8(N_("Mark off")));
1894 cur.clearSelection();
1896 dr.setMessage(from_utf8(N_("Mark on")));
1899 case LFUN_MARK_TOGGLE:
1900 cur.selection(false);
1903 dr.setMessage(from_utf8(N_("Mark removed")));
1906 dr.setMessage(from_utf8(N_("Mark set")));
1911 case LFUN_SCREEN_SHOW_CURSOR:
1915 case LFUN_SCREEN_RECENTER:
1919 case LFUN_BIBTEX_DATABASE_ADD: {
1920 Cursor tmpcur = cur;
1921 findInset(tmpcur, { BIBTEX_CODE }, false);
1922 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1925 if (inset->addDatabase(cmd.argument()))
1926 dr.forceBufferUpdate();
1931 case LFUN_BIBTEX_DATABASE_DEL: {
1932 Cursor tmpcur = cur;
1933 findInset(tmpcur, { BIBTEX_CODE }, false);
1934 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1937 if (inset->delDatabase(cmd.argument()))
1938 dr.forceBufferUpdate();
1943 case LFUN_GRAPHICS_UNIFY: {
1945 cur.recordUndoFullBuffer();
1947 DocIterator from, to;
1948 from = cur.selectionBegin();
1949 to = cur.selectionEnd();
1951 string const newId = cmd.getArg(0);
1952 bool fetchId = newId.empty(); //if we wait for groupId from first graphics inset
1954 InsetGraphicsParams grp_par;
1956 InsetGraphics::string2params(graphics::getGroupParams(buffer_, newId), buffer_, grp_par);
1958 if (!from.nextInset()) //move to closest inset
1959 from.forwardInset();
1961 while (!from.empty() && from < to) {
1962 Inset * inset = from.nextInset();
1965 InsetGraphics * ig = inset->asInsetGraphics();
1967 InsetGraphicsParams inspar = ig->getParams();
1972 grp_par.filename = inspar.filename;
1973 ig->setParams(grp_par);
1976 from.forwardInset();
1978 dr.screenUpdate(Update::Force); //needed if triggered from context menu
1982 case LFUN_BIBTEX_DATABASE_LIST: {
1983 docstring_list const & files = buffer_.getBibfiles();
1986 char const separator(os::path_separator());
1987 for (auto const & file : files) {
1991 result += separator;
1993 FileName const fn = buffer_.getBibfilePath(file);
1994 string const path = fn.realPath();
1995 result += from_utf8(os::external_path(path));
1997 dr.setMessage(result);
2001 case LFUN_STATISTICS: {
2002 DocIterator from, to;
2003 if (cur.selection()) {
2004 from = cur.selectionBegin();
2005 to = cur.selectionEnd();
2007 from = doc_iterator_begin(&buffer_);
2008 to = doc_iterator_end(&buffer_);
2010 buffer_.updateStatistics(from, to);
2011 int const words = buffer_.wordCount();
2012 int const chars = buffer_.charCount(false);
2013 int const chars_blanks = buffer_.charCount(true);
2015 if (cur.selection())
2016 message = _("Statistics for the selection:");
2018 message = _("Statistics for the document:");
2021 message += bformat(_("%1$d words"), words);
2023 message += _("One word");
2025 if (chars_blanks != 1)
2026 message += bformat(_("%1$d characters"), chars_blanks);
2028 message += _("One character");
2031 message += bformat(_("%1$d characters (no blanks)"), chars);
2033 message += _("One character (no blanks)");
2035 Alert::information(_("Statistics"), message);
2039 case LFUN_STATISTICS_REFERENCE_CLAMP: {
2040 d->stats_update_trigger_ = true;
2041 if (cmd.argument() == "reset") {
2042 d->stats_ref_value_w_ = d->stats_ref_value_c_ = d->stats_ref_value_nb_ = 0;
2046 DocIterator from, to;
2047 from = doc_iterator_begin(&buffer_);
2048 to = doc_iterator_end(&buffer_);
2049 buffer_.updateStatistics(from, to);
2051 d->stats_ref_value_w_ = buffer_.wordCount();
2052 d->stats_ref_value_c_ = buffer_.charCount(true);
2053 d->stats_ref_value_nb_ = buffer_.charCount(false);
2058 case LFUN_SCREEN_UP:
2059 case LFUN_SCREEN_DOWN: {
2060 Point p = getPos(cur);
2061 // This code has been commented out to enable to scroll down a
2062 // document, even if there are large insets in it (see bug #5465).
2063 /*if (p.y_ < 0 || p.y_ > height_) {
2064 // The cursor is off-screen so recenter before proceeding.
2068 int const scrolled = scroll(act == LFUN_SCREEN_UP
2069 ? -height_ : height_);
2070 if (act == LFUN_SCREEN_UP && scrolled > -height_)
2072 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
2073 p = Point(width_, height_);
2074 bool const in_texted = cur.inTexted();
2075 cur.setCursor(doc_iterator_begin(cur.buffer()));
2076 cur.selHandle(false);
2077 // Force an immediate computation of metrics because we need it below
2079 processUpdateFlags(Update::Force);
2081 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
2082 true, act == LFUN_SCREEN_UP);
2083 //FIXME: what to do with cur.x_target()?
2084 bool update = in_texted && cur.bv().checkDepm(cur, old);
2087 if (update || cur.mark())
2088 dr.screenUpdate(Update::Force | Update::FitCursor);
2090 dr.forceBufferUpdate();
2095 string const scroll_type = cmd.getArg(0);
2096 int scroll_step = 0;
2097 if (scroll_type == "line")
2098 scroll_step = d->scrollbarParameters_.single_step;
2099 else if (scroll_type == "page")
2100 scroll_step = d->scrollbarParameters_.page_step;
2103 string const scroll_quantity = cmd.getArg(1);
2104 if (scroll_quantity == "up")
2105 scrollUp(scroll_step);
2106 else if (scroll_quantity == "down")
2107 scrollDown(scroll_step);
2109 int const scroll_value = convert<int>(scroll_quantity);
2111 scroll(scroll_step * scroll_value);
2113 dr.screenUpdate(Update::ForceDraw);
2114 dr.forceBufferUpdate();
2118 case LFUN_SCREEN_UP_SELECT: {
2119 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
2120 cur.selHandle(true);
2121 if (isTopScreen()) {
2122 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
2126 int y = getPos(cur).y_;
2127 int const ymin = y - height_ + defaultRowHeight();
2128 while (y > ymin && cur.up())
2132 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
2136 case LFUN_SCREEN_DOWN_SELECT: {
2137 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
2138 cur.selHandle(true);
2139 if (isBottomScreen()) {
2140 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
2144 int y = getPos(cur).y_;
2145 int const ymax = y + height_ - defaultRowHeight();
2146 while (y < ymax && cur.down())
2150 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
2155 case LFUN_INSET_SELECT_ALL: {
2156 // true if all cells are selected
2157 bool const all_selected = cur.depth() > 1
2158 && cur.selBegin().at_begin()
2159 && cur.selEnd().at_end();
2160 // true if some cells are selected
2161 bool const cells_selected = cur.depth() > 1
2162 && cur.selBegin().at_cell_begin()
2163 && cur.selEnd().at_cell_end();
2164 if (all_selected || (cells_selected && !cur.inset().isTable())) {
2165 // All the contents of the inset if selected, or only at
2166 // least one cell but inset is not a table.
2167 // Select the inset from outside.
2170 cur.selection(true);
2172 } else if (cells_selected) {
2173 // At least one complete cell is selected and inset is a table.
2179 cur.selection(true);
2180 cur.idx() = cur.lastidx();
2181 cur.pit() = cur.lastpit();
2182 cur.pos() = cur.lastpos();
2184 // select current cell
2188 cur.selection(true);
2189 cur.pit() = cur.lastpit();
2190 cur.pos() = cur.lastpos();
2192 cur.setCurrentFont();
2193 dr.screenUpdate(Update::Force);
2198 case LFUN_UNICODE_INSERT: {
2199 if (cmd.argument().empty())
2202 FuncCode code = cur.inset().currentMode() == Inset::MATH_MODE ?
2203 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
2206 docstring const arg = from_utf8(cmd.getArg(i));
2210 LYXERR0("Not a hexstring: " << arg);
2214 char_type c = hexToInt(arg);
2215 if (c >= 32 && c < 0x10ffff) {
2216 LYXERR(Debug::KEY, "Inserting c: " << c);
2217 lyx::dispatch(FuncRequest(code, docstring(1, c)));
2225 // This would be in Buffer class if only Cursor did not
2226 // require a bufferview
2227 case LFUN_INSET_FORALL: {
2228 docstring const name = from_utf8(cmd.getArg(0));
2229 string const commandstr = cmd.getLongArg(1);
2230 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
2232 // an arbitrary number to limit number of iterations
2233 const int max_iter = 100000;
2235 Cursor & bvcur = d->cursor_;
2236 Cursor const savecur = bvcur;
2238 if (!bvcur.nextInset())
2239 bvcur.forwardInset();
2240 bvcur.beginUndoGroup();
2241 while(bvcur && iterations < max_iter) {
2242 Inset * const ins = bvcur.nextInset();
2245 docstring insname = ins->layoutName();
2246 while (!insname.empty()) {
2247 if (insname == name || name == from_utf8("*")) {
2248 lyx::dispatch(fr, dr);
2249 // we do not want to remember selection here
2250 bvcur.clearSelection();
2254 size_t const i = insname.rfind(':');
2255 if (i == string::npos)
2257 insname = insname.substr(0, i);
2259 // if we did not delete the inset, skip it
2260 if (!bvcur.nextInset() || bvcur.nextInset() == ins)
2261 bvcur.forwardInset();
2264 bvcur.fixIfBroken();
2265 /** This is a dummy undo record only to remember the cursor
2266 * that has just been set; this will be used on a redo action
2267 * (see ticket #10097)
2269 * FIXME: a better fix would be to have a way to set the
2270 * cursor value directly, but I am not sure it is worth it.
2273 bvcur.endUndoGroup();
2274 dr.screenUpdate(Update::Force);
2275 dr.forceBufferUpdate();
2277 if (iterations >= max_iter) {
2279 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
2281 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
2286 case LFUN_BRANCH_ADD_INSERT: {
2287 docstring branch_name = from_utf8(cmd.getArg(0));
2288 if (branch_name.empty())
2289 if (!Alert::askForText(branch_name, _("Branch name")) ||
2290 branch_name.empty())
2293 DispatchResult drtmp;
2294 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
2295 if (drtmp.error()) {
2296 Alert::warning(_("Branch already exists"), drtmp.message());
2299 docstring const sep = buffer_.params().branchlist().separator();
2300 for (docstring const & branch : getVectorFromString(branch_name, sep))
2301 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch));
2305 case LFUN_KEYMAP_OFF:
2306 getIntl().keyMapOn(false);
2309 case LFUN_KEYMAP_PRIMARY:
2310 getIntl().keyMapPrim();
2313 case LFUN_KEYMAP_SECONDARY:
2314 getIntl().keyMapSec();
2317 case LFUN_KEYMAP_TOGGLE:
2318 getIntl().toggleKeyMap();
2321 case LFUN_DIALOG_SHOW_NEW_INSET: {
2322 string const name = cmd.getArg(0);
2323 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2324 if (decodeInsetParam(name, data, buffer_))
2325 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
2327 lyxerr << "Inset type '" << name <<
2328 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
2332 case LFUN_CITATION_INSERT: {
2333 if (argument.empty()) {
2334 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
2337 // we can have one optional argument, delimited by '|'
2338 // citation-insert <key>|<text_before>
2339 // this should be enhanced to also support text_after
2340 // and citation style
2341 string arg = argument;
2343 if (contains(argument, "|")) {
2344 arg = token(argument, '|', 0);
2345 opt1 = token(argument, '|', 1);
2348 // if our cursor is directly in front of or behind a citation inset,
2349 // we will instead add the new key to it.
2350 Inset * inset = cur.nextInset();
2351 if (!inset || inset->lyxCode() != CITE_CODE)
2352 inset = cur.prevInset();
2353 if (inset && inset->lyxCode() == CITE_CODE) {
2354 InsetCitation * icite = static_cast<InsetCitation *>(inset);
2355 if (icite->addKey(arg)) {
2356 dr.forceBufferUpdate();
2357 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
2359 LYXERR0("Discarding optional argument to citation-insert.");
2364 InsetCommandParams icp(CITE_CODE);
2365 icp["key"] = from_utf8(arg);
2367 icp["before"] = from_utf8(opt1);
2369 from_ascii(InsetCitation::last_literal ? "true" : "false");
2370 string icstr = InsetCommand::params2string(icp);
2371 FuncRequest fr(LFUN_INSET_INSERT, icstr);
2374 // if the request comes from the LyX server, then we
2375 // return a list of the undefined keys, in case some
2376 // action could be taken.
2377 if (cmd.origin() != FuncRequest::LYXSERVER)
2380 vector<docstring> keys = getVectorFromString(from_utf8(arg));
2381 vector<docstring>::iterator it = keys.begin();
2382 vector<docstring>::const_iterator end = keys.end();
2384 BiblioInfo const & bibInfo = buffer_.masterBibInfo();
2385 const BiblioInfo::const_iterator bibEnd = bibInfo.end();
2387 if (bibInfo.find(*it) != bibEnd) {
2388 it = keys.erase(it);
2393 dr.setMessage(getStringFromVector(keys));
2398 case LFUN_INSET_APPLY: {
2399 string const name = cmd.getArg(0);
2400 Inset * inset = editedInset(name);
2402 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2406 // put cursor in front of inset.
2407 if (!setCursorFromInset(inset)) {
2408 LASSERT(false, break);
2411 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2412 inset->dispatch(cur, fr);
2413 dr.screenUpdate(cur.result().screenUpdate());
2414 if (cur.result().needBufferUpdate())
2415 dr.forceBufferUpdate();
2420 // The change of language of buffer belongs to the Buffer class.
2421 // We have to do it here because we need a cursor for Undo.
2422 // When Undo::recordUndoBufferParams() is implemented someday
2423 // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
2424 case LFUN_BUFFER_LANGUAGE: {
2425 Language const * oldL = buffer_.params().language;
2426 Language const * newL = languages.getLanguage(argument);
2427 if (!newL || oldL == newL)
2429 if (oldL->rightToLeft() == newL->rightToLeft()) {
2430 cur.recordUndoFullBuffer();
2431 buffer_.changeLanguage(oldL, newL);
2432 cur.setCurrentFont();
2433 dr.forceBufferUpdate();
2438 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2439 case LFUN_FILE_INSERT_PLAINTEXT: {
2440 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
2441 string const fname = to_utf8(cmd.argument());
2442 if (!FileName::isAbsolute(fname))
2443 dr.setMessage(_("Absolute filename expected."));
2445 insertPlaintextFile(FileName(fname), as_paragraph);
2450 // With multi-cell table content, we pass down to the inset
2451 if (cur.inTexted() && cur.selection()
2452 && cur.selectionBegin().idx() != cur.selectionEnd().idx()) {
2453 buffer_.dispatch(cmd, dr);
2454 dispatched = dr.dispatched();
2457 cap::copySelection(cur);
2458 cur.message(_("Copy"));
2462 // OK, so try the Buffer itself...
2463 buffer_.dispatch(cmd, dr);
2464 dispatched = dr.dispatched();
2468 buffer_.undo().endUndoGroup();
2469 dr.dispatched(dispatched);
2471 // NOTE: The code below is copied from Cursor::dispatch. If you
2472 // need to modify this, please update the other one too.
2474 // notify insets we just entered/left
2475 if (cursor() != old) {
2476 old.beginUndoGroup();
2478 bool badcursor = notifyCursorLeavesOrEnters(old, cursor());
2480 cursor().fixIfBroken();
2481 resetInlineCompletionPos();
2488 docstring BufferView::requestSelection()
2490 Cursor & cur = d->cursor_;
2492 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2493 if (!cur.selection()) {
2494 d->xsel_cache_.set = false;
2498 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2499 if (!d->xsel_cache_.set ||
2500 cur.top() != d->xsel_cache_.cursor ||
2501 cur.realAnchor().top() != d->xsel_cache_.anchor)
2503 d->xsel_cache_.cursor = cur.top();
2504 d->xsel_cache_.anchor = cur.realAnchor().top();
2505 d->xsel_cache_.set = cur.selection();
2506 return cur.selectionAsString(false);
2512 void BufferView::clearSelection()
2514 d->cursor_.clearSelection();
2515 // Clear the selection buffer. Otherwise a subsequent
2516 // middle-mouse-button paste would use the selection buffer,
2517 // not the more current external selection.
2518 cap::clearSelection();
2519 d->xsel_cache_.set = false;
2520 // The buffer did not really change, but this causes the
2521 // redraw we need because we cleared the selection above.
2522 buffer_.changed(false);
2526 void BufferView::resize(int width, int height)
2529 // Update metrics only if width has changed
2530 if (width != width_) {
2533 // Clear the paragraph height cache.
2534 d->par_height_.clear();
2535 // Redo the metrics.
2536 updateMetrics(true);
2538 // metrics is OK, full drawing is necessary now
2539 d->update_flags_ = (d->update_flags_ & ~Update::Force) | Update::ForceDraw;
2540 d->update_strategy_ = FullScreenUpdate;
2544 Inset const * BufferView::getCoveringInset(Text const & text,
2547 TextMetrics & tm = d->text_metrics_[&text];
2548 Inset * inset = tm.checkInsetHit(x, y);
2552 if (!inset->descendable(*this))
2553 // No need to go further down if the inset is not
2557 size_t cell_number = inset->nargs();
2558 // Check all the inner cell.
2559 for (size_t i = 0; i != cell_number; ++i) {
2560 Text const * inner_text = inset->getText(i);
2563 Inset const * inset_deeper =
2564 getCoveringInset(*inner_text, x, y);
2566 return inset_deeper;
2574 Inset const * BufferView::clickableMathInset(InsetMathNest const * inset,
2575 CoordCache::Insets const & inset_cache, int x, int y) const
2577 for (size_t i = 0; i < inset->nargs(); ++i) {
2578 MathData const & ar = inset->cell(i);
2579 for (size_t j = 0; j < ar.size(); ++j) {
2580 string const name = lyxerr.debugging(Debug::MATHED)
2581 ? insetName(ar[j].nucleus()->lyxCode())
2583 LYXERR(Debug::MATHED, "Checking inset: " << name);
2584 if (ar[j].nucleus()->clickable(*this, x, y)) {
2585 if (inset_cache.covers(ar[j].nucleus(), x, y)) {
2586 LYXERR(Debug::MATHED, "Clickable inset: "
2588 return ar[j].nucleus();
2591 InsetMathNest const * imn =
2592 ar[j].nucleus()->asNestInset();
2594 Inset const * inner =
2595 clickableMathInset(imn, inset_cache, x, y);
2605 void BufferView::updateHoveredInset() const
2607 // Get inset under mouse, if there is one.
2608 int const x = d->mouse_position_cache_.x_;
2609 int const y = d->mouse_position_cache_.y_;
2610 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2611 if (covering_inset && covering_inset->asInsetMath()) {
2612 Inset const * inner_inset = clickableMathInset(
2613 covering_inset->asInsetMath()->asNestInset(),
2614 coordCache().getInsets(), x, y);
2616 covering_inset = inner_inset;
2619 d->clickable_inset_ = covering_inset && covering_inset->clickable(*this, x, y);
2621 if (covering_inset == d->last_inset_)
2622 // Same inset, no need to do anything...
2625 bool need_redraw = false;
2626 if (d->last_inset_) {
2627 // Remove the hint on the last hovered inset (if any).
2628 need_redraw |= d->last_inset_->setMouseHover(this, false);
2629 d->last_inset_ = nullptr;
2632 if (covering_inset && covering_inset->setMouseHover(this, true)) {
2634 // Only the insets that accept the hover state, do
2635 // clear the last_inset_, so only set the last_inset_
2636 // member if the hovered setting is accepted.
2637 d->last_inset_ = covering_inset;
2641 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2642 << d->mouse_position_cache_.x_ << ", "
2643 << d->mouse_position_cache_.y_ << ")");
2645 d->update_strategy_ = DecorationUpdate;
2647 // This event (moving without mouse click) is not passed further.
2648 // This should be changed if it is further utilized.
2649 buffer_.changed(false);
2654 void BufferView::clearLastInset(Inset * inset) const
2656 if (d->last_inset_ != inset) {
2657 LYXERR0("Wrong last_inset!");
2660 d->last_inset_ = nullptr;
2664 bool BufferView::mouseSelecting() const
2666 return d->mouse_selecting_;
2670 int BufferView::stats_ref_value_w() const
2672 return d->stats_ref_value_w_;
2676 int BufferView::stats_ref_value_c() const
2678 return d->stats_ref_value_c_;
2682 int BufferView::stats_ref_value_nb() const
2684 return d->stats_ref_value_nb_;
2688 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2690 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2695 // This is only called for mouse related events including
2696 // LFUN_FILE_OPEN generated by drag-and-drop.
2697 FuncRequest cmd = cmd0;
2699 // Either the inset under the cursor or the
2700 // surrounding Text will handle this event.
2702 // make sure we stay within the screen...
2703 cmd.set_y(min(max(cmd.y(), -1), height_));
2705 d->mouse_position_cache_.x_ = cmd.x();
2706 d->mouse_position_cache_.y_ = cmd.y();
2708 d->mouse_selecting_ =
2709 cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::button1;
2711 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2712 updateHoveredInset();
2716 Cursor old = cursor();
2718 cur.push(buffer_.inset());
2719 cur.selection(d->cursor_.selection());
2721 // Build temporary cursor.
2722 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2724 // If inset is not editable, cur.pos() might point behind the
2725 // inset (depending on cmd.x(), cmd.y()). This is needed for
2726 // editing to fix bug 9628, but e.g. the context menu needs a
2727 // cursor in front of the inset.
2728 if ((inset->hasSettings() || !inset->contextMenuName().empty()
2729 || inset->lyxCode() == SEPARATOR_CODE) &&
2730 cur.nextInset() != inset && cur.prevInset() == inset)
2732 } else if (cur.inTexted() && cur.pos()
2733 && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
2734 // Always place cursor in front of a separator inset.
2738 // Put anchor at the same position.
2741 old.beginUndoGroup();
2743 // Try to dispatch to an non-editable inset near this position
2744 // via the temp cursor. If the inset wishes to change the real
2745 // cursor it has to do so explicitly by using
2746 // cur.bv().cursor() = cur; (or similar)
2748 inset->dispatch(cur, cmd);
2750 // Now dispatch to the temporary cursor. If the real cursor should
2751 // be modified, the inset's dispatch has to do so explicitly.
2752 if (!inset || !cur.result().dispatched())
2755 // Notify left insets
2757 bool badcursor = old.fixIfBroken() || cur.fixIfBroken();
2758 badcursor = badcursor || notifyCursorLeavesOrEnters(old, cur);
2760 cursor().fixIfBroken();
2765 // Do we have a selection?
2766 theSelection().haveSelection(cursor().selection());
2768 if (cur.needBufferUpdate() || buffer().needUpdate()) {
2769 cur.clearBufferUpdate();
2770 buffer().updateBuffer();
2773 // If the command has been dispatched,
2774 if (cur.result().dispatched() || cur.result().screenUpdate())
2775 processUpdateFlags(cur.result().screenUpdate());
2779 int BufferView::minVisiblePart()
2781 return 2 * defaultRowHeight();
2785 int BufferView::scroll(int pixels)
2788 return scrollDown(pixels);
2790 return scrollUp(-pixels);
2795 int BufferView::scrollDown(int pixels)
2797 Text * text = &buffer_.text();
2798 TextMetrics & tm = d->text_metrics_[text];
2799 int const ymax = height_ + pixels;
2801 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2802 int bottom_pos = last.second->bottom();
2803 if (lyxrc.scroll_below_document)
2804 bottom_pos += height_ - minVisiblePart();
2805 if (last.first + 1 == int(text->paragraphs().size())) {
2806 if (bottom_pos <= height_)
2808 pixels = min(pixels, bottom_pos - height_);
2811 if (bottom_pos > ymax)
2813 tm.newParMetricsDown();
2815 d->anchor_ypos_ -= pixels;
2820 int BufferView::scrollUp(int pixels)
2822 Text * text = &buffer_.text();
2823 TextMetrics & tm = d->text_metrics_[text];
2824 int ymin = - pixels;
2826 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2827 int top_pos = first.second->top();
2828 if (first.first == 0) {
2831 pixels = min(pixels, - top_pos);
2836 tm.newParMetricsUp();
2838 d->anchor_ypos_ += pixels;
2843 bool BufferView::setCursorFromRow(int row)
2845 TexRow::TextEntry start, end;
2846 tie(start,end) = buffer_.texrow().getEntriesFromRow(row);
2847 LYXERR(Debug::OUTFILE,
2848 "setCursorFromRow: for row " << row << ", TexRow has found "
2849 "start (id=" << start.id << ",pos=" << start.pos << "), "
2850 "end (id=" << end.id << ",pos=" << end.pos << ")");
2851 return setCursorFromEntries(start, end);
2855 bool BufferView::setCursorFromEntries(TexRow::TextEntry start,
2856 TexRow::TextEntry end)
2858 DocIterator dit_start, dit_end;
2859 tie(dit_start,dit_end) =
2860 TexRow::getDocIteratorsFromEntries(start, end, buffer_);
2863 // Setting selection start
2864 d->cursor_.clearSelection();
2865 setCursor(dit_start);
2866 // Setting selection end
2868 d->cursor_.resetAnchor();
2869 setCursorSelectionTo(dit_end);
2875 bool BufferView::setCursorFromInset(Inset const * inset)
2877 // are we already there?
2878 if (cursor().nextInset() == inset)
2881 // Inset is not at cursor position. Find it in the document.
2884 while (cur && cur.nextInset() != inset)
2895 void BufferView::gotoLabel(docstring const & label)
2898 bool have_inactive = false;
2899 for (Buffer const * buf : buffer().allRelatives()) {
2901 for (TocItem const & item : *buf->tocBackend().toc("label")) {
2902 if (label == item.str() && item.isOutput()) {
2903 lyx::dispatch(item.action());
2906 // If we find an inactive label, save it for the case
2907 // that no active one is there
2908 if (label == item.str() && !have_inactive) {
2909 have_inactive = true;
2910 action = item.action();
2914 // We only found an inactive label. Go there.
2916 lyx::dispatch(action);
2920 TextMetrics const & BufferView::textMetrics(Text const * t) const
2922 return const_cast<BufferView *>(this)->textMetrics(t);
2926 TextMetrics & BufferView::textMetrics(Text const * t)
2929 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2930 if (tmc_it == d->text_metrics_.end()) {
2931 tmc_it = d->text_metrics_.emplace(std::piecewise_construct,
2932 std::forward_as_tuple(t),
2933 std::forward_as_tuple(this, const_cast<Text *>(t))).first;
2935 return tmc_it->second;
2939 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2942 return textMetrics(t).parMetrics(pit);
2946 int BufferView::workHeight() const
2952 void BufferView::setCursor(DocIterator const & dit)
2955 size_t const n = dit.depth();
2956 for (size_t i = 0; i < n; ++i)
2957 dit[i].inset().edit(d->cursor_, true);
2959 d->cursor_.setCursor(dit);
2960 d->cursor_.selection(false);
2961 d->cursor_.setCurrentFont();
2963 // It seems on general grounds as if this is probably needed, but
2964 // it is not yet clear.
2965 // See bug #7394 and r38388.
2966 // d->cursor.resetAnchor();
2970 void BufferView::setCursorSelectionTo(DocIterator const & dit)
2972 size_t const n = dit.depth();
2973 for (size_t i = 0; i < n; ++i)
2974 dit[i].inset().edit(d->cursor_, true);
2976 d->cursor_.selection(true);
2977 d->cursor_.setCursorSelectionTo(dit);
2978 d->cursor_.setCurrentFont();
2982 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2984 // Would be wrong to delete anything if we have a selection.
2985 if (cur.selection())
2988 bool need_anchor_change = false;
2989 bool changed = Text::deleteEmptyParagraphMechanism(cur, old,
2990 need_anchor_change);
2992 if (need_anchor_change)
3000 // we would rather not do this here, but it needs to be done before
3001 // the changed() signal is sent.
3002 buffer_.updateBuffer();
3004 buffer_.changed(true);
3009 bool BufferView::mouseSetCursor(Cursor & cur, bool const select)
3011 LASSERT(&cur.bv() == this, return false);
3014 // this event will clear selection so we save selection for
3015 // persistent selection
3016 cap::saveSelection(cursor());
3018 d->cursor_.macroModeClose();
3019 // If a macro has been finalized, the cursor might have been broken
3022 // Has the cursor just left the inset?
3023 bool const leftinset = (&d->cursor_.inset() != &cur.inset());
3025 d->cursor_.fixIfBroken();
3027 // do the dEPM magic if needed
3028 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
3029 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
3030 // the leftinset bool would not be necessary (badcursor instead).
3031 bool update = leftinset;
3034 d->cursor_.setSelection();
3035 d->cursor_.setCursorSelectionTo(cur);
3037 if (d->cursor_.inTexted())
3038 update |= checkDepm(cur, d->cursor_);
3039 d->cursor_.resetAnchor();
3040 d->cursor_.setCursor(cur);
3041 d->cursor_.clearSelection();
3043 d->cursor_.boundary(cur.boundary());
3044 d->cursor_.finishUndo();
3045 d->cursor_.setCurrentFont();
3047 cur.forceBufferUpdate();
3052 void BufferView::putSelectionAt(DocIterator const & cur,
3053 int length, bool backwards)
3055 d->cursor_.clearSelection();
3061 d->cursor_.pos() += length;
3062 d->cursor_.setSelection(d->cursor_, -length);
3064 d->cursor_.setSelection(d->cursor_, length);
3069 void BufferView::setSelection(DocIterator const & from,
3070 DocIterator const & to)
3072 if (from.pit() != to.pit()) {
3073 // there are multiple paragraphs in selection
3074 cursor().setCursor(from);
3075 cursor().clearSelection();
3076 cursor().selection(true);
3077 cursor().setCursor(to);
3078 cursor().selection(true);
3080 // only single paragraph
3081 int const size = to.pos() - from.pos();
3082 putSelectionAt(from, size, false);
3084 processUpdateFlags(Update::Force | Update::FitCursor);
3088 bool BufferView::selectIfEmpty(DocIterator & cur)
3090 if ((cur.inTexted() && !cur.paragraph().empty())
3091 || (cur.inMathed() && !cur.cell().empty()))
3094 pit_type const beg_pit = cur.pit();
3096 // The paragraph associated to this item isn't
3097 // the first one, so it can be selected
3100 // We have to resort to select the space between the
3101 // end of this item and the begin of the next one
3105 // If it is the only item in the document,
3106 // nothing can be selected
3109 pit_type const end_pit = cur.pit();
3110 pos_type const end_pos = cur.pos();
3111 d->cursor_.clearSelection();
3113 d->cursor_.setCursor(cur);
3114 d->cursor_.pit() = beg_pit;
3115 d->cursor_.pos() = 0;
3116 d->cursor_.selection(false);
3117 d->cursor_.resetAnchor();
3118 d->cursor_.pit() = end_pit;
3119 d->cursor_.pos() = end_pos;
3120 d->cursor_.setSelection();
3125 Cursor & BufferView::cursor()
3131 Cursor const & BufferView::cursor() const
3137 bool BufferView::singleParUpdate()
3139 CursorSlice const & its = d->cursor_.innerTextSlice();
3140 pit_type const pit = its.pit();
3141 TextMetrics & tm = textMetrics(its.text());
3142 Dimension const old_dim = tm.parMetrics(pit).dim();
3144 // make sure inline completion pointer is ok
3145 if (d->inlineCompletionPos_.fixIfBroken())
3146 d->inlineCompletionPos_ = DocIterator();
3148 /* Try to rebreak only the paragraph containing the cursor (if
3149 * this paragraph contains insets etc., rebreaking will
3150 * recursively descend). We need a full redraw if either
3151 * 1/ the height has changed
3153 * 2/ the width has changed and it was equal to the textmetrics
3154 * width; the goal is to catch the case of a one-row inset that
3155 * grows with its contents, but optimize the case of typing at
3156 * the end of a mmultiple-row paragraph.
3158 * NOTE: if only the height has changed, then it should be
3159 * possible to update all metrics at minimal cost. However,
3160 * since this is risky, we do not try that right now.
3162 tm.redoParagraph(pit);
3163 ParagraphMetrics & pm = tm.parMetrics(pit);
3164 if (pm.height() != old_dim.height()
3165 || (pm.width() != old_dim.width() && old_dim.width() == tm.width())) {
3166 // Paragraph height or width has changed so we cannot proceed
3167 // to the singlePar optimisation.
3168 LYXERR(Debug::PAINTING, "SinglePar optimization failed.");
3171 // Since position() points to the baseline of the first row, we
3172 // may have to update it. See ticket #11601 for an example where
3173 // the height does not change but the ascent does.
3174 pm.setPosition(pm.position() - old_dim.ascent() + pm.ascent());
3176 tm.updatePosCache(pit);
3178 LYXERR(Debug::PAINTING, "\ny1: " << pm.top() << " y2: " << pm.bottom()
3179 << " pit: " << pit << " singlepar: 1");
3184 void BufferView::updateMetrics()
3186 updateMetrics(true);
3187 // metrics is done, full drawing is necessary now
3188 d->update_flags_ = (d->update_flags_ & ~Update::Force) | Update::ForceDraw;
3189 d->update_strategy_ = FullScreenUpdate;
3193 void BufferView::updateMetrics(bool force)
3198 //LYXERR0("updateMetrics " << _v_(force));
3200 Text & buftext = buffer_.text();
3201 pit_type const lastpit = int(buftext.paragraphs().size()) - 1;
3204 // Clear out the position cache in case of full screen redraw,
3205 d->coord_cache_.clear();
3206 d->math_rows_.clear();
3208 // Clear out paragraph metrics to avoid having invalid metrics
3209 // in the cache from paragraphs not relayouted below. The
3210 // complete text metrics will be redone.
3211 d->text_metrics_.clear();
3214 // This should not be moved earlier
3215 TextMetrics & tm = textMetrics(&buftext);
3217 // make sure inline completion pointer is ok
3218 if (d->inlineCompletionPos_.fixIfBroken())
3219 d->inlineCompletionPos_ = DocIterator();
3221 if (d->anchor_pit_ > lastpit)
3222 // The anchor pit must have been deleted...
3223 d->anchor_pit_ = lastpit;
3225 // Update metrics around the anchor
3226 tm.updateMetrics(d->anchor_pit_, d->anchor_ypos_, height_);
3228 // Check that the end of the document is not too high
3229 int const min_visible = lyxrc.scroll_below_document ? minVisiblePart() : height_;
3230 if (tm.last().first == lastpit && tm.last().second->hasPosition()
3231 && tm.last().second->bottom() < min_visible) {
3232 d->anchor_ypos_ += min_visible - tm.last().second->bottom();
3233 LYXERR(Debug::SCROLLING, "Too high, adjusting anchor ypos to " << d->anchor_ypos_);
3234 tm.updateMetrics(d->anchor_pit_, d->anchor_ypos_, height_);
3237 // Check that the start of the document is not too low
3238 if (tm.first().first == 0 && tm.first().second->hasPosition()
3239 && tm.first().second->top() > 0) {
3240 d->anchor_ypos_ -= tm.first().second->top();
3241 LYXERR(Debug::SCROLLING, "Too low, adjusting anchor ypos to " << d->anchor_ypos_);
3242 tm.updateMetrics(d->anchor_pit_, d->anchor_ypos_, height_);
3245 /* FIXME: do we want that? It avoids potential issues with old
3246 * paragraphs that should have been recomputed but have not, at
3247 * the price of potential extra metrics computation. I do not
3248 * think that the performance gain is high, so that for now the
3249 * extra paragraphs are removed
3251 // Remove paragraphs that are outside of screen
3252 while(!tm.first().second->hasPosition() || tm.first().second->bottom() <= 0) {
3253 //LYXERR0("Forget pit: " << tm.first().first);
3254 tm.forget(tm.first().first);
3256 while(!tm.last().second->hasPosition() || tm.last().second->top() > height_) {
3257 //LYXERR0("Forget pit: " << tm.first().first);
3258 tm.forget(tm.last().first);
3261 /* FIXME: if paragraphs outside of the screen are not removed
3262 * above, one has to search for the first visible one here */
3263 // Normalize anchor for next time
3264 if (d->anchor_pit_ != tm.first().first
3265 || d->anchor_ypos_ != tm.first().second->position()) {
3266 LYXERR(Debug::PAINTING, __func__ << ": Found new anchor pit = " << tm.first().first
3267 << " anchor ypos = " << tm.first().second->position()
3268 << " (was " << d->anchor_pit_ << ", " << d->anchor_ypos_ << ")");
3269 d->anchor_pit_ = tm.first().first;
3270 d->anchor_ypos_ = tm.first().second->position();
3273 // Now update the positions of insets in the cache.
3276 if (lyxerr.debugging(Debug::WORKAREA)) {
3277 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
3278 d->coord_cache_.dump();
3283 void BufferView::updatePosCache()
3285 // this is the "nodraw" drawing stage: only set the positions of the
3286 // insets in metrics cache.
3287 frontend::NullPainter np;
3292 void BufferView::insertLyXFile(FileName const & fname, bool const ignorelang)
3294 LASSERT(d->cursor_.inTexted(), return);
3296 // Get absolute path of file and add ".lyx"
3297 // to the filename if necessary
3298 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
3300 docstring const disp_fn = makeDisplayPath(filename.absFileName());
3301 // emit message signal.
3302 message(bformat(_("Inserting document %1$s..."), disp_fn));
3305 Buffer buf(filename.absFileName(), false);
3306 if (buf.loadLyXFile() == Buffer::ReadSuccess) {
3307 ErrorList & el = buffer_.errorList("Parse");
3308 // Copy the inserted document error list into the current buffer one.
3309 el = buf.errorList("Parse");
3310 ParagraphList & pars = buf.paragraphs();
3312 // set main language of imported file to context language
3313 buf.changeLanguage(buf.language(), d->cursor_.getFont().language());
3314 buffer_.undo().recordUndo(d->cursor_);
3315 cap::replaceSelection(d->cursor_);
3316 cap::pasteParagraphList(d->cursor_, pars,
3317 buf.params().documentClassPtr(),
3318 buf.params().authors(), el);
3319 res = _("Document %1$s inserted.");
3321 res = _("Could not insert document %1$s");
3324 buffer_.changed(true);
3325 // emit message signal.
3326 message(bformat(res, disp_fn));
3330 Point BufferView::coordOffset(DocIterator const & dit) const
3336 // Addup contribution of nested insets, from inside to outside,
3337 // keeping the outer paragraph for a special handling below
3338 for (size_t i = dit.depth() - 1; i >= 1; --i) {
3339 CursorSlice const & sl = dit[i];
3343 // get relative position inside sl.inset()
3344 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
3346 // Make relative position inside of the edited inset relative to sl.inset()
3350 // In case of an RTL inset, the edited inset will be positioned to the left
3353 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
3354 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
3359 // remember width for the case that sl.inset() is positioned in an RTL inset
3360 lastw = sl.inset().dimension(*this).wid;
3362 //lyxerr << "Cursor::getPos, i: "
3363 // << i << " x: " << xx << " y: " << y << endl;
3366 // Add contribution of initial rows of outermost paragraph
3367 CursorSlice const & sl = dit[0];
3368 TextMetrics const & tm = textMetrics(sl.text());
3369 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
3371 LBUFERR(!pm.rows().empty());
3372 y -= pm.rows()[0].ascent();
3374 // FIXME: document this mess
3376 if (sl.pos() > 0 && dit.depth() == 1) {
3378 if (pos && dit.boundary())
3380 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
3381 rend = pm.pos2row(pos);
3383 rend = pm.pos2row(sl.pos());
3385 size_t rend = pm.pos2row(sl.pos());
3387 for (size_t rit = 0; rit != rend; ++rit)
3388 y += pm.rows()[rit].height();
3389 y += pm.rows()[rend].ascent();
3391 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
3393 // Make relative position from the nested inset now bufferview absolute.
3394 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
3397 // In the RTL case place the nested inset at the left of the cursor in
3398 // the outer paragraph
3399 bool boundary_1 = dit.boundary() && 1 == dit.depth();
3400 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
3408 Point BufferView::getPos(DocIterator const & dit) const
3410 if (!paragraphVisible(dit))
3411 return Point(-1, -1);
3413 CursorSlice const & bot = dit.bottom();
3414 TextMetrics const & tm = textMetrics(bot.text());
3416 // offset from outer paragraph
3417 Point p = coordOffset(dit);
3418 p.y_ += tm.parMetrics(bot.pit()).position();
3423 bool BufferView::paragraphVisible(DocIterator const & dit) const
3425 CursorSlice const & bot = dit.bottom();
3426 TextMetrics const & tm = textMetrics(bot.text());
3428 return tm.contains(bot.pit());
3432 void BufferView::caretPosAndDim(Point & p, Dimension & dim) const
3434 Cursor const & cur = cursor();
3435 if (cur.inMathed() && hasMathRow(&cur.cell())) {
3436 MathRow const & mrow = mathRow(&cur.cell());
3437 dim = mrow.caret_dim;
3439 Font const font = cur.real_current_font;
3440 frontend::FontMetrics const & fm = theFontMetrics(font);
3441 // lineWidth() can be 0 to mean 'thin line' on HiDpi, but the
3442 // caret drawing code is not prepared for that.
3443 dim.wid = max(fm.lineWidth(), 1);
3444 dim.asc = fm.maxAscent();
3445 dim.des = fm.maxDescent();
3447 if (lyxrc.cursor_width > 0)
3448 dim.wid = lyxrc.cursor_width;
3451 // center fat carets horizontally
3452 p.x_ -= dim.wid / 2;
3458 void BufferView::buildCaretGeometry(bool complet)
3462 caretPosAndDim(p, dim);
3464 Cursor const & cur = d->cursor_;
3465 Font const & realfont = cur.real_current_font;
3466 frontend::FontMetrics const & fm = theFontMetrics(realfont.fontInfo());
3467 bool const isrtl = realfont.isVisibleRightToLeft();
3468 int const dir = isrtl ? -1 : 1;
3470 frontend::CaretGeometry & cg = d->caret_geometry_;
3473 // The caret itself, slanted for italics in text edit mode except
3474 // for selections because the selection rect does not slant
3475 bool const slant = fm.italic() && cur.inTexted() && !cur.selection();
3476 double const slope = slant ? fm.italicSlope() : 0;
3477 cg.shapes.push_back(
3478 {{iround(p.x_ + dim.asc * slope), p.y_},
3479 {iround(p.x_ - dim.des * slope), p.y_ + dim.height()},
3480 {iround(p.x_ + dir * dim.wid - dim.des * slope), p.y_ + dim.height()},
3481 {iround(p.x_ + dir * dim.wid + dim.asc * slope), p.y_}}
3484 // The language indicator _| (if needed)
3485 Language const * doclang = buffer().params().language;
3486 if (!((realfont.language() == doclang && isrtl == doclang->rightToLeft())
3487 || realfont.language() == latex_language)) {
3488 int const lx = dim.height() / 3;
3489 int const xx = iround(p.x_ - dim.des * slope);
3490 int const yy = p.y_ + dim.height();
3491 cg.shapes.push_back(
3492 {{xx, yy - dim.wid},
3493 {xx + dir * (dim.wid + lx - 1), yy - dim.wid},
3494 {xx + dir * (dim.wid + lx - 1), yy},
3499 // The completion triangle |> (if needed)
3501 int const m = p.y_ + dim.height() / 2;
3502 int const d = dim.height() / 8;
3503 // offset for slanted carret
3504 int const sx = iround((dim.asc - (dim.height() / 2 - d)) * slope);
3505 // starting position x
3506 int const xx = p.x_ + dir * dim.wid + sx;
3507 cg.shapes.push_back(
3511 {xx, m + d - dim.wid},
3512 {xx + dir * d - dim.wid, m},
3513 {xx, m - d + dim.wid}}
3517 // compute extremal x values
3519 cg.right = -1000000;
3521 cg.bottom = -1000000;
3522 for (auto const & shape : cg.shapes)
3523 for (Point const & p : shape) {
3524 cg.left = min(cg.left, p.x_);
3525 cg.right = max(cg.right, p.x_);
3526 cg.top = min(cg.top, p.y_);
3527 cg.bottom = max(cg.bottom, p.y_);
3532 frontend::CaretGeometry const & BufferView::caretGeometry() const
3534 return d->caret_geometry_;
3538 bool BufferView::caretInView() const
3540 if (!paragraphVisible(cursor()))
3544 caretPosAndDim(p, dim);
3546 // does the cursor touch the screen ?
3547 if (p.y_ + dim.height() < 0 || p.y_ >= workHeight())
3553 int BufferView::horizScrollOffset() const
3555 return d->horiz_scroll_offset_;
3559 int BufferView::horizScrollOffset(Text const * text,
3560 pit_type pit, pos_type pos) const
3562 // Is this a row that is currently scrolled?
3563 if (!d->current_row_slice_.empty()
3564 && &text->inset() == d->current_row_slice_.inset().asInsetText()
3565 && pit == d->current_row_slice_.pit()
3566 && pos == d->current_row_slice_.pos())
3567 return d->horiz_scroll_offset_;
3572 void BufferView::setCurrentRowSlice(CursorSlice const & rowSlice)
3574 // nothing to do if the cursor was already on this row
3575 if (d->current_row_slice_ == rowSlice)
3578 // if the (previous) current row was scrolled, we have to
3579 // remember it in order to repaint it next time.
3580 if (d->horiz_scroll_offset_ != 0) {
3581 // search the old row in cache and mark it changed
3582 for (auto & tm_pair : d->text_metrics_) {
3583 if (&tm_pair.first->inset() == rowSlice.inset().asInsetText()) {
3584 tm_pair.second.setRowChanged(rowSlice.pit(), rowSlice.pos());
3585 // We found it, no need to continue.
3591 // Since we changed row, the scroll offset is not valid anymore
3592 d->horiz_scroll_offset_ = 0;
3593 d->current_row_slice_ = rowSlice;
3597 void BufferView::checkCursorScrollOffset()
3599 CursorSlice rowSlice = d->cursor_.bottom();
3600 TextMetrics const & tm = textMetrics(rowSlice.text());
3602 // Stop if metrics have not been computed yet, since it means
3603 // that there is nothing to do.
3604 if (!tm.contains(rowSlice.pit()))
3606 ParagraphMetrics const & pm = tm.parMetrics(rowSlice.pit());
3607 Row const & row = pm.getRow(rowSlice.pos(),
3608 d->cursor_.boundary() && rowSlice == d->cursor_.top());
3609 rowSlice.pos() = row.pos();
3611 // Set the row on which the cursor lives.
3612 setCurrentRowSlice(rowSlice);
3614 // Current x position of the cursor in pixels
3615 int cur_x = getPos(d->cursor_).x_;
3617 // Horizontal scroll offset of the cursor row in pixels
3618 int offset = d->horiz_scroll_offset_;
3619 int const MARGIN = 2 * theFontMetrics(d->cursor_.real_current_font).em()
3621 if (row.right_x() <= workWidth() - row.right_margin) {
3622 // Row is narrower than the work area, no offset needed.
3625 if (cur_x - offset < MARGIN) {
3626 // cursor would be too far right
3627 offset = cur_x - MARGIN;
3628 } else if (cur_x - offset > workWidth() - MARGIN) {
3629 // cursor would be too far left
3630 offset = cur_x - workWidth() + MARGIN;
3632 // Correct the offset to make sure that we do not scroll too much
3635 if (row.right_x() - offset < workWidth() - row.right_margin)
3636 offset = row.right_x() - workWidth() + row.right_margin;
3639 //lyxerr << "cur_x=" << cur_x << ", offset=" << offset << ", row.wid=" << row.width() << ", margin=" << MARGIN << endl;
3641 if (offset != d->horiz_scroll_offset_) {
3642 LYXERR(Debug::PAINTING, "Horiz. scroll offset changed from "
3643 << d->horiz_scroll_offset_ << " to " << offset);
3645 if (d->update_strategy_ == NoScreenUpdate)
3646 d->update_strategy_ = SingleParUpdate;
3649 d->horiz_scroll_offset_ = offset;
3653 bool BufferView::busy() const
3655 return buffer().undo().activeUndoGroup();
3659 void BufferView::draw(frontend::Painter & pain, bool paint_caret)
3663 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t--- START NODRAW ---"
3664 : "\t\t*** START DRAWING ***"));
3665 Text & text = buffer_.text();
3666 TextMetrics const & tm = d->text_metrics_[&text];
3667 int const y = tm.first().second->position();
3668 PainterInfo pi(this, pain);
3670 // Check whether the row where the cursor lives needs to be scrolled.
3671 // Update the drawing strategy if needed.
3672 checkCursorScrollOffset();
3674 switch (d->update_strategy_) {
3676 case NoScreenUpdate:
3677 // no screen painting is actually needed. In nodraw stage
3678 // however, the different coordinates of insets and paragraphs
3679 // needs to be updated.
3680 LYXERR(Debug::PAINTING, "Strategy: NoScreenUpdate");
3681 if (pain.isNull()) {
3682 pi.full_repaint = true;
3685 pi.full_repaint = false;
3690 case SingleParUpdate:
3691 pi.full_repaint = false;
3692 LYXERR(Debug::PAINTING, "Strategy: SingleParUpdate");
3693 // In general, only the current row of the outermost paragraph
3694 // will be redrawn. Particular cases where selection spans
3695 // multiple paragraph are correctly detected in TextMetrics.
3699 case DecorationUpdate:
3700 // FIXME: We should also distinguish DecorationUpdate to avoid text
3701 // drawing if possible. This is not possible to do easily right now
3702 // because of the single backing pixmap.
3704 case FullScreenUpdate:
3706 LYXERR(Debug::PAINTING,
3707 ((d->update_strategy_ == FullScreenUpdate)
3708 ? "Strategy: FullScreenUpdate"
3709 : "Strategy: DecorationUpdate"));
3711 // The whole screen, including insets, will be refreshed.
3712 pi.full_repaint = true;
3714 // Clear background.
3715 pain.fillRectangle(0, 0, width_, height_,
3716 pi.backgroundColor(&buffer_.inset()));
3724 // Possibly grey out below
3725 if (d->update_strategy_ != NoScreenUpdate) {
3726 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3727 int const y2 = lastpm.second->bottom();
3730 Color color = buffer().isInternal()
3731 ? Color_background : Color_bottomarea;
3732 pain.fillRectangle(0, y2, width_, height_ - y2, color);
3736 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t --- END NODRAW ---"
3737 : "\t\t *** END DRAWING ***"));
3739 // The scrollbar needs an update.
3740 // FIXME: does it always? see ticket #11947.
3741 updateScrollbarParameters();
3743 // Normalize anchor for next time (in case updateMetrics did not do it yet)
3744 // FIXME: is this useful?
3745 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
3746 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3747 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
3748 ParagraphMetrics const & pm = tm.parMetrics(pit);
3749 if (pm.bottom() > 0) {
3750 if (d->anchor_pit_ != pit
3751 || d->anchor_ypos_ != pm.position())
3752 LYXERR0(__func__ << ": Found new anchor pit = " << pit
3753 << " anchor ypos = " << pm.position()
3754 << " (was " << d->anchor_pit_ << ", " << d->anchor_ypos_ << ")"
3755 "\nIf you see this message, please report.");
3756 d->anchor_pit_ = pit;
3757 d->anchor_ypos_ = pm.position();
3762 if (!pain.isNull()) {
3763 // reset the update flags, everything has been done
3764 d->update_flags_ = Update::None;
3767 // If a caret has to be painted, mark its text row as dirty to
3768 //make sure that it will be repainted on next redraw.
3769 /* FIXME: investigate whether this can be avoided when the cursor did not
3773 Cursor cur(d->cursor_);
3774 while (cur.depth() > 1) {
3775 if (!cur.inTexted())
3777 TextMetrics const & tm = textMetrics(cur.text());
3778 if (d->caret_geometry_.left >= tm.origin().x_
3779 && d->caret_geometry_.right <= tm.origin().x_ + tm.dim().width())
3783 cur.textRow().changed(true);
3788 void BufferView::message(docstring const & msg)
3791 d->gui_->message(msg);
3795 void BufferView::showDialog(string const & name)
3798 d->gui_->showDialog(name, string());
3802 void BufferView::showDialog(string const & name,
3803 string const & data, Inset * inset)
3806 d->gui_->showDialog(name, data, inset);
3810 void BufferView::updateDialog(string const & name, string const & data)
3813 d->gui_->updateDialog(name, data);
3817 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
3823 // FIXME: Move this out of BufferView again
3824 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
3826 if (!fname.isReadableFile()) {
3827 docstring const error = from_ascii(strerror(errno));
3828 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3829 docstring const text =
3830 bformat(_("Could not read the specified document\n"
3831 "%1$s\ndue to the error: %2$s"), file, error);
3832 Alert::error(_("Could not read file"), text);
3836 if (!fname.isReadableFile()) {
3837 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3838 docstring const text =
3839 bformat(_("%1$s\n is not readable."), file);
3840 Alert::error(_("Could not open file"), text);
3844 // FIXME UNICODE: We don't know the encoding of the file
3845 docstring file_content = fname.fileContents("UTF-8");
3846 if (file_content.empty()) {
3847 Alert::error(_("Reading not UTF-8 encoded file"),
3848 _("The file is not UTF-8 encoded.\n"
3849 "It will be read as local 8Bit-encoded.\n"
3850 "If this does not give the correct result\n"
3851 "then please change the encoding of the file\n"
3852 "to UTF-8 with a program other than LyX.\n"));
3853 file_content = fname.fileContents("local8bit");
3856 return normalize_c(file_content);
3860 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
3862 docstring const tmpstr = contentsOfPlaintextFile(f);
3867 Cursor & cur = cursor();
3868 cap::replaceSelection(cur);
3869 buffer_.undo().recordUndo(cur);
3871 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3873 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3875 buffer_.changed(true);
3879 docstring const & BufferView::inlineCompletion() const
3881 return d->inlineCompletion_;
3885 size_t BufferView::inlineCompletionUniqueChars() const
3887 return d->inlineCompletionUniqueChars_;
3891 DocIterator const & BufferView::inlineCompletionPos() const
3893 return d->inlineCompletionPos_;
3897 void BufferView::resetInlineCompletionPos()
3899 d->inlineCompletionPos_ = DocIterator();
3903 bool samePar(DocIterator const & a, DocIterator const & b)
3905 if (a.empty() && b.empty())
3907 if (a.empty() || b.empty())
3909 if (a.depth() != b.depth())
3911 return &a.innerParagraph() == &b.innerParagraph();
3915 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3916 docstring const & completion, size_t uniqueChars)
3918 uniqueChars = min(completion.size(), uniqueChars);
3919 bool changed = d->inlineCompletion_ != completion
3920 || d->inlineCompletionUniqueChars_ != uniqueChars;
3921 bool singlePar = true;
3922 d->inlineCompletion_ = completion;
3923 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3925 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3928 DocIterator const & old = d->inlineCompletionPos_;
3930 //lyxerr << "inlineCompletionPos changed" << std::endl;
3931 // old or pos are in another paragraph?
3932 if ((!samePar(cur, pos) && !pos.empty())
3933 || (!samePar(cur, old) && !old.empty())) {
3935 //lyxerr << "different paragraph" << std::endl;
3937 d->inlineCompletionPos_ = pos;
3942 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3943 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3945 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3950 bool BufferView::clickableInset() const
3952 return d->clickable_inset_;
3956 bool BufferView::stats_update_trigger()
3958 if (d->stats_update_trigger_) {
3959 d->stats_update_trigger_ = false;