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_(0),
218 wh_(0), inlineCompletionUniqueChars_(0),
219 last_inset_(nullptr), mouse_position_cache_(),
220 gui_(nullptr), bookmark_edit_position_(-1),
221 horiz_scroll_offset_(0), clickable_inset_(false)
223 xsel_cache_.set = false;
227 ScrollbarParameters scrollbarParameters_;
229 ScreenUpdateStrategy update_strategy_;
231 Update::flags update_flags_;
233 CoordCache coord_cache_;
235 typedef unordered_map<MathData const *, MathRow> MathRows;
238 /// this is used to handle XSelection events in the right manner.
247 pit_type anchor_pit_;
250 /// Estimated average par height for scrollbar.
253 vector<int> par_height_;
256 DocIterator inlineCompletionPos_;
258 docstring inlineCompletion_;
260 size_t inlineCompletionUniqueChars_;
262 /// keyboard mapping object.
265 /// last visited inset.
266 /** kept to send setMouseHover(false).
267 * Not owned, so don't delete.
269 Inset const * last_inset_;
271 /// position of the mouse at the time of the last mouse move
272 /// This is used to update the hovering status of inset in
273 /// cases where the buffer is scrolled, but the mouse didn't move.
274 Point mouse_position_cache_;
276 mutable TextMetricsCache text_metrics_;
279 /** Not owned, so don't delete.
281 frontend::GuiBufferViewDelegate * gui_;
284 map<string, Inset *> edited_insets_;
286 // 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;
559 } else if (flags & Update::ForceDraw)
560 // This will compute only the needed metrics and update positions.
561 updateMetrics(false);
563 // Detect whether we can only repaint a single paragraph (if we
564 // are not already redrawing all).
565 // We handle this before FitCursor because the later will require
566 // correct metrics at cursor position.
567 if (!(flags & Update::ForceDraw)
568 && (flags & Update::SinglePar)
569 && !singleParUpdate())
572 // Then make sure that the screen contains the cursor if needed
573 if (flags & Update::FitCursor) {
574 if (needsFitCursor()) {
575 // First try to make the selection start visible
576 // (which is just the cursor when there is no selection)
577 scrollToCursor(d->cursor_.selectionBegin(), SCROLL_VISIBLE);
578 // Metrics have to be recomputed (maybe again)
580 // Is the cursor visible? (only useful if cursor is at end of selection)
581 if (needsFitCursor()) {
582 // then try to make cursor visible instead
583 scrollToCursor(d->cursor_, SCROLL_VISIBLE);
584 // Metrics have to be recomputed (maybe again)
588 flags = flags & ~Update::FitCursor;
591 // Add flags to the the update flags. These will be reset to None
592 // after the redraw is actually done
593 d->update_flags_ = d->update_flags_ | flags;
594 LYXERR(Debug::PAINTING, "Cumulative flags: " << flagsAsString(flags));
596 // Now compute the update strategy
597 // Possibly values in flag are None, SinglePar, Decoration, ForceDraw
598 LATTEST((d->update_flags_ & ~(Update::None | Update::SinglePar
599 | Update::Decoration | Update::ForceDraw)) == 0);
601 if (d->update_flags_ & Update::ForceDraw)
602 d->update_strategy_ = FullScreenUpdate;
603 else if (d->update_flags_ & Update::Decoration)
604 d->update_strategy_ = DecorationUpdate;
605 else if (d->update_flags_ & Update::SinglePar)
606 d->update_strategy_ = SingleParUpdate;
608 // no need to redraw anything.
609 d->update_strategy_ = NoScreenUpdate;
612 updateHoveredInset();
615 buffer_.changed(false);
619 void BufferView::updateScrollbarParameters()
624 // We prefer fixed size line scrolling.
625 d->scrollbarParameters_.single_step = defaultRowHeight();
626 // We prefer full screen page scrolling.
627 d->scrollbarParameters_.page_step = height_;
629 Text & t = buffer_.text();
630 TextMetrics & tm = d->text_metrics_[&t];
632 LYXERR(Debug::SCROLLING, " Updating scrollbar: height: "
633 << t.paragraphs().size()
634 << " curr par: " << d->cursor_.bottom().pit()
635 << " default height " << defaultRowHeight());
637 size_t const parsize = t.paragraphs().size();
638 if (d->par_height_.size() != parsize) {
639 d->par_height_.clear();
640 // FIXME: We assume a default paragraph height of 2 rows. This
641 // should probably be pondered with the screen width.
642 d->par_height_.resize(parsize, defaultRowHeight() * 2);
645 // Look at paragraph heights on-screen
646 pair<pit_type, ParagraphMetrics const *> first = tm.first();
647 pair<pit_type, ParagraphMetrics const *> last = tm.last();
648 for (pit_type pit = first.first; pit <= last.first; ++pit) {
649 d->par_height_[pit] = tm.parMetrics(pit).height();
650 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
651 << d->par_height_[pit]);
654 int top_pos = first.second->top();
655 int bottom_pos = last.second->bottom();
656 bool first_visible = first.first == 0 && top_pos >= 0;
657 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
658 if (first_visible && last_visible) {
659 d->scrollbarParameters_.min = 0;
660 d->scrollbarParameters_.max = 0;
664 d->scrollbarParameters_.min = top_pos;
665 for (size_t i = 0; i != size_t(first.first); ++i)
666 d->scrollbarParameters_.min -= d->par_height_[i];
667 d->scrollbarParameters_.max = bottom_pos;
668 for (size_t i = last.first + 1; i != parsize; ++i)
669 d->scrollbarParameters_.max += d->par_height_[i];
671 // The reference is the top position so we remove one page.
672 if (lyxrc.scroll_below_document)
673 d->scrollbarParameters_.max -= minVisiblePart();
675 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
677 // 0 must be inside the range as it denotes the current position
678 if (d->scrollbarParameters_.max < 0)
679 d->scrollbarParameters_.max = 0;
680 if (d->scrollbarParameters_.min > 0)
681 d->scrollbarParameters_.min = 0;
685 ScrollbarParameters const & BufferView::scrollbarParameters() const
687 return d->scrollbarParameters_;
691 docstring BufferView::toolTip(int x, int y) const
693 // Get inset under mouse, if there is one.
694 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
696 // No inset, no tooltip...
698 return covering_inset->toolTip(*this, x, y);
702 string BufferView::contextMenu(int x, int y) const
704 //If there is a selection, return the containing inset menu
705 if (d->cursor_.selection())
706 return d->cursor_.inset().contextMenu(*this, x, y);
708 // Get inset under mouse, if there is one.
709 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
710 if (covering_inset) {
711 if (covering_inset->asInsetMath()) {
712 CoordCache::Insets const & inset_cache =
713 coordCache().getInsets();
714 Inset const * inner_inset = mathContextMenu(
715 covering_inset->asInsetMath()->asNestInset(),
718 return inner_inset->contextMenu(*this, x, y);
720 return covering_inset->contextMenu(*this, x, y);
723 return buffer_.inset().contextMenu(*this, x, y);
727 Inset const * BufferView::mathContextMenu(InsetMathNest const * inset,
728 CoordCache::Insets const & inset_cache, int x, int y) const
730 for (size_t i = 0; i < inset->nargs(); ++i) {
731 MathData const & ar = inset->cell(i);
732 for (size_t j = 0; j < ar.size(); ++j) {
733 string const name = lyxerr.debugging(Debug::MATHED)
734 ? insetName(ar[j].nucleus()->lyxCode())
736 LYXERR(Debug::MATHED, "Examining inset: " << name);
737 if (!ar[j].nucleus()->contextMenuName().empty()) {
738 if (inset_cache.covers(ar[j].nucleus(), x, y)) {
739 LYXERR(Debug::MATHED, "Hit inset: "
741 return ar[j].nucleus();
744 InsetMathNest const * imn =
745 ar[j].nucleus()->asNestInset();
747 Inset const * inner =
748 mathContextMenu(imn, inset_cache, x, y);
758 void BufferView::scrollDocView(int const pixels, bool update)
760 // The scrollbar values are relative to the top of the screen, therefore the
761 // offset is equal to the target value.
763 // No scrolling at all? No need to redraw anything
767 // If part of the existing paragraphs will remain visible, prefer to
769 TextMetrics const & tm = textMetrics(&buffer_.text());
770 if (tm.first().second->top() - pixels <= height_
771 && tm.last().second->bottom() - pixels >= 0) {
772 LYXERR(Debug::SCROLLING, "small skip");
773 d->anchor_ypos_ -= pixels;
774 processUpdateFlags(Update::ForceDraw);
778 // cut off at the top
779 if (pixels <= d->scrollbarParameters_.min) {
780 DocIterator dit = doc_iterator_begin(&buffer_);
781 showCursor(dit, SCROLL_VISIBLE, update);
782 LYXERR(Debug::SCROLLING, "scroll to top");
786 // cut off at the bottom
787 if (pixels >= d->scrollbarParameters_.max) {
788 DocIterator dit = doc_iterator_end(&buffer_);
790 showCursor(dit, SCROLL_VISIBLE, update);
791 LYXERR(Debug::SCROLLING, "scroll to bottom");
795 LYXERR(Debug::SCROLLING, "search paragraph");
796 // find paragraph at target position
797 int par_pos = d->scrollbarParameters_.min;
799 for (; i != int(d->par_height_.size()); ++i) {
800 par_pos += d->par_height_[i];
801 if (par_pos >= pixels)
805 if (par_pos < pixels) {
806 // It seems we didn't find the correct pit so stay on the safe side and
808 LYXERR0("scrolling position not found!");
809 scrollDocView(d->scrollbarParameters_.max, update);
813 DocIterator dit = doc_iterator_begin(&buffer_);
815 LYXERR(Debug::SCROLLING, "pixels = " << pixels << " -> scroll to pit " << i);
816 showCursor(dit, SCROLL_VISIBLE, update);
820 // FIXME: this method is not working well.
821 void BufferView::setCursorFromScrollbar()
823 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
825 int const height = 2 * defaultRowHeight();
826 int const first = height;
827 int const last = height_ - height;
829 Cursor const & oldcur = d->cursor_;
831 switch (cursorStatus(oldcur)) {
839 int const y = getPos(oldcur).y_;
840 newy = min(last, max(y, first));
844 // We reset the cursor because cursorStatus() does not
845 // work when the cursor is within mathed.
848 tm.setCursorFromCoordinates(cur, 0, newy);
850 // update the bufferview cursor and notify insets
851 // FIXME: Care about the d->cursor_ flags to redraw if needed
852 Cursor old = d->cursor_;
854 // the DEPM call in mouseSetCursor() might have destroyed the
855 // paragraph the cursor is in.
856 bool badcursor = old.fixIfBroken();
857 badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
859 d->cursor_.fixIfBroken();
863 Change const BufferView::getCurrentChange() const
865 if (!d->cursor_.selection())
866 return Change(Change::UNCHANGED);
868 DocIterator dit = d->cursor_.selectionBegin();
869 // The selected content might have been changed (see #7685)
870 dit = dit.getInnerText();
871 return dit.paragraph().lookupChange(dit.pos());
875 // this could be used elsewhere as well?
876 // FIXME: This does not work within mathed!
877 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
879 Point const p = getPos(dit);
882 if (p.y_ > workHeight())
888 void BufferView::bookmarkEditPosition()
890 // Don't eat cpu time for each keystroke
891 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
894 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
898 void BufferView::saveBookmark(unsigned int idx)
900 if (buffer().isInternal())
903 // tentatively save bookmark, id and pos will be used to
904 // acturately locate a bookmark in a 'live' lyx session.
905 // pit and pos will be updated with bottom level pit/pos
907 theSession().bookmarks().save(
909 d->cursor_.bottom().pit(),
910 d->cursor_.bottom().pos(),
911 d->cursor_.paragraph().id(),
916 // emit message signal.
917 message(_("Save bookmark"));
921 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
922 int top_id, pos_type top_pos)
924 bool success = false;
927 d->cursor_.clearSelection();
929 // if a valid par_id is given, try it first
930 // This is the case for a 'live' bookmark when unique paragraph ID
931 // is used to track bookmarks.
933 dit = buffer_.getParFromID(top_id);
935 dit.pos() = min(dit.paragraph().size(), top_pos);
936 // Some slices of the iterator may not be
937 // reachable (e.g. closed collapsible inset)
938 // so the dociterator may need to be
939 // shortened. Otherwise, setCursor may crash
940 // lyx when the cursor can not be set to these
942 size_t const n = dit.depth();
943 for (size_t i = 0; i < n; ++i)
944 if (!dit[i].inset().editable()) {
952 // if top_id == 0, or searching through top_id failed
953 // This is the case for a 'restored' bookmark when only bottom
954 // (document level) pit was saved. Because of this, bookmark
955 // restoration is inaccurate. If a bookmark was within an inset,
956 // it will be restored to the left of the outmost inset that contains
958 if (!success && bottom_pit < int(buffer_.paragraphs().size())) {
959 dit = doc_iterator_begin(&buffer_);
961 dit.pit() = bottom_pit;
962 dit.pos() = min(bottom_pos, dit.paragraph().size());
967 // Note: only bottom (document) level pit is set.
969 // set the current font.
970 d->cursor_.setCurrentFont();
971 // Do not forget to reset the anchor (see #9912)
972 d->cursor_.resetAnchor();
973 processUpdateFlags(Update::Force | Update::FitCursor);
980 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
982 if (d->cursor_.real_current_font.isRightToLeft()) {
983 if (d->intl_.keymap == Intl::PRIMARY)
984 d->intl_.keyMapSec();
986 if (d->intl_.keymap == Intl::SECONDARY)
987 d->intl_.keyMapPrim();
990 d->intl_.getTransManager().translateAndInsert(c, t, cur);
994 int BufferView::workWidth() const
1000 void BufferView::recenter()
1002 showCursor(d->cursor_, SCROLL_CENTER, true);
1006 void BufferView::showCursor()
1008 showCursor(d->cursor_, SCROLL_VISIBLE, true);
1012 void BufferView::showCursor(DocIterator const & dit, ScrollType how,
1015 if (scrollToCursor(dit, how) && update)
1016 processUpdateFlags(Update::Force);
1020 bool BufferView::scrollToCursor(DocIterator const & dit, ScrollType how)
1022 // We are not properly started yet, delay until resizing is done.
1026 if (how == SCROLL_CENTER)
1027 LYXERR(Debug::SCROLLING, "Centering cursor in workarea");
1028 else if (how == SCROLL_TOP)
1029 LYXERR(Debug::SCROLLING, "Setting cursor to top of workarea");
1031 LYXERR(Debug::SCROLLING, "Making sure cursor is visible in workarea");
1033 CursorSlice const & bot = dit.bottom();
1034 TextMetrics & tm = textMetrics(bot.text());
1036 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
1037 pos_type bot_pit = bot.pit();
1038 if (bot_pit > max_pit) {
1039 // FIXME: Why does this happen?
1040 LYXERR0("bottom pit is greater that max pit: "
1041 << bot_pit << " > " << max_pit);
1045 if (bot_pit == tm.first().first - 1)
1046 tm.newParMetricsUp();
1047 else if (bot_pit == tm.last().first + 1)
1048 tm.newParMetricsDown();
1050 if (tm.contains(bot_pit) && how == SCROLL_VISIBLE) {
1051 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
1052 LBUFERR(!pm.rows().empty());
1053 // FIXME: smooth scrolling doesn't work in mathed.
1054 CursorSlice const & cs = dit.innerTextSlice();
1055 int const ypos = pm.position() + coordOffset(dit).y_;
1056 ParagraphMetrics const & inner_pm =
1057 textMetrics(cs.text()).parMetrics(cs.pit());
1058 Dimension const & row_dim =
1059 inner_pm.getRow(cs.pos(), dit.boundary()).dim();
1062 // We try to visualize the whole row, if the row height is larger than
1063 // the screen height, we scroll to a heuristic value of height_ / 4.
1064 // FIXME: This heuristic value should be replaced by a recursive search
1065 // for a row in the inset that can be visualized completely.
1066 if (row_dim.height() > height_) {
1067 if (ypos < defaultRowHeight())
1068 scrolled = scroll(ypos - height_ / 4);
1069 else if (ypos > height_ - defaultRowHeight())
1070 scrolled = scroll(ypos - 3 * height_ / 4);
1073 // If the top part of the row falls of the screen, we scroll
1074 // up to align the top of the row with the top of the screen.
1075 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
1076 int const ynew = row_dim.ascent();
1077 scrolled = scrollUp(ynew - ypos);
1080 // If the bottom of the row falls of the screen, we scroll down.
1081 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
1082 int const ynew = height_ - row_dim.descent();
1083 scrolled = scrollDown(ypos - ynew);
1086 // else, nothing to do, the cursor is already visible so we just return.
1087 return scrolled != 0;
1090 // fix inline completion position
1091 if (d->inlineCompletionPos_.fixIfBroken())
1092 d->inlineCompletionPos_ = DocIterator();
1094 tm.redoParagraph(bot_pit);
1095 int const offset = coordOffset(dit).y_;
1096 pit_type const old_pit = d->anchor_pit_;
1097 d->anchor_pit_ = bot_pit;
1099 CursorSlice const & cs = dit.innerTextSlice();
1100 ParagraphMetrics const & inner_pm =
1101 textMetrics(cs.text()).parMetrics(cs.pit());
1102 Dimension const & row_dim =
1103 inner_pm.getRow(cs.pos(), dit.boundary()).dim();
1105 int const old_ypos = d->anchor_ypos_;
1106 d->anchor_ypos_ = - offset + row_dim.ascent();
1107 if (how == SCROLL_CENTER)
1108 d->anchor_ypos_ += height_/2 - row_dim.height() / 2;
1109 else if (offset > height_)
1110 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
1112 d->anchor_ypos_ = defaultRowHeight() * 2;
1114 return d->anchor_ypos_ != old_ypos || d->anchor_pit_ != old_pit;
1118 void BufferView::makeDocumentClass()
1120 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1121 buffer_.params().makeDocumentClass(buffer_.isClone(), buffer_.isInternal());
1122 updateDocumentClass(olddc);
1126 void BufferView::updateDocumentClass(DocumentClassConstPtr olddc)
1128 StableDocIterator backcur(d->cursor_);
1129 ErrorList & el = buffer_.errorList("Class Switch");
1130 cap::switchBetweenClasses(
1131 olddc, buffer_.params().documentClassPtr(),
1132 static_cast<InsetText &>(buffer_.inset()), el);
1134 setCursor(backcur.asDocIterator(&buffer_));
1136 buffer_.errors("Class Switch");
1140 /** Return the change status at cursor position, taking into account the
1141 * status at each level of the document iterator (a table in a deleted
1142 * footnote is deleted).
1143 * When \param outer is true, the top slice is not looked at.
1145 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
1147 size_t const depth = dit.depth() - (outer ? 1 : 0);
1149 for (size_t i = 0 ; i < depth ; ++i) {
1150 CursorSlice const & slice = dit[i];
1151 if (!slice.inset().inMathed()
1152 && slice.pos() < slice.paragraph().size()) {
1153 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
1154 if (ch != Change::UNCHANGED)
1158 return Change::UNCHANGED;
1162 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1164 FuncCode const act = cmd.action();
1166 // Can we use a readonly buffer?
1167 if (buffer_.isReadonly()
1168 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1169 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1170 if (buffer_.hasReadonlyFlag())
1171 flag.message(from_utf8(N_("Document is read-only")));
1173 flag.message(from_utf8(N_("Document has been modified externally")));
1174 flag.setEnabled(false);
1178 // Are we in a DELETED change-tracking region?
1179 if (lookupChangeType(d->cursor_, true) == Change::DELETED
1180 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1181 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1182 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1183 flag.setEnabled(false);
1187 Cursor & cur = d->cursor_;
1189 if (cur.getStatus(cmd, flag))
1194 // FIXME: This is a bit problematic because we don't check if this is
1195 // a document BufferView or not for these LFUNs. We probably have to
1196 // dispatch both to currentBufferView() and, if that fails,
1197 // to documentBufferView(); same as we do now for current Buffer and
1198 // document Buffer. Ideally those LFUN should go to Buffer as they
1199 // operate on the full Buffer and the cursor is only needed either for
1200 // an Undo record or to restore a cursor position. But we don't know
1201 // how to do that inside Buffer of course.
1202 case LFUN_BUFFER_PARAMS_APPLY:
1203 case LFUN_LAYOUT_MODULES_CLEAR:
1204 case LFUN_LAYOUT_MODULE_ADD:
1205 case LFUN_LAYOUT_RELOAD:
1206 case LFUN_TEXTCLASS_APPLY:
1207 case LFUN_TEXTCLASS_LOAD:
1208 flag.setEnabled(!buffer_.isReadonly());
1212 // We do not use the LyXAction flag for readonly because Undo sets the
1213 // buffer clean/dirty status by itself.
1214 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1217 // We do not use the LyXAction flag for readonly because Redo sets the
1218 // buffer clean/dirty status by itself.
1219 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1221 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1222 case LFUN_FILE_INSERT_PLAINTEXT: {
1223 docstring const & fname = cmd.argument();
1224 if (!FileName::isAbsolute(to_utf8(fname))) {
1225 flag.message(_("Absolute filename expected."));
1228 flag.setEnabled(cur.inTexted());
1231 case LFUN_FILE_INSERT:
1232 case LFUN_BOOKMARK_SAVE:
1233 // FIXME: Actually, these LFUNS should be moved to Text
1234 flag.setEnabled(cur.inTexted());
1237 case LFUN_FONT_STATE:
1238 case LFUN_LABEL_INSERT:
1239 case LFUN_INFO_INSERT:
1240 case LFUN_PARAGRAPH_GOTO:
1241 case LFUN_NOTE_NEXT:
1242 case LFUN_REFERENCE_NEXT:
1243 case LFUN_WORD_FIND:
1244 case LFUN_WORD_FIND_FORWARD:
1245 case LFUN_WORD_FIND_BACKWARD:
1246 case LFUN_WORD_REPLACE:
1249 case LFUN_MARK_TOGGLE:
1250 case LFUN_SEARCH_STRING_SET:
1251 case LFUN_SCREEN_RECENTER:
1252 case LFUN_SCREEN_SHOW_CURSOR:
1253 case LFUN_BIBTEX_DATABASE_ADD:
1254 case LFUN_BIBTEX_DATABASE_DEL:
1255 case LFUN_BIBTEX_DATABASE_LIST:
1256 case LFUN_STATISTICS:
1257 case LFUN_KEYMAP_OFF:
1258 case LFUN_KEYMAP_PRIMARY:
1259 case LFUN_KEYMAP_SECONDARY:
1260 case LFUN_KEYMAP_TOGGLE:
1261 case LFUN_INSET_SELECT_ALL:
1262 flag.setEnabled(true);
1265 case LFUN_GRAPHICS_UNIFY:
1266 flag.setEnabled(cur.countInsetsInSelection(GRAPHICS_CODE)>1);
1269 case LFUN_WORD_FINDADV: {
1270 FindAndReplaceOptions opt;
1271 istringstream iss(to_utf8(cmd.argument()));
1273 flag.setEnabled(opt.repl_buf_name.empty()
1274 || !buffer_.isReadonly());
1278 case LFUN_LABEL_GOTO:
1279 flag.setEnabled(!cmd.argument().empty()
1280 || getInsetByCode<InsetRef>(cur, REF_CODE)
1281 || getInsetByCode<InsetMathRef>(cur, MATH_REF_CODE));
1284 case LFUN_CHANGES_MERGE:
1285 case LFUN_CHANGE_NEXT:
1286 case LFUN_CHANGE_PREVIOUS:
1287 case LFUN_ALL_CHANGES_ACCEPT:
1288 case LFUN_ALL_CHANGES_REJECT:
1289 flag.setEnabled(buffer_.areChangesPresent());
1292 case LFUN_SCREEN_UP:
1293 case LFUN_SCREEN_DOWN:
1295 case LFUN_SCREEN_UP_SELECT:
1296 case LFUN_SCREEN_DOWN_SELECT:
1297 case LFUN_INSET_FORALL:
1298 flag.setEnabled(true);
1301 case LFUN_LAYOUT_TABULAR:
1302 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1306 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1309 case LFUN_LAYOUT_PARAGRAPH:
1310 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1313 case LFUN_BRANCH_ADD_INSERT:
1314 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1317 case LFUN_DIALOG_SHOW_NEW_INSET:
1318 // FIXME: this is wrong, but I do not understand the
1320 if (cur.inset().lyxCode() == CAPTION_CODE)
1321 return cur.inset().getStatus(cur, cmd, flag);
1322 // FIXME we should consider passthru paragraphs too.
1323 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1326 case LFUN_CITATION_INSERT: {
1327 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1328 // FIXME: This could turn in a recursive hell.
1329 // Shouldn't we use Buffer::getStatus() instead?
1330 flag.setEnabled(lyx::getStatus(fr).enabled());
1333 case LFUN_INSET_APPLY: {
1334 string const name = cmd.getArg(0);
1335 Inset * inset = editedInset(name);
1337 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1338 if (!inset->getStatus(cur, fr, flag)) {
1339 // Every inset is supposed to handle this
1340 LASSERT(false, break);
1343 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1344 flag = lyx::getStatus(fr);
1350 flag.setEnabled(cur.selection());
1353 case LFUN_STATISTICS_REFERENCE_CLAMP: {
1354 // disable optitem reset if clamp not used
1355 if (cmd.argument() == "reset" && d->stats_ref_value_c_ == 0) {
1356 flag.setEnabled(false);
1359 flag.setEnabled(true);
1372 Inset * BufferView::editedInset(string const & name) const
1374 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1375 return it == d->edited_insets_.end() ? nullptr : it->second;
1379 void BufferView::editInset(string const & name, Inset * inset)
1382 d->edited_insets_[name] = inset;
1384 d->edited_insets_.erase(name);
1388 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1390 LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1392 string const argument = to_utf8(cmd.argument());
1393 Cursor & cur = d->cursor_;
1396 // Don't dispatch function that does not apply to internal buffers.
1397 if (buffer_.isInternal()
1398 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1401 // We'll set this back to false if need be.
1402 bool dispatched = true;
1403 buffer_.undo().beginUndoGroup();
1405 FuncCode const act = cmd.action();
1408 case LFUN_BUFFER_PARAMS_APPLY: {
1409 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1410 cur.recordUndoBufferParams();
1411 istringstream ss(to_utf8(cmd.argument()));
1414 int const unknown_tokens = buffer_.readHeader(lex);
1415 if (unknown_tokens != 0) {
1416 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1417 << unknown_tokens << " unknown token"
1418 << (unknown_tokens == 1 ? "" : "s"));
1420 updateDocumentClass(olddc);
1422 // We are most certainly here because of a change in the document
1423 // It is then better to make sure that all dialogs are in sync with
1424 // current document settings.
1425 dr.screenUpdate(Update::Force | Update::FitCursor);
1426 dr.forceBufferUpdate();
1430 case LFUN_LAYOUT_MODULES_CLEAR: {
1431 // FIXME: this modifies the document in cap::switchBetweenClasses
1432 // without calling recordUndo. Fix this before using
1433 // recordUndoBufferParams().
1434 cur.recordUndoFullBuffer();
1435 buffer_.params().clearLayoutModules();
1436 makeDocumentClass();
1437 dr.screenUpdate(Update::Force);
1438 dr.forceBufferUpdate();
1442 case LFUN_LAYOUT_MODULE_ADD: {
1443 BufferParams const & params = buffer_.params();
1444 if (!params.layoutModuleCanBeAdded(argument)) {
1445 LYXERR0("Module `" << argument <<
1446 "' cannot be added due to failed requirements or "
1447 "conflicts with installed modules.");
1450 // FIXME: this modifies the document in cap::switchBetweenClasses
1451 // without calling recordUndo. Fix this before using
1452 // recordUndoBufferParams().
1453 cur.recordUndoFullBuffer();
1454 buffer_.params().addLayoutModule(argument);
1455 makeDocumentClass();
1456 dr.screenUpdate(Update::Force);
1457 dr.forceBufferUpdate();
1461 case LFUN_TEXTCLASS_APPLY: {
1462 // since this shortcircuits, the second call is made only if
1464 bool const success =
1465 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1466 LayoutFileList::get().load(argument, buffer_.filePath());
1468 docstring s = bformat(_("The document class `%1$s' "
1469 "could not be loaded."), from_utf8(argument));
1470 frontend::Alert::error(_("Could not load class"), s);
1474 LayoutFile const * old_layout = buffer_.params().baseClass();
1475 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1477 if (old_layout == new_layout)
1481 // Save the old, possibly modular, layout for use in conversion.
1482 // FIXME: this modifies the document in cap::switchBetweenClasses
1483 // without calling recordUndo. Fix this before using
1484 // recordUndoBufferParams().
1485 cur.recordUndoFullBuffer();
1486 buffer_.params().setBaseClass(argument, buffer_.layoutPos());
1487 makeDocumentClass();
1488 dr.screenUpdate(Update::Force);
1489 dr.forceBufferUpdate();
1493 case LFUN_TEXTCLASS_LOAD: {
1494 // since this shortcircuits, the second call is made only if
1496 bool const success =
1497 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1498 LayoutFileList::get().load(argument, buffer_.filePath());
1500 docstring s = bformat(_("The document class `%1$s' "
1501 "could not be loaded."), from_utf8(argument));
1502 frontend::Alert::error(_("Could not load class"), s);
1507 case LFUN_LAYOUT_RELOAD: {
1508 LayoutFileIndex bc = buffer_.params().baseClassID();
1509 LayoutFileList::get().reset(bc);
1510 buffer_.params().setBaseClass(bc, buffer_.layoutPos());
1511 makeDocumentClass();
1512 dr.screenUpdate(Update::Force);
1513 dr.forceBufferUpdate();
1518 dr.setMessage(_("Undo"));
1519 cur.clearSelection();
1520 // We need to find out if the bibliography information
1521 // has changed. See bug #11055.
1522 // So these should not be references...
1523 string const engine = buffer().params().citeEngine();
1524 CiteEngineType const enginetype = buffer().params().citeEngineType();
1525 if (!cur.undoAction())
1526 dr.setMessage(_("No further undo information"));
1528 dr.screenUpdate(Update::Force | Update::FitCursor);
1529 dr.forceBufferUpdate();
1530 resetInlineCompletionPos();
1531 if (buffer().params().citeEngine() != engine ||
1532 buffer().params().citeEngineType() != enginetype)
1533 buffer().invalidateCiteLabels();
1539 dr.setMessage(_("Redo"));
1540 cur.clearSelection();
1541 // We need to find out if the bibliography information
1542 // has changed. See bug #11055.
1543 // So these should not be references...
1544 string const engine = buffer().params().citeEngine();
1545 CiteEngineType const enginetype = buffer().params().citeEngineType();
1546 if (!cur.redoAction())
1547 dr.setMessage(_("No further redo information"));
1549 dr.screenUpdate(Update::Force | Update::FitCursor);
1550 dr.forceBufferUpdate();
1551 resetInlineCompletionPos();
1552 if (buffer().params().citeEngine() != engine ||
1553 buffer().params().citeEngineType() != enginetype)
1554 buffer().invalidateCiteLabels();
1559 case LFUN_FONT_STATE:
1560 dr.setMessage(cur.currentState(false));
1563 case LFUN_BOOKMARK_SAVE:
1564 dr.screenUpdate(Update::Force);
1565 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1568 case LFUN_LABEL_GOTO: {
1569 docstring label = cmd.argument();
1570 if (label.empty()) {
1572 getInsetByCode<InsetRef>(cur, REF_CODE);
1574 label = inset->getParam("reference");
1575 // persistent=false: use temp_bookmark
1579 if (!label.empty()) {
1581 // at the moment, this is redundant, since gotoLabel will
1582 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1584 dr.screenUpdate(Update::Force | Update::FitCursor);
1586 InsetMathRef * minset =
1587 getInsetByCode<InsetMathRef>(cur, MATH_REF_CODE);
1589 lyx::dispatch(FuncRequest(LFUN_LABEL_GOTO,
1590 minset->getTarget()));
1595 case LFUN_PARAGRAPH_GOTO: {
1596 int const id = convert<int>(cmd.getArg(0));
1597 pos_type const pos = convert<int>(cmd.getArg(1));
1600 string const str_id_end = cmd.getArg(2);
1601 string const str_pos_end = cmd.getArg(3);
1603 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1604 b = theBufferList().next(b)) {
1607 curs.setCursor(b->getParFromID(id));
1609 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1613 LYXERR(Debug::INFO, "Paragraph " << curs.paragraph().id()
1614 << " found in buffer `"
1615 << b->absFileName() << "'.");
1617 if (b == &buffer_) {
1619 if (str_id_end.empty() || str_pos_end.empty()) {
1622 mouseSetCursor(curs);
1625 int const id_end = convert<int>(str_id_end);
1626 pos_type const pos_end = convert<int>(str_pos_end);
1627 success = setCursorFromEntries({id, pos},
1630 if (success && scrollToCursor(d->cursor_, SCROLL_TOP))
1631 dr.screenUpdate(Update::Force);
1633 // Switch to other buffer view and resend cmd
1634 lyx::dispatch(FuncRequest(
1635 LFUN_BUFFER_SWITCH, b->absFileName()));
1643 case LFUN_NOTE_NEXT:
1644 if (gotoInset(this, { NOTE_CODE }, false))
1645 dr.screenUpdate(Update::Force);
1648 case LFUN_REFERENCE_NEXT: {
1649 if (gotoInset(this, { LABEL_CODE, REF_CODE }, true))
1650 dr.screenUpdate(Update::Force);
1654 case LFUN_CHANGE_NEXT:
1655 findNextChange(this);
1656 if (cur.inset().isTable())
1657 // In tables, there might be whole changed rows or columns
1659 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1660 dr.screenUpdate(Update::Force | Update::FitCursor);
1663 case LFUN_CHANGE_PREVIOUS:
1664 findPreviousChange(this);
1665 if (cur.inset().isTable())
1666 // In tables, there might be whole changed rows or columns
1668 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1669 dr.screenUpdate(Update::Force | Update::FitCursor);
1672 case LFUN_CHANGES_MERGE:
1673 if (findNextChange(this) || findPreviousChange(this)) {
1674 dr.screenUpdate(Update::Force | Update::FitCursor);
1675 dr.forceBufferUpdate();
1676 showDialog("changes");
1680 case LFUN_ALL_CHANGES_ACCEPT: {
1681 // select complete document
1683 cur.selHandle(true);
1684 buffer_.text().cursorBottom(cur);
1685 // accept everything in a single step to support atomic undo
1686 // temporarily disable track changes in order to end with really
1687 // no new (e.g., DPSM-caused) changes (see #7487)
1688 bool const track = buffer_.params().track_changes;
1689 buffer_.params().track_changes = false;
1690 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1691 buffer_.params().track_changes = track;
1693 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1694 dr.screenUpdate(Update::Force | Update::FitCursor);
1695 dr.forceBufferUpdate();
1699 case LFUN_ALL_CHANGES_REJECT: {
1700 // select complete document
1702 cur.selHandle(true);
1703 buffer_.text().cursorBottom(cur);
1704 // reject everything in a single step to support atomic undo
1705 // temporarily disable track changes in order to end with really
1706 // no new (e.g., DPSM-caused) changes (see #7487)
1707 bool const track = buffer_.params().track_changes;
1708 buffer_.params().track_changes = false;
1709 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1710 buffer_.params().track_changes = track;
1712 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1713 dr.screenUpdate(Update::Force | Update::FitCursor);
1714 dr.forceBufferUpdate();
1718 case LFUN_WORD_FIND_FORWARD:
1719 case LFUN_WORD_FIND_BACKWARD: {
1720 docstring searched_string;
1722 if (!cmd.argument().empty()) {
1723 setSearchRequestCache(cmd.argument());
1724 searched_string = cmd.argument();
1726 searched_string = searchRequestCache();
1729 if (searched_string.empty())
1732 docstring const data =
1733 find2string(searched_string, false, false,
1734 act == LFUN_WORD_FIND_FORWARD, false, false, false);
1735 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1737 dr.screenUpdate(Update::Force | Update::FitCursor);
1739 dr.setMessage(_("Search string not found!"));
1743 case LFUN_WORD_FIND: {
1744 docstring arg = cmd.argument();
1746 arg = searchRequestCache();
1748 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1751 if (lyxfind(this, FuncRequest(act, arg)))
1752 dr.screenUpdate(Update::Force | Update::FitCursor);
1754 dr.setMessage(_("Search string not found!"));
1756 setSearchRequestCache(arg);
1760 case LFUN_SEARCH_STRING_SET: {
1761 docstring pattern = cmd.argument();
1762 if (!pattern.empty()) {
1763 setSearchRequestCache(pattern);
1766 if (cur.selection())
1767 pattern = cur.selectionAsString(false);
1768 else if (!cur.inTexted())
1769 break; // not suitable for selectWord at cursor
1771 pos_type spos = cur.pos();
1772 cur.innerText()->selectWord(cur, WHOLE_WORD);
1773 pattern = cur.selectionAsString(false);
1774 cur.selection(false);
1777 setSearchRequestCache(pattern);
1781 case LFUN_WORD_REPLACE: {
1782 if (lyxreplace(this, cmd)) {
1783 dr.forceBufferUpdate();
1784 dr.screenUpdate(Update::Force | Update::FitCursor);
1787 dr.setMessage(_("Search string not found!"));
1791 case LFUN_WORD_FINDADV: {
1792 FindAndReplaceOptions opt;
1793 istringstream iss(to_utf8(cmd.argument()));
1795 if (findAdv(this, opt)) {
1796 dr.screenUpdate(Update::Force | Update::FitCursor);
1806 case LFUN_INDEX_TAG_ALL: {
1811 Inset * ins = cur.nextInset();
1812 if (!ins || ins->lyxCode() != INDEX_CODE)
1813 // not at index inset
1816 // clone the index inset
1818 new InsetIndex(static_cast<InsetIndex &>(*cur.nextInset()));
1819 // In order to avoid duplication, we compare the
1820 // LaTeX output if we find another index inset after
1822 odocstringstream oilatex;
1823 otexstream oits(oilatex);
1824 OutputParams rp(&cur.buffer()->params().encoding());
1825 ins->latex(oits, rp);
1826 cap::copyInsetToTemp(cur, cins);
1828 // move backwards into preceding word
1829 // skip over other index insets
1830 cur.backwardPosIgnoreCollapsed();
1832 if (cur.inset().lyxCode() == INDEX_CODE)
1834 else if (cur.prevInset() && cur.prevInset()->lyxCode() == INDEX_CODE)
1835 cur.backwardPosIgnoreCollapsed();
1839 if (!cur.inTexted()) {
1840 // Nothing to do here.
1841 setCursorFromInset(ins);
1844 // Get word or selection
1845 cur.text()->selectWord(cur, WHOLE_WORD);
1846 docstring const searched_string = cur.selectionAsString(false);
1847 if (searched_string.empty())
1849 // Start from the beginning
1850 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
1851 while (findOne(this, searched_string,
1852 false,// case sensitive
1853 true,// match whole word only
1855 false,//find deleted
1859 false// only selection
1861 cur.clearSelection();
1862 Inset * ains = cur.nextInset();
1863 if (ains && ains->lyxCode() == INDEX_CODE) {
1864 // We have an index inset.
1865 // Check whether it has the same
1866 // LaTeX content and move on if so.
1867 odocstringstream filatex;
1868 otexstream fits(filatex);
1869 ains->latex(fits, rp);
1870 if (oilatex.str() == filatex.str())
1873 // Paste the inset and possibly continue
1874 cap::pasteFromTemp(cursor(), cursor().buffer()->errorList("Paste"));
1876 // Go back to start position.
1877 setCursorFromInset(ins);
1878 dr.screenUpdate(cur.result().screenUpdate());
1879 if (cur.result().needBufferUpdate())
1880 dr.forceBufferUpdate();
1885 cur.clearSelection();
1886 dr.setMessage(from_utf8(N_("Mark off")));
1890 cur.clearSelection();
1892 dr.setMessage(from_utf8(N_("Mark on")));
1895 case LFUN_MARK_TOGGLE:
1896 cur.selection(false);
1899 dr.setMessage(from_utf8(N_("Mark removed")));
1902 dr.setMessage(from_utf8(N_("Mark set")));
1907 case LFUN_SCREEN_SHOW_CURSOR:
1911 case LFUN_SCREEN_RECENTER:
1915 case LFUN_BIBTEX_DATABASE_ADD: {
1916 Cursor tmpcur = cur;
1917 findInset(tmpcur, { BIBTEX_CODE }, false);
1918 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1921 if (inset->addDatabase(cmd.argument()))
1922 dr.forceBufferUpdate();
1927 case LFUN_BIBTEX_DATABASE_DEL: {
1928 Cursor tmpcur = cur;
1929 findInset(tmpcur, { BIBTEX_CODE }, false);
1930 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1933 if (inset->delDatabase(cmd.argument()))
1934 dr.forceBufferUpdate();
1939 case LFUN_GRAPHICS_UNIFY: {
1941 cur.recordUndoFullBuffer();
1943 DocIterator from, to;
1944 from = cur.selectionBegin();
1945 to = cur.selectionEnd();
1947 string const newId = cmd.getArg(0);
1948 bool fetchId = newId.empty(); //if we wait for groupId from first graphics inset
1950 InsetGraphicsParams grp_par;
1952 InsetGraphics::string2params(graphics::getGroupParams(buffer_, newId), buffer_, grp_par);
1954 if (!from.nextInset()) //move to closest inset
1955 from.forwardInset();
1957 while (!from.empty() && from < to) {
1958 Inset * inset = from.nextInset();
1961 InsetGraphics * ig = inset->asInsetGraphics();
1963 InsetGraphicsParams inspar = ig->getParams();
1968 grp_par.filename = inspar.filename;
1969 ig->setParams(grp_par);
1972 from.forwardInset();
1974 dr.screenUpdate(Update::Force); //needed if triggered from context menu
1978 case LFUN_BIBTEX_DATABASE_LIST: {
1979 docstring_list const & files = buffer_.getBibfiles();
1982 char const separator(os::path_separator());
1983 for (auto const & file : files) {
1987 result += separator;
1989 FileName const fn = buffer_.getBibfilePath(file);
1990 string const path = fn.realPath();
1991 result += from_utf8(os::external_path(path));
1993 dr.setMessage(result);
1997 case LFUN_STATISTICS: {
1998 DocIterator from, to;
1999 if (cur.selection()) {
2000 from = cur.selectionBegin();
2001 to = cur.selectionEnd();
2003 from = doc_iterator_begin(&buffer_);
2004 to = doc_iterator_end(&buffer_);
2006 buffer_.updateStatistics(from, to);
2007 int const words = buffer_.wordCount();
2008 int const chars = buffer_.charCount(false);
2009 int const chars_blanks = buffer_.charCount(true);
2011 if (cur.selection())
2012 message = _("Statistics for the selection:");
2014 message = _("Statistics for the document:");
2017 message += bformat(_("%1$d words"), words);
2019 message += _("One word");
2021 if (chars_blanks != 1)
2022 message += bformat(_("%1$d characters"), chars_blanks);
2024 message += _("One character");
2027 message += bformat(_("%1$d characters (no blanks)"), chars);
2029 message += _("One character (no blanks)");
2031 Alert::information(_("Statistics"), message);
2035 case LFUN_STATISTICS_REFERENCE_CLAMP: {
2036 d->stats_update_trigger_ = true;
2037 if (cmd.argument() == "reset") {
2038 d->stats_ref_value_w_ = d->stats_ref_value_c_ = d->stats_ref_value_nb_ = 0;
2042 DocIterator from, to;
2043 from = doc_iterator_begin(&buffer_);
2044 to = doc_iterator_end(&buffer_);
2045 buffer_.updateStatistics(from, to);
2047 d->stats_ref_value_w_ = buffer_.wordCount();
2048 d->stats_ref_value_c_ = buffer_.charCount(true);
2049 d->stats_ref_value_nb_ = buffer_.charCount(false);
2054 case LFUN_SCREEN_UP:
2055 case LFUN_SCREEN_DOWN: {
2056 Point p = getPos(cur);
2057 // This code has been commented out to enable to scroll down a
2058 // document, even if there are large insets in it (see bug #5465).
2059 /*if (p.y_ < 0 || p.y_ > height_) {
2060 // The cursor is off-screen so recenter before proceeding.
2064 int const scrolled = scroll(act == LFUN_SCREEN_UP
2065 ? -height_ : height_);
2066 if (act == LFUN_SCREEN_UP && scrolled > -height_)
2068 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
2069 p = Point(width_, height_);
2070 bool const in_texted = cur.inTexted();
2071 cur.setCursor(doc_iterator_begin(cur.buffer()));
2072 cur.selHandle(false);
2073 // Force an immediate computation of metrics because we need it below
2075 processUpdateFlags(Update::Force);
2077 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
2078 true, act == LFUN_SCREEN_UP);
2079 //FIXME: what to do with cur.x_target()?
2080 bool update = in_texted && cur.bv().checkDepm(cur, old);
2083 if (update || cur.mark())
2084 dr.screenUpdate(Update::Force | Update::FitCursor);
2086 dr.forceBufferUpdate();
2091 string const scroll_type = cmd.getArg(0);
2092 int scroll_step = 0;
2093 if (scroll_type == "line")
2094 scroll_step = d->scrollbarParameters_.single_step;
2095 else if (scroll_type == "page")
2096 scroll_step = d->scrollbarParameters_.page_step;
2099 string const scroll_quantity = cmd.getArg(1);
2100 if (scroll_quantity == "up")
2101 scrollUp(scroll_step);
2102 else if (scroll_quantity == "down")
2103 scrollDown(scroll_step);
2105 int const scroll_value = convert<int>(scroll_quantity);
2107 scroll(scroll_step * scroll_value);
2109 dr.screenUpdate(Update::ForceDraw);
2110 dr.forceBufferUpdate();
2114 case LFUN_SCREEN_UP_SELECT: {
2115 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
2116 cur.selHandle(true);
2117 if (isTopScreen()) {
2118 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
2122 int y = getPos(cur).y_;
2123 int const ymin = y - height_ + defaultRowHeight();
2124 while (y > ymin && cur.up())
2128 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
2132 case LFUN_SCREEN_DOWN_SELECT: {
2133 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
2134 cur.selHandle(true);
2135 if (isBottomScreen()) {
2136 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
2140 int y = getPos(cur).y_;
2141 int const ymax = y + height_ - defaultRowHeight();
2142 while (y < ymax && cur.down())
2146 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
2151 case LFUN_INSET_SELECT_ALL: {
2152 // true if all cells are selected
2153 bool const all_selected = cur.depth() > 1
2154 && cur.selBegin().at_begin()
2155 && cur.selEnd().at_end();
2156 // true if some cells are selected
2157 bool const cells_selected = cur.depth() > 1
2158 && cur.selBegin().at_cell_begin()
2159 && cur.selEnd().at_cell_end();
2160 if (all_selected || (cells_selected && !cur.inset().isTable())) {
2161 // All the contents of the inset if selected, or only at
2162 // least one cell but inset is not a table.
2163 // Select the inset from outside.
2166 cur.selection(true);
2168 } else if (cells_selected) {
2169 // At least one complete cell is selected and inset is a table.
2175 cur.selection(true);
2176 cur.idx() = cur.lastidx();
2177 cur.pit() = cur.lastpit();
2178 cur.pos() = cur.lastpos();
2180 // select current cell
2184 cur.selection(true);
2185 cur.pit() = cur.lastpit();
2186 cur.pos() = cur.lastpos();
2188 cur.setCurrentFont();
2189 dr.screenUpdate(Update::Force);
2194 case LFUN_UNICODE_INSERT: {
2195 if (cmd.argument().empty())
2198 FuncCode code = cur.inset().currentMode() == Inset::MATH_MODE ?
2199 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
2202 docstring const arg = from_utf8(cmd.getArg(i));
2206 LYXERR0("Not a hexstring: " << arg);
2210 char_type c = hexToInt(arg);
2211 if (c >= 32 && c < 0x10ffff) {
2212 LYXERR(Debug::KEY, "Inserting c: " << c);
2213 lyx::dispatch(FuncRequest(code, docstring(1, c)));
2221 // This would be in Buffer class if only Cursor did not
2222 // require a bufferview
2223 case LFUN_INSET_FORALL: {
2224 docstring const name = from_utf8(cmd.getArg(0));
2225 string const commandstr = cmd.getLongArg(1);
2226 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
2228 // an arbitrary number to limit number of iterations
2229 const int max_iter = 100000;
2231 Cursor & bvcur = d->cursor_;
2232 Cursor const savecur = bvcur;
2234 if (!bvcur.nextInset())
2235 bvcur.forwardInset();
2236 bvcur.beginUndoGroup();
2237 while(bvcur && iterations < max_iter) {
2238 Inset * const ins = bvcur.nextInset();
2241 docstring insname = ins->layoutName();
2242 while (!insname.empty()) {
2243 if (insname == name || name == from_utf8("*")) {
2244 lyx::dispatch(fr, dr);
2245 // we do not want to remember selection here
2246 bvcur.clearSelection();
2250 size_t const i = insname.rfind(':');
2251 if (i == string::npos)
2253 insname = insname.substr(0, i);
2255 // if we did not delete the inset, skip it
2256 if (!bvcur.nextInset() || bvcur.nextInset() == ins)
2257 bvcur.forwardInset();
2260 bvcur.fixIfBroken();
2261 /** This is a dummy undo record only to remember the cursor
2262 * that has just been set; this will be used on a redo action
2263 * (see ticket #10097)
2265 * FIXME: a better fix would be to have a way to set the
2266 * cursor value directly, but I am not sure it is worth it.
2269 bvcur.endUndoGroup();
2270 dr.screenUpdate(Update::Force);
2271 dr.forceBufferUpdate();
2273 if (iterations >= max_iter) {
2275 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
2277 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
2282 case LFUN_BRANCH_ADD_INSERT: {
2283 docstring branch_name = from_utf8(cmd.getArg(0));
2284 if (branch_name.empty())
2285 if (!Alert::askForText(branch_name, _("Branch name")) ||
2286 branch_name.empty())
2289 DispatchResult drtmp;
2290 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
2291 if (drtmp.error()) {
2292 Alert::warning(_("Branch already exists"), drtmp.message());
2295 docstring const sep = buffer_.params().branchlist().separator();
2296 for (docstring const & branch : getVectorFromString(branch_name, sep))
2297 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch));
2301 case LFUN_KEYMAP_OFF:
2302 getIntl().keyMapOn(false);
2305 case LFUN_KEYMAP_PRIMARY:
2306 getIntl().keyMapPrim();
2309 case LFUN_KEYMAP_SECONDARY:
2310 getIntl().keyMapSec();
2313 case LFUN_KEYMAP_TOGGLE:
2314 getIntl().toggleKeyMap();
2317 case LFUN_DIALOG_SHOW_NEW_INSET: {
2318 string const name = cmd.getArg(0);
2319 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2320 if (decodeInsetParam(name, data, buffer_))
2321 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
2323 lyxerr << "Inset type '" << name <<
2324 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
2328 case LFUN_CITATION_INSERT: {
2329 if (argument.empty()) {
2330 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
2333 // we can have one optional argument, delimited by '|'
2334 // citation-insert <key>|<text_before>
2335 // this should be enhanced to also support text_after
2336 // and citation style
2337 string arg = argument;
2339 if (contains(argument, "|")) {
2340 arg = token(argument, '|', 0);
2341 opt1 = token(argument, '|', 1);
2344 // if our cursor is directly in front of or behind a citation inset,
2345 // we will instead add the new key to it.
2346 Inset * inset = cur.nextInset();
2347 if (!inset || inset->lyxCode() != CITE_CODE)
2348 inset = cur.prevInset();
2349 if (inset && inset->lyxCode() == CITE_CODE) {
2350 InsetCitation * icite = static_cast<InsetCitation *>(inset);
2351 if (icite->addKey(arg)) {
2352 dr.forceBufferUpdate();
2353 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
2355 LYXERR0("Discarding optional argument to citation-insert.");
2360 InsetCommandParams icp(CITE_CODE);
2361 icp["key"] = from_utf8(arg);
2363 icp["before"] = from_utf8(opt1);
2365 from_ascii(InsetCitation::last_literal ? "true" : "false");
2366 string icstr = InsetCommand::params2string(icp);
2367 FuncRequest fr(LFUN_INSET_INSERT, icstr);
2370 // if the request comes from the LyX server, then we
2371 // return a list of the undefined keys, in case some
2372 // action could be taken.
2373 if (cmd.origin() != FuncRequest::LYXSERVER)
2376 vector<docstring> keys = getVectorFromString(from_utf8(arg));
2377 vector<docstring>::iterator it = keys.begin();
2378 vector<docstring>::const_iterator end = keys.end();
2380 BiblioInfo const & bibInfo = buffer_.masterBibInfo();
2381 const BiblioInfo::const_iterator bibEnd = bibInfo.end();
2383 if (bibInfo.find(*it) != bibEnd) {
2384 it = keys.erase(it);
2389 dr.setMessage(getStringFromVector(keys));
2394 case LFUN_INSET_APPLY: {
2395 string const name = cmd.getArg(0);
2396 Inset * inset = editedInset(name);
2398 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2402 // put cursor in front of inset.
2403 if (!setCursorFromInset(inset)) {
2404 LASSERT(false, break);
2407 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2408 inset->dispatch(cur, fr);
2409 dr.screenUpdate(cur.result().screenUpdate());
2410 if (cur.result().needBufferUpdate())
2411 dr.forceBufferUpdate();
2416 // The change of language of buffer belongs to the Buffer class.
2417 // We have to do it here because we need a cursor for Undo.
2418 // When Undo::recordUndoBufferParams() is implemented someday
2419 // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
2420 case LFUN_BUFFER_LANGUAGE: {
2421 Language const * oldL = buffer_.params().language;
2422 Language const * newL = languages.getLanguage(argument);
2423 if (!newL || oldL == newL)
2425 if (oldL->rightToLeft() == newL->rightToLeft()) {
2426 cur.recordUndoFullBuffer();
2427 buffer_.changeLanguage(oldL, newL);
2428 cur.setCurrentFont();
2429 dr.forceBufferUpdate();
2434 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2435 case LFUN_FILE_INSERT_PLAINTEXT: {
2436 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
2437 string const fname = to_utf8(cmd.argument());
2438 if (!FileName::isAbsolute(fname))
2439 dr.setMessage(_("Absolute filename expected."));
2441 insertPlaintextFile(FileName(fname), as_paragraph);
2446 // With multi-cell table content, we pass down to the inset
2447 if (cur.inTexted() && cur.selection()
2448 && cur.selectionBegin().idx() != cur.selectionEnd().idx()) {
2449 buffer_.dispatch(cmd, dr);
2450 dispatched = dr.dispatched();
2453 cap::copySelection(cur);
2454 cur.message(_("Copy"));
2458 // OK, so try the Buffer itself...
2459 buffer_.dispatch(cmd, dr);
2460 dispatched = dr.dispatched();
2464 buffer_.undo().endUndoGroup();
2465 dr.dispatched(dispatched);
2467 // NOTE: The code below is copied from Cursor::dispatch. If you
2468 // need to modify this, please update the other one too.
2470 // notify insets we just entered/left
2471 if (cursor() != old) {
2472 old.beginUndoGroup();
2474 bool badcursor = notifyCursorLeavesOrEnters(old, cursor());
2476 cursor().fixIfBroken();
2477 resetInlineCompletionPos();
2484 docstring BufferView::requestSelection()
2486 Cursor & cur = d->cursor_;
2488 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2489 if (!cur.selection()) {
2490 d->xsel_cache_.set = false;
2494 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2495 if (!d->xsel_cache_.set ||
2496 cur.top() != d->xsel_cache_.cursor ||
2497 cur.realAnchor().top() != d->xsel_cache_.anchor)
2499 d->xsel_cache_.cursor = cur.top();
2500 d->xsel_cache_.anchor = cur.realAnchor().top();
2501 d->xsel_cache_.set = cur.selection();
2502 return cur.selectionAsString(false);
2508 void BufferView::clearSelection()
2510 d->cursor_.clearSelection();
2511 // Clear the selection buffer. Otherwise a subsequent
2512 // middle-mouse-button paste would use the selection buffer,
2513 // not the more current external selection.
2514 cap::clearSelection();
2515 d->xsel_cache_.set = false;
2516 // The buffer did not really change, but this causes the
2517 // redraw we need because we cleared the selection above.
2518 buffer_.changed(false);
2522 void BufferView::resize(int width, int height)
2525 // Update metrics only if width has changed
2526 if (width != width_) {
2529 // Clear the paragraph height cache.
2530 d->par_height_.clear();
2531 // Redo the metrics.
2532 updateMetrics(true);
2534 // metrics is OK, full drawing is necessary now
2535 d->update_flags_ = (d->update_flags_ & ~Update::Force) | Update::ForceDraw;
2536 d->update_strategy_ = FullScreenUpdate;
2540 Inset const * BufferView::getCoveringInset(Text const & text,
2543 TextMetrics & tm = d->text_metrics_[&text];
2544 Inset * inset = tm.checkInsetHit(x, y);
2548 if (!inset->descendable(*this))
2549 // No need to go further down if the inset is not
2553 size_t cell_number = inset->nargs();
2554 // Check all the inner cell.
2555 for (size_t i = 0; i != cell_number; ++i) {
2556 Text const * inner_text = inset->getText(i);
2559 Inset const * inset_deeper =
2560 getCoveringInset(*inner_text, x, y);
2562 return inset_deeper;
2570 Inset const * BufferView::clickableMathInset(InsetMathNest const * inset,
2571 CoordCache::Insets const & inset_cache, int x, int y) const
2573 for (size_t i = 0; i < inset->nargs(); ++i) {
2574 MathData const & ar = inset->cell(i);
2575 for (size_t j = 0; j < ar.size(); ++j) {
2576 string const name = lyxerr.debugging(Debug::MATHED)
2577 ? insetName(ar[j].nucleus()->lyxCode())
2579 LYXERR(Debug::MATHED, "Checking inset: " << name);
2580 if (ar[j].nucleus()->clickable(*this, x, y)) {
2581 if (inset_cache.covers(ar[j].nucleus(), x, y)) {
2582 LYXERR(Debug::MATHED, "Clickable inset: "
2584 return ar[j].nucleus();
2587 InsetMathNest const * imn =
2588 ar[j].nucleus()->asNestInset();
2590 Inset const * inner =
2591 clickableMathInset(imn, inset_cache, x, y);
2601 void BufferView::updateHoveredInset() const
2603 // Get inset under mouse, if there is one.
2604 int const x = d->mouse_position_cache_.x_;
2605 int const y = d->mouse_position_cache_.y_;
2606 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2607 if (covering_inset && covering_inset->asInsetMath()) {
2608 Inset const * inner_inset = clickableMathInset(
2609 covering_inset->asInsetMath()->asNestInset(),
2610 coordCache().getInsets(), x, y);
2612 covering_inset = inner_inset;
2615 d->clickable_inset_ = covering_inset && covering_inset->clickable(*this, x, y);
2617 if (covering_inset == d->last_inset_)
2618 // Same inset, no need to do anything...
2621 bool need_redraw = false;
2622 if (d->last_inset_) {
2623 // Remove the hint on the last hovered inset (if any).
2624 need_redraw |= d->last_inset_->setMouseHover(this, false);
2625 d->last_inset_ = nullptr;
2628 if (covering_inset && covering_inset->setMouseHover(this, true)) {
2630 // Only the insets that accept the hover state, do
2631 // clear the last_inset_, so only set the last_inset_
2632 // member if the hovered setting is accepted.
2633 d->last_inset_ = covering_inset;
2637 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2638 << d->mouse_position_cache_.x_ << ", "
2639 << d->mouse_position_cache_.y_ << ")");
2641 d->update_strategy_ = DecorationUpdate;
2643 // This event (moving without mouse click) is not passed further.
2644 // This should be changed if it is further utilized.
2645 buffer_.changed(false);
2650 void BufferView::clearLastInset(Inset * inset) const
2652 if (d->last_inset_ != inset) {
2653 LYXERR0("Wrong last_inset!");
2656 d->last_inset_ = nullptr;
2660 bool BufferView::mouseSelecting() const
2662 return d->mouse_selecting_;
2666 int BufferView::stats_ref_value_w() const
2668 return d->stats_ref_value_w_;
2672 int BufferView::stats_ref_value_c() const
2674 return d->stats_ref_value_c_;
2678 int BufferView::stats_ref_value_nb() const
2680 return d->stats_ref_value_nb_;
2684 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2686 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2691 // This is only called for mouse related events including
2692 // LFUN_FILE_OPEN generated by drag-and-drop.
2693 FuncRequest cmd = cmd0;
2695 // Either the inset under the cursor or the
2696 // surrounding Text will handle this event.
2698 // make sure we stay within the screen...
2699 cmd.set_y(min(max(cmd.y(), -1), height_));
2701 d->mouse_position_cache_.x_ = cmd.x();
2702 d->mouse_position_cache_.y_ = cmd.y();
2704 d->mouse_selecting_ =
2705 cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::button1;
2707 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2708 updateHoveredInset();
2712 Cursor old = cursor();
2714 cur.push(buffer_.inset());
2715 cur.selection(d->cursor_.selection());
2717 // Build temporary cursor.
2718 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2720 // If inset is not editable, cur.pos() might point behind the
2721 // inset (depending on cmd.x(), cmd.y()). This is needed for
2722 // editing to fix bug 9628, but e.g. the context menu needs a
2723 // cursor in front of the inset.
2724 if ((inset->hasSettings() || !inset->contextMenuName().empty()
2725 || inset->lyxCode() == SEPARATOR_CODE) &&
2726 cur.nextInset() != inset && cur.prevInset() == inset)
2728 } else if (cur.inTexted() && cur.pos()
2729 && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
2730 // Always place cursor in front of a separator inset.
2734 // Put anchor at the same position.
2737 old.beginUndoGroup();
2739 // Try to dispatch to an non-editable inset near this position
2740 // via the temp cursor. If the inset wishes to change the real
2741 // cursor it has to do so explicitly by using
2742 // cur.bv().cursor() = cur; (or similar)
2744 inset->dispatch(cur, cmd);
2746 // Now dispatch to the temporary cursor. If the real cursor should
2747 // be modified, the inset's dispatch has to do so explicitly.
2748 if (!inset || !cur.result().dispatched())
2751 // Notify left insets
2753 bool badcursor = old.fixIfBroken() || cur.fixIfBroken();
2754 badcursor = badcursor || notifyCursorLeavesOrEnters(old, cur);
2756 cursor().fixIfBroken();
2761 // Do we have a selection?
2762 theSelection().haveSelection(cursor().selection());
2764 if (cur.needBufferUpdate() || buffer().needUpdate()) {
2765 cur.clearBufferUpdate();
2766 buffer().updateBuffer();
2769 // If the command has been dispatched,
2770 if (cur.result().dispatched() || cur.result().screenUpdate())
2771 processUpdateFlags(cur.result().screenUpdate());
2775 int BufferView::minVisiblePart()
2777 return 2 * defaultRowHeight();
2781 int BufferView::scroll(int pixels)
2784 return scrollDown(pixels);
2786 return scrollUp(-pixels);
2791 int BufferView::scrollDown(int pixels)
2793 Text * text = &buffer_.text();
2794 TextMetrics & tm = d->text_metrics_[text];
2795 int const ymax = height_ + pixels;
2797 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2798 int bottom_pos = last.second->bottom();
2799 if (lyxrc.scroll_below_document)
2800 bottom_pos += height_ - minVisiblePart();
2801 if (last.first + 1 == int(text->paragraphs().size())) {
2802 if (bottom_pos <= height_)
2804 pixels = min(pixels, bottom_pos - height_);
2807 if (bottom_pos > ymax)
2809 tm.newParMetricsDown();
2811 d->anchor_ypos_ -= pixels;
2816 int BufferView::scrollUp(int pixels)
2818 Text * text = &buffer_.text();
2819 TextMetrics & tm = d->text_metrics_[text];
2820 int ymin = - pixels;
2822 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2823 int top_pos = first.second->top();
2824 if (first.first == 0) {
2827 pixels = min(pixels, - top_pos);
2832 tm.newParMetricsUp();
2834 d->anchor_ypos_ += pixels;
2839 bool BufferView::setCursorFromRow(int row)
2841 TexRow::TextEntry start, end;
2842 tie(start,end) = buffer_.texrow().getEntriesFromRow(row);
2843 LYXERR(Debug::OUTFILE,
2844 "setCursorFromRow: for row " << row << ", TexRow has found "
2845 "start (id=" << start.id << ",pos=" << start.pos << "), "
2846 "end (id=" << end.id << ",pos=" << end.pos << ")");
2847 return setCursorFromEntries(start, end);
2851 bool BufferView::setCursorFromEntries(TexRow::TextEntry start,
2852 TexRow::TextEntry end)
2854 DocIterator dit_start, dit_end;
2855 tie(dit_start,dit_end) =
2856 TexRow::getDocIteratorsFromEntries(start, end, buffer_);
2859 // Setting selection start
2860 d->cursor_.clearSelection();
2861 setCursor(dit_start);
2862 // Setting selection end
2864 d->cursor_.resetAnchor();
2865 setCursorSelectionTo(dit_end);
2871 bool BufferView::setCursorFromInset(Inset const * inset)
2873 // are we already there?
2874 if (cursor().nextInset() == inset)
2877 // Inset is not at cursor position. Find it in the document.
2880 while (cur && cur.nextInset() != inset)
2891 void BufferView::gotoLabel(docstring const & label)
2894 bool have_inactive = false;
2895 for (Buffer const * buf : buffer().allRelatives()) {
2897 for (TocItem const & item : *buf->tocBackend().toc("label")) {
2898 if (label == item.str() && item.isOutput()) {
2899 lyx::dispatch(item.action());
2902 // If we find an inactive label, save it for the case
2903 // that no active one is there
2904 if (label == item.str() && !have_inactive) {
2905 have_inactive = true;
2906 action = item.action();
2910 // We only found an inactive label. Go there.
2912 lyx::dispatch(action);
2916 TextMetrics const & BufferView::textMetrics(Text const * t) const
2918 return const_cast<BufferView *>(this)->textMetrics(t);
2922 TextMetrics & BufferView::textMetrics(Text const * t)
2925 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2926 if (tmc_it == d->text_metrics_.end()) {
2927 tmc_it = d->text_metrics_.emplace(std::piecewise_construct,
2928 std::forward_as_tuple(t),
2929 std::forward_as_tuple(this, const_cast<Text *>(t))).first;
2931 return tmc_it->second;
2935 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2938 return textMetrics(t).parMetrics(pit);
2942 int BufferView::workHeight() const
2948 void BufferView::setCursor(DocIterator const & dit)
2951 size_t const n = dit.depth();
2952 for (size_t i = 0; i < n; ++i)
2953 dit[i].inset().edit(d->cursor_, true);
2955 d->cursor_.setCursor(dit);
2956 d->cursor_.selection(false);
2957 d->cursor_.setCurrentFont();
2959 // It seems on general grounds as if this is probably needed, but
2960 // it is not yet clear.
2961 // See bug #7394 and r38388.
2962 // d->cursor.resetAnchor();
2966 void BufferView::setCursorSelectionTo(DocIterator const & dit)
2968 size_t const n = dit.depth();
2969 for (size_t i = 0; i < n; ++i)
2970 dit[i].inset().edit(d->cursor_, true);
2972 d->cursor_.selection(true);
2973 d->cursor_.setCursorSelectionTo(dit);
2974 d->cursor_.setCurrentFont();
2978 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2980 // Would be wrong to delete anything if we have a selection.
2981 if (cur.selection())
2984 bool need_anchor_change = false;
2985 bool changed = Text::deleteEmptyParagraphMechanism(cur, old,
2986 need_anchor_change);
2988 if (need_anchor_change)
2996 // we would rather not do this here, but it needs to be done before
2997 // the changed() signal is sent.
2998 buffer_.updateBuffer();
3000 buffer_.changed(true);
3005 bool BufferView::mouseSetCursor(Cursor & cur, bool const select)
3007 LASSERT(&cur.bv() == this, return false);
3010 // this event will clear selection so we save selection for
3011 // persistent selection
3012 cap::saveSelection(cursor());
3014 d->cursor_.macroModeClose();
3015 // If a macro has been finalized, the cursor might have been broken
3018 // Has the cursor just left the inset?
3019 bool const leftinset = (&d->cursor_.inset() != &cur.inset());
3021 d->cursor_.fixIfBroken();
3023 // do the dEPM magic if needed
3024 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
3025 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
3026 // the leftinset bool would not be necessary (badcursor instead).
3027 bool update = leftinset;
3030 d->cursor_.setSelection();
3031 d->cursor_.setCursorSelectionTo(cur);
3033 if (d->cursor_.inTexted())
3034 update |= checkDepm(cur, d->cursor_);
3035 d->cursor_.resetAnchor();
3036 d->cursor_.setCursor(cur);
3037 d->cursor_.clearSelection();
3039 d->cursor_.boundary(cur.boundary());
3040 d->cursor_.finishUndo();
3041 d->cursor_.setCurrentFont();
3043 cur.forceBufferUpdate();
3048 void BufferView::putSelectionAt(DocIterator const & cur,
3049 int length, bool backwards)
3051 d->cursor_.clearSelection();
3057 d->cursor_.pos() += length;
3058 d->cursor_.setSelection(d->cursor_, -length);
3060 d->cursor_.setSelection(d->cursor_, length);
3065 void BufferView::setSelection(DocIterator const & from,
3066 DocIterator const & to)
3068 if (from.pit() != to.pit()) {
3069 // there are multiple paragraphs in selection
3070 cursor().setCursor(from);
3071 cursor().clearSelection();
3072 cursor().selection(true);
3073 cursor().setCursor(to);
3074 cursor().selection(true);
3076 // only single paragraph
3077 int const size = to.pos() - from.pos();
3078 putSelectionAt(from, size, false);
3080 processUpdateFlags(Update::Force | Update::FitCursor);
3084 bool BufferView::selectIfEmpty(DocIterator & cur)
3086 if ((cur.inTexted() && !cur.paragraph().empty())
3087 || (cur.inMathed() && !cur.cell().empty()))
3090 pit_type const beg_pit = cur.pit();
3092 // The paragraph associated to this item isn't
3093 // the first one, so it can be selected
3096 // We have to resort to select the space between the
3097 // end of this item and the begin of the next one
3101 // If it is the only item in the document,
3102 // nothing can be selected
3105 pit_type const end_pit = cur.pit();
3106 pos_type const end_pos = cur.pos();
3107 d->cursor_.clearSelection();
3109 d->cursor_.setCursor(cur);
3110 d->cursor_.pit() = beg_pit;
3111 d->cursor_.pos() = 0;
3112 d->cursor_.selection(false);
3113 d->cursor_.resetAnchor();
3114 d->cursor_.pit() = end_pit;
3115 d->cursor_.pos() = end_pos;
3116 d->cursor_.setSelection();
3121 Cursor & BufferView::cursor()
3127 Cursor const & BufferView::cursor() const
3133 bool BufferView::singleParUpdate()
3135 CursorSlice const & its = d->cursor_.innerTextSlice();
3136 pit_type const pit = its.pit();
3137 TextMetrics & tm = textMetrics(its.text());
3138 Dimension const old_dim = tm.parMetrics(pit).dim();
3140 // make sure inline completion pointer is ok
3141 if (d->inlineCompletionPos_.fixIfBroken())
3142 d->inlineCompletionPos_ = DocIterator();
3144 /* Try to rebreak only the paragraph containing the cursor (if
3145 * this paragraph contains insets etc., rebreaking will
3146 * recursively descend). We need a full redraw if either
3147 * 1/ the height has changed
3149 * 2/ the width has changed and it was equal to the textmetrics
3150 * width; the goal is to catch the case of a one-row inset that
3151 * grows with its contents, but optimize the case of typing at
3152 * the end of a mmultiple-row paragraph.
3154 * NOTE: if only the height has changed, then it should be
3155 * possible to update all metrics at minimal cost. However,
3156 * since this is risky, we do not try that right now.
3158 tm.redoParagraph(pit);
3159 ParagraphMetrics & pm = tm.parMetrics(pit);
3160 if (pm.height() != old_dim.height()
3161 || (pm.width() != old_dim.width() && old_dim.width() == tm.width())) {
3162 // Paragraph height or width has changed so we cannot proceed
3163 // to the singlePar optimisation.
3164 LYXERR(Debug::PAINTING, "SinglePar optimization failed.");
3167 // Since position() points to the baseline of the first row, we
3168 // may have to update it. See ticket #11601 for an example where
3169 // the height does not change but the ascent does.
3170 pm.setPosition(pm.position() - old_dim.ascent() + pm.ascent());
3172 tm.updatePosCache(pit);
3174 LYXERR(Debug::PAINTING, "\ny1: " << pm.top() << " y2: " << pm.bottom()
3175 << " pit: " << pit << " singlepar: 1");
3180 void BufferView::updateMetrics()
3182 updateMetrics(true);
3183 // metrics is done, full drawing is necessary now
3184 d->update_flags_ = (d->update_flags_ & ~Update::Force) | Update::ForceDraw;
3185 d->update_strategy_ = FullScreenUpdate;
3189 void BufferView::updateMetrics(bool force)
3194 //LYXERR0("updateMetrics " << _v_(force));
3196 Text & buftext = buffer_.text();
3197 pit_type const lastpit = int(buftext.paragraphs().size()) - 1;
3200 // Clear out the position cache in case of full screen redraw,
3201 d->coord_cache_.clear();
3202 d->math_rows_.clear();
3204 // Clear out paragraph metrics to avoid having invalid metrics
3205 // in the cache from paragraphs not relayouted below. The
3206 // complete text metrics will be redone.
3207 d->text_metrics_.clear();
3210 TextMetrics & tm = textMetrics(&buftext);
3212 // make sure inline completion pointer is ok
3213 if (d->inlineCompletionPos_.fixIfBroken())
3214 d->inlineCompletionPos_ = DocIterator();
3216 if (d->anchor_pit_ > lastpit)
3217 // The anchor pit must have been deleted...
3218 d->anchor_pit_ = lastpit;
3220 // Update metrics around the anchor
3221 tm.updateMetrics(d->anchor_pit_, d->anchor_ypos_, height_);
3223 // Check that the end of the document is not too high
3224 int const min_visible = lyxrc.scroll_below_document ? minVisiblePart() : height_;
3225 if (tm.last().first == lastpit && tm.last().second->bottom() < min_visible) {
3226 d->anchor_ypos_ += min_visible - tm.last().second->bottom();
3227 LYXERR(Debug::SCROLLING, "Too high, adjusting anchor ypos to " << d->anchor_ypos_);
3228 tm.updateMetrics(d->anchor_pit_, d->anchor_ypos_, height_);
3231 // Check that the start of the document is not too low
3232 if (tm.first().first == 0 && tm.first().second->top() > 0) {
3233 d->anchor_ypos_ -= tm.first().second->top();
3234 LYXERR(Debug::SCROLLING, "Too low, adjusting anchor ypos to " << d->anchor_ypos_);
3235 tm.updateMetrics(d->anchor_pit_, d->anchor_ypos_, height_);
3238 /* FIXME: do we want that? It avoids potential issues with old
3239 * paragraphs that should have been recomputed but have not, at
3240 * the price of potential extra metrics computaiton. I do not
3241 * think that the performance gain is high, so that for now the
3242 * extra paragraphs are removed
3244 // Remove paragraphs that are outside of screen
3245 while(tm.first().second->bottom() <= 0) {
3246 //LYXERR0("Forget pit: " << tm.first().first);
3247 tm.forget(tm.first().first);
3249 while(tm.last().second->top() > height_) {
3250 //LYXERR0("Forget pit: " << tm.first().first);
3251 tm.forget(tm.last().first);
3254 /* FIXME: if paragraphs outside of the screen are not removed
3255 * above, one has to search for the first visible one here */
3256 // Normalize anchor for next time
3257 if (d->anchor_pit_ != tm.first().first
3258 || d->anchor_ypos_ != tm.first().second->position()) {
3259 LYXERR(Debug::PAINTING, __func__ << ": Found new anchor pit = " << tm.first().first
3260 << " anchor ypos = " << tm.first().second->position()
3261 << " (was " << d->anchor_pit_ << ", " << d->anchor_ypos_ << ")");
3262 d->anchor_pit_ = tm.first().first;
3263 d->anchor_ypos_ = tm.first().second->position();
3266 // Now update the positions of insets in the cache.
3269 if (lyxerr.debugging(Debug::WORKAREA)) {
3270 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
3271 d->coord_cache_.dump();
3276 void BufferView::updatePosCache()
3278 // this is the "nodraw" drawing stage: only set the positions of the
3279 // insets in metrics cache.
3280 frontend::NullPainter np;
3285 void BufferView::insertLyXFile(FileName const & fname, bool const ignorelang)
3287 LASSERT(d->cursor_.inTexted(), return);
3289 // Get absolute path of file and add ".lyx"
3290 // to the filename if necessary
3291 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
3293 docstring const disp_fn = makeDisplayPath(filename.absFileName());
3294 // emit message signal.
3295 message(bformat(_("Inserting document %1$s..."), disp_fn));
3298 Buffer buf(filename.absFileName(), false);
3299 if (buf.loadLyXFile() == Buffer::ReadSuccess) {
3300 ErrorList & el = buffer_.errorList("Parse");
3301 // Copy the inserted document error list into the current buffer one.
3302 el = buf.errorList("Parse");
3303 ParagraphList & pars = buf.paragraphs();
3305 // set main language of imported file to context language
3306 buf.changeLanguage(buf.language(), d->cursor_.getFont().language());
3307 buffer_.undo().recordUndo(d->cursor_);
3308 cap::replaceSelection(d->cursor_);
3309 cap::pasteParagraphList(d->cursor_, pars,
3310 buf.params().documentClassPtr(),
3311 buf.params().authors(), el);
3312 res = _("Document %1$s inserted.");
3314 res = _("Could not insert document %1$s");
3317 buffer_.changed(true);
3318 // emit message signal.
3319 message(bformat(res, disp_fn));
3323 Point BufferView::coordOffset(DocIterator const & dit) const
3329 // Addup contribution of nested insets, from inside to outside,
3330 // keeping the outer paragraph for a special handling below
3331 for (size_t i = dit.depth() - 1; i >= 1; --i) {
3332 CursorSlice const & sl = dit[i];
3336 // get relative position inside sl.inset()
3337 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
3339 // Make relative position inside of the edited inset relative to sl.inset()
3343 // In case of an RTL inset, the edited inset will be positioned to the left
3346 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
3347 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
3352 // remember width for the case that sl.inset() is positioned in an RTL inset
3353 lastw = sl.inset().dimension(*this).wid;
3355 //lyxerr << "Cursor::getPos, i: "
3356 // << i << " x: " << xx << " y: " << y << endl;
3359 // Add contribution of initial rows of outermost paragraph
3360 CursorSlice const & sl = dit[0];
3361 TextMetrics const & tm = textMetrics(sl.text());
3362 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
3364 LBUFERR(!pm.rows().empty());
3365 y -= pm.rows()[0].ascent();
3367 // FIXME: document this mess
3369 if (sl.pos() > 0 && dit.depth() == 1) {
3371 if (pos && dit.boundary())
3373 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
3374 rend = pm.pos2row(pos);
3376 rend = pm.pos2row(sl.pos());
3378 size_t rend = pm.pos2row(sl.pos());
3380 for (size_t rit = 0; rit != rend; ++rit)
3381 y += pm.rows()[rit].height();
3382 y += pm.rows()[rend].ascent();
3384 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
3386 // Make relative position from the nested inset now bufferview absolute.
3387 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
3390 // In the RTL case place the nested inset at the left of the cursor in
3391 // the outer paragraph
3392 bool boundary_1 = dit.boundary() && 1 == dit.depth();
3393 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
3401 Point BufferView::getPos(DocIterator const & dit) const
3403 if (!paragraphVisible(dit))
3404 return Point(-1, -1);
3406 CursorSlice const & bot = dit.bottom();
3407 TextMetrics const & tm = textMetrics(bot.text());
3409 // offset from outer paragraph
3410 Point p = coordOffset(dit);
3411 p.y_ += tm.parMetrics(bot.pit()).position();
3416 bool BufferView::paragraphVisible(DocIterator const & dit) const
3418 CursorSlice const & bot = dit.bottom();
3419 TextMetrics const & tm = textMetrics(bot.text());
3421 return tm.contains(bot.pit());
3425 void BufferView::caretPosAndDim(Point & p, Dimension & dim) const
3427 Cursor const & cur = cursor();
3428 if (cur.inMathed() && hasMathRow(&cur.cell())) {
3429 MathRow const & mrow = mathRow(&cur.cell());
3430 dim = mrow.caret_dim;
3432 Font const font = cur.real_current_font;
3433 frontend::FontMetrics const & fm = theFontMetrics(font);
3434 // lineWidth() can be 0 to mean 'thin line' on HiDpi, but the
3435 // caret drawing code is not prepared for that.
3436 dim.wid = max(fm.lineWidth(), 1);
3437 dim.asc = fm.maxAscent();
3438 dim.des = fm.maxDescent();
3440 if (lyxrc.cursor_width > 0)
3441 dim.wid = lyxrc.cursor_width;
3444 // center fat carets horizontally
3445 p.x_ -= dim.wid / 2;
3451 void BufferView::buildCaretGeometry(bool complet)
3455 caretPosAndDim(p, dim);
3457 Cursor const & cur = d->cursor_;
3458 Font const & realfont = cur.real_current_font;
3459 frontend::FontMetrics const & fm = theFontMetrics(realfont.fontInfo());
3460 bool const isrtl = realfont.isVisibleRightToLeft();
3461 int const dir = isrtl ? -1 : 1;
3463 frontend::CaretGeometry & cg = d->caret_geometry_;
3466 // The caret itself, slanted for italics in text edit mode except
3467 // for selections because the selection rect does not slant
3468 bool const slant = fm.italic() && cur.inTexted() && !cur.selection();
3469 double const slope = slant ? fm.italicSlope() : 0;
3470 cg.shapes.push_back(
3471 {{iround(p.x_ + dim.asc * slope), p.y_},
3472 {iround(p.x_ - dim.des * slope), p.y_ + dim.height()},
3473 {iround(p.x_ + dir * dim.wid - dim.des * slope), p.y_ + dim.height()},
3474 {iround(p.x_ + dir * dim.wid + dim.asc * slope), p.y_}}
3477 // The language indicator _| (if needed)
3478 Language const * doclang = buffer().params().language;
3479 if (!((realfont.language() == doclang && isrtl == doclang->rightToLeft())
3480 || realfont.language() == latex_language)) {
3481 int const lx = dim.height() / 3;
3482 int const xx = iround(p.x_ - dim.des * slope);
3483 int const yy = p.y_ + dim.height();
3484 cg.shapes.push_back(
3485 {{xx, yy - dim.wid},
3486 {xx + dir * (dim.wid + lx - 1), yy - dim.wid},
3487 {xx + dir * (dim.wid + lx - 1), yy},
3492 // The completion triangle |> (if needed)
3494 int const m = p.y_ + dim.height() / 2;
3495 int const d = dim.height() / 8;
3496 // offset for slanted carret
3497 int const sx = iround((dim.asc - (dim.height() / 2 - d)) * slope);
3498 // starting position x
3499 int const xx = p.x_ + dir * dim.wid + sx;
3500 cg.shapes.push_back(
3504 {xx, m + d - dim.wid},
3505 {xx + dir * d - dim.wid, m},
3506 {xx, m - d + dim.wid}}
3510 // compute extremal x values
3512 cg.right = -1000000;
3514 cg.bottom = -1000000;
3515 for (auto const & shape : cg.shapes)
3516 for (Point const & p : shape) {
3517 cg.left = min(cg.left, p.x_);
3518 cg.right = max(cg.right, p.x_);
3519 cg.top = min(cg.top, p.y_);
3520 cg.bottom = max(cg.bottom, p.y_);
3525 frontend::CaretGeometry const & BufferView::caretGeometry() const
3527 return d->caret_geometry_;
3531 bool BufferView::caretInView() const
3533 if (!paragraphVisible(cursor()))
3537 caretPosAndDim(p, dim);
3539 // does the cursor touch the screen ?
3540 if (p.y_ + dim.height() < 0 || p.y_ >= workHeight())
3546 int BufferView::horizScrollOffset() const
3548 return d->horiz_scroll_offset_;
3552 int BufferView::horizScrollOffset(Text const * text,
3553 pit_type pit, pos_type pos) const
3555 // Is this a row that is currently scrolled?
3556 if (!d->current_row_slice_.empty()
3557 && &text->inset() == d->current_row_slice_.inset().asInsetText()
3558 && pit == d->current_row_slice_.pit()
3559 && pos == d->current_row_slice_.pos())
3560 return d->horiz_scroll_offset_;
3565 void BufferView::setCurrentRowSlice(CursorSlice const & rowSlice)
3567 // nothing to do if the cursor was already on this row
3568 if (d->current_row_slice_ == rowSlice)
3571 // if the (previous) current row was scrolled, we have to
3572 // remember it in order to repaint it next time.
3573 if (d->horiz_scroll_offset_ != 0) {
3574 // search the old row in cache and mark it changed
3575 for (auto & tm_pair : d->text_metrics_) {
3576 if (&tm_pair.first->inset() == rowSlice.inset().asInsetText()) {
3577 tm_pair.second.setRowChanged(rowSlice.pit(), rowSlice.pos());
3578 // We found it, no need to continue.
3584 // Since we changed row, the scroll offset is not valid anymore
3585 d->horiz_scroll_offset_ = 0;
3586 d->current_row_slice_ = rowSlice;
3590 void BufferView::checkCursorScrollOffset()
3592 CursorSlice rowSlice = d->cursor_.bottom();
3593 TextMetrics const & tm = textMetrics(rowSlice.text());
3595 // Stop if metrics have not been computed yet, since it means
3596 // that there is nothing to do.
3597 if (!tm.contains(rowSlice.pit()))
3599 ParagraphMetrics const & pm = tm.parMetrics(rowSlice.pit());
3600 Row const & row = pm.getRow(rowSlice.pos(),
3601 d->cursor_.boundary() && rowSlice == d->cursor_.top());
3602 rowSlice.pos() = row.pos();
3604 // Set the row on which the cursor lives.
3605 setCurrentRowSlice(rowSlice);
3607 // Current x position of the cursor in pixels
3608 int cur_x = getPos(d->cursor_).x_;
3610 // Horizontal scroll offset of the cursor row in pixels
3611 int offset = d->horiz_scroll_offset_;
3612 int const MARGIN = 2 * theFontMetrics(d->cursor_.real_current_font).em()
3614 if (row.right_x() <= workWidth() - row.right_margin) {
3615 // Row is narrower than the work area, no offset needed.
3618 if (cur_x - offset < MARGIN) {
3619 // cursor would be too far right
3620 offset = cur_x - MARGIN;
3621 } else if (cur_x - offset > workWidth() - MARGIN) {
3622 // cursor would be too far left
3623 offset = cur_x - workWidth() + MARGIN;
3625 // Correct the offset to make sure that we do not scroll too much
3628 if (row.right_x() - offset < workWidth() - row.right_margin)
3629 offset = row.right_x() - workWidth() + row.right_margin;
3632 //lyxerr << "cur_x=" << cur_x << ", offset=" << offset << ", row.wid=" << row.width() << ", margin=" << MARGIN << endl;
3634 if (offset != d->horiz_scroll_offset_) {
3635 LYXERR(Debug::PAINTING, "Horiz. scroll offset changed from "
3636 << d->horiz_scroll_offset_ << " to " << offset);
3638 if (d->update_strategy_ == NoScreenUpdate)
3639 d->update_strategy_ = SingleParUpdate;
3642 d->horiz_scroll_offset_ = offset;
3646 bool BufferView::busy() const
3648 return buffer().undo().activeUndoGroup();
3652 void BufferView::draw(frontend::Painter & pain, bool paint_caret)
3656 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t--- START NODRAW ---"
3657 : "\t\t*** START DRAWING ***"));
3658 Text & text = buffer_.text();
3659 TextMetrics const & tm = d->text_metrics_[&text];
3660 int const y = tm.first().second->position();
3661 PainterInfo pi(this, pain);
3663 // Check whether the row where the cursor lives needs to be scrolled.
3664 // Update the drawing strategy if needed.
3665 checkCursorScrollOffset();
3667 switch (d->update_strategy_) {
3669 case NoScreenUpdate:
3670 // no screen painting is actually needed. In nodraw stage
3671 // however, the different coordinates of insets and paragraphs
3672 // needs to be updated.
3673 LYXERR(Debug::PAINTING, "Strategy: NoScreenUpdate");
3674 if (pain.isNull()) {
3675 pi.full_repaint = true;
3678 pi.full_repaint = false;
3683 case SingleParUpdate:
3684 pi.full_repaint = false;
3685 LYXERR(Debug::PAINTING, "Strategy: SingleParUpdate");
3686 // In general, only the current row of the outermost paragraph
3687 // will be redrawn. Particular cases where selection spans
3688 // multiple paragraph are correctly detected in TextMetrics.
3692 case DecorationUpdate:
3693 // FIXME: We should also distinguish DecorationUpdate to avoid text
3694 // drawing if possible. This is not possible to do easily right now
3695 // because of the single backing pixmap.
3697 case FullScreenUpdate:
3699 LYXERR(Debug::PAINTING,
3700 ((d->update_strategy_ == FullScreenUpdate)
3701 ? "Strategy: FullScreenUpdate"
3702 : "Strategy: DecorationUpdate"));
3704 // The whole screen, including insets, will be refreshed.
3705 pi.full_repaint = true;
3707 // Clear background.
3708 pain.fillRectangle(0, 0, width_, height_,
3709 pi.backgroundColor(&buffer_.inset()));
3717 // Possibly grey out below
3718 if (d->update_strategy_ != NoScreenUpdate) {
3719 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3720 int const y2 = lastpm.second->bottom();
3723 Color color = buffer().isInternal()
3724 ? Color_background : Color_bottomarea;
3725 pain.fillRectangle(0, y2, width_, height_ - y2, color);
3729 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t --- END NODRAW ---"
3730 : "\t\t *** END DRAWING ***"));
3732 // The scrollbar needs an update.
3733 // FIXME: does it always? see ticket #11947.
3734 updateScrollbarParameters();
3736 // Normalize anchor for next time (in case updateMetrics did not do it yet)
3737 // FIXME: is this useful?
3738 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
3739 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3740 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
3741 ParagraphMetrics const & pm = tm.parMetrics(pit);
3742 if (pm.bottom() > 0) {
3743 if (d->anchor_pit_ != pit
3744 || d->anchor_ypos_ != pm.position())
3745 LYXERR0(__func__ << ": Found new anchor pit = " << pit
3746 << " anchor ypos = " << pm.position()
3747 << " (was " << d->anchor_pit_ << ", " << d->anchor_ypos_ << ")"
3748 "\nIf you see this message, please report.");
3749 d->anchor_pit_ = pit;
3750 d->anchor_ypos_ = pm.position();
3755 if (!pain.isNull()) {
3756 // reset the update flags, everything has been done
3757 d->update_flags_ = Update::None;
3760 // If a caret has to be painted, mark its text row as dirty to
3761 //make sure that it will be repainted on next redraw.
3762 /* FIXME: investigate whether this can be avoided when the cursor did not
3766 Cursor cur(d->cursor_);
3767 while (cur.depth() > 1) {
3768 if (!cur.inTexted())
3770 TextMetrics const & tm = textMetrics(cur.text());
3771 if (d->caret_geometry_.left >= tm.origin().x_
3772 && d->caret_geometry_.right <= tm.origin().x_ + tm.dim().width())
3776 cur.textRow().changed(true);
3781 void BufferView::message(docstring const & msg)
3784 d->gui_->message(msg);
3788 void BufferView::showDialog(string const & name)
3791 d->gui_->showDialog(name, string());
3795 void BufferView::showDialog(string const & name,
3796 string const & data, Inset * inset)
3799 d->gui_->showDialog(name, data, inset);
3803 void BufferView::updateDialog(string const & name, string const & data)
3806 d->gui_->updateDialog(name, data);
3810 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
3816 // FIXME: Move this out of BufferView again
3817 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
3819 if (!fname.isReadableFile()) {
3820 docstring const error = from_ascii(strerror(errno));
3821 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3822 docstring const text =
3823 bformat(_("Could not read the specified document\n"
3824 "%1$s\ndue to the error: %2$s"), file, error);
3825 Alert::error(_("Could not read file"), text);
3829 if (!fname.isReadableFile()) {
3830 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3831 docstring const text =
3832 bformat(_("%1$s\n is not readable."), file);
3833 Alert::error(_("Could not open file"), text);
3837 // FIXME UNICODE: We don't know the encoding of the file
3838 docstring file_content = fname.fileContents("UTF-8");
3839 if (file_content.empty()) {
3840 Alert::error(_("Reading not UTF-8 encoded file"),
3841 _("The file is not UTF-8 encoded.\n"
3842 "It will be read as local 8Bit-encoded.\n"
3843 "If this does not give the correct result\n"
3844 "then please change the encoding of the file\n"
3845 "to UTF-8 with a program other than LyX.\n"));
3846 file_content = fname.fileContents("local8bit");
3849 return normalize_c(file_content);
3853 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
3855 docstring const tmpstr = contentsOfPlaintextFile(f);
3860 Cursor & cur = cursor();
3861 cap::replaceSelection(cur);
3862 buffer_.undo().recordUndo(cur);
3864 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3866 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3868 buffer_.changed(true);
3872 docstring const & BufferView::inlineCompletion() const
3874 return d->inlineCompletion_;
3878 size_t BufferView::inlineCompletionUniqueChars() const
3880 return d->inlineCompletionUniqueChars_;
3884 DocIterator const & BufferView::inlineCompletionPos() const
3886 return d->inlineCompletionPos_;
3890 void BufferView::resetInlineCompletionPos()
3892 d->inlineCompletionPos_ = DocIterator();
3896 bool samePar(DocIterator const & a, DocIterator const & b)
3898 if (a.empty() && b.empty())
3900 if (a.empty() || b.empty())
3902 if (a.depth() != b.depth())
3904 return &a.innerParagraph() == &b.innerParagraph();
3908 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3909 docstring const & completion, size_t uniqueChars)
3911 uniqueChars = min(completion.size(), uniqueChars);
3912 bool changed = d->inlineCompletion_ != completion
3913 || d->inlineCompletionUniqueChars_ != uniqueChars;
3914 bool singlePar = true;
3915 d->inlineCompletion_ = completion;
3916 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3918 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3921 DocIterator const & old = d->inlineCompletionPos_;
3923 //lyxerr << "inlineCompletionPos changed" << std::endl;
3924 // old or pos are in another paragraph?
3925 if ((!samePar(cur, pos) && !pos.empty())
3926 || (!samePar(cur, old) && !old.empty())) {
3928 //lyxerr << "different paragraph" << std::endl;
3930 d->inlineCompletionPos_ = pos;
3935 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3936 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3938 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3943 bool BufferView::clickableInset() const
3945 return d->clickable_inset_;
3949 bool BufferView::stats_update_trigger()
3951 if (d->stats_update_trigger_) {
3952 d->stats_update_trigger_ = false;