3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
19 #include "BranchList.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BiblioInfo.h"
24 #include "CoordCache.h"
26 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
29 #include "FuncRequest.h"
30 #include "FuncStatus.h"
33 #include "LayoutFile.h"
36 #include "LyXAction.h"
39 #include "MetricsInfo.h"
40 #include "Paragraph.h"
42 #include "texstream.h"
44 #include "TextMetrics.h"
46 #include "TocBackend.h"
48 #include "insets/InsetBibtex.h"
49 #include "insets/InsetCitation.h"
50 #include "insets/InsetCommand.h" // ChangeRefs
51 #include "insets/InsetGraphics.h"
52 #include "insets/InsetIndex.h"
53 #include "insets/InsetRef.h"
54 #include "insets/InsetText.h"
56 #include "mathed/InsetMathNest.h"
57 #include "mathed/InsetMathRef.h"
58 #include "mathed/MathData.h"
59 #include "mathed/MathRow.h"
61 #include "frontends/alert.h"
62 #include "frontends/CaretGeometry.h"
63 #include "frontends/Delegates.h"
64 #include "frontends/FontMetrics.h"
65 #include "frontends/NullPainter.h"
66 #include "frontends/Painter.h"
67 #include "frontends/Selection.h"
68 #include "frontends/Clipboard.h"
70 #include "support/convert.h"
71 #include "support/debug.h"
72 #include "support/docstring.h"
73 #include "support/docstring_list.h"
74 #include "support/filetools.h"
75 #include "support/gettext.h"
76 #include "support/lassert.h"
77 #include "support/Length.h"
78 #include "support/lstrings.h"
79 #include "support/lyxlib.h"
80 #include "support/types.h"
92 using namespace lyx::support;
96 namespace Alert = frontend::Alert;
100 /// Return an inset of this class if it exists at the current cursor position
102 T * getInsetByCode(Cursor const & cur, InsetCode code)
104 DocIterator it = cur;
105 Inset * inset = it.nextInset();
106 if (inset && inset->lyxCode() == code)
107 return static_cast<T*>(inset);
112 /// Note that comparing contents can only be used for InsetCommand
113 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
114 docstring const & contents)
116 DocIterator tmpdit = dit;
119 Inset const * inset = tmpdit.nextInset();
121 bool const valid_code = std::find(codes.begin(), codes.end(),
122 inset->lyxCode()) != codes.end();
123 InsetCommand const * ic = inset->asInsetCommand();
124 bool const same_or_no_contents = contents.empty()
125 || (ic && (ic->getFirstNonOptParam() == contents));
127 if (valid_code && same_or_no_contents) {
132 tmpdit.forwardInset();
139 /// Looks for next inset with one of the given codes.
140 /// Note that same_content can only be used for InsetCommand
141 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
145 DocIterator tmpdit = dit;
146 tmpdit.forwardInset();
150 Inset const * inset = tmpdit.nextInset();
151 if (same_content && inset) {
152 InsetCommand const * ic = inset->asInsetCommand();
154 bool const valid_code = std::find(codes.begin(), codes.end(),
155 ic->lyxCode()) != codes.end();
157 contents = ic->getFirstNonOptParam();
161 if (!findNextInset(tmpdit, codes, contents)) {
162 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
163 inset = &tmpdit.bottom().inset();
164 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
165 if (!findNextInset(tmpdit, codes, contents))
177 /// Moves cursor to the next inset with one of the given codes.
178 bool gotoInset(BufferView * bv, vector<InsetCode> const & codes,
181 Cursor tmpcur = bv->cursor();
182 if (!findInset(tmpcur, codes, same_content)) {
183 bv->cursor().message(_("No more insets"));
187 tmpcur.clearSelection();
188 bv->setCursor(tmpcur);
189 return bv->scrollToCursor(bv->cursor(), SCROLL_TOP);
193 /// A map from a Text to the associated text metrics
194 typedef map<Text const *, TextMetrics> TextMetricsCache;
196 enum ScreenUpdateStrategy {
206 /////////////////////////////////////////////////////////////////////
210 /////////////////////////////////////////////////////////////////////
212 struct BufferView::Private
214 Private(BufferView & bv) :
215 update_strategy_(FullScreenUpdate),
216 update_flags_(Update::Force),
217 cursor_(bv), anchor_pit_(0), anchor_ypos_(0),
218 wh_(0), inlineCompletionUniqueChars_(0),
219 last_inset_(nullptr), mouse_position_cache_(),
220 gui_(nullptr), bookmark_edit_position_(-1),
221 horiz_scroll_offset_(0), clickable_inset_(false)
223 xsel_cache_.set = false;
227 ScrollbarParameters scrollbarParameters_;
229 ScreenUpdateStrategy update_strategy_;
231 Update::flags update_flags_;
233 CoordCache coord_cache_;
235 typedef unordered_map<MathData const *, MathRow> MathRows;
238 /// this is used to handle XSelection events in the right manner.
247 pit_type anchor_pit_;
250 /// Estimated average par height for scrollbar.
253 vector<int> par_height_;
256 DocIterator inlineCompletionPos_;
258 docstring inlineCompletion_;
260 size_t inlineCompletionUniqueChars_;
262 /// keyboard mapping object.
265 /// last visited inset.
266 /** kept to send setMouseHover(false).
267 * Not owned, so don't delete.
269 Inset const * last_inset_;
271 /// position of the mouse at the time of the last mouse move
272 /// This is used to update the hovering status of inset in
273 /// cases where the buffer is scrolled, but the mouse didn't move.
274 Point mouse_position_cache_;
276 mutable TextMetricsCache text_metrics_;
279 /** Not owned, so don't delete.
281 frontend::GuiBufferViewDelegate * gui_;
284 map<string, Inset *> edited_insets_;
286 // 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;
304 BufferView::BufferView(Buffer & buf)
305 : width_(0), height_(0), full_screen_(false), buffer_(buf),
306 d(new Private(*this))
308 d->xsel_cache_.set = false;
309 d->intl_.initKeyMapper(lyxrc.use_kbmap);
311 d->cursor_.setBuffer(&buf);
312 d->cursor_.push(buffer_.inset());
313 d->cursor_.resetAnchor();
314 d->cursor_.setCurrentFont();
316 buffer_.updatePreviews();
320 BufferView::~BufferView()
322 // current buffer is going to be switched-off, save cursor pos
323 // Ideally, the whole cursor stack should be saved, but session
324 // currently can only handle bottom (whole document) level pit and pos.
325 // That is to say, if a cursor is in a nested inset, it will be
326 // restore to the left of the top level inset.
327 LastFilePosSection::FilePos fp;
328 fp.file = buffer_.fileName();
329 fp.pit = d->cursor_.bottom().pit();
330 fp.pos = d->cursor_.bottom().pos();
331 theSession().lastFilePos().save(fp);
334 d->last_inset_->setMouseHover(this, false);
340 void BufferView::copySettingsFrom(BufferView const & bv)
342 setCursor(bv.cursor());
343 d->anchor_pit_ = bv.d->anchor_pit_;
344 d->anchor_ypos_ = bv.d->anchor_ypos_;
348 int BufferView::defaultMargin() const
350 // The value used to be hardcoded to 10
351 return zoomedPixels(20);
355 int BufferView::rightMargin() const
357 const int screen_width = inPixels(lyxrc.screen_width);
359 // The additional test for the case the outliner is opened.
360 if (!lyxrc.screen_limit || width_ < screen_width + 2 * defaultMargin()) {
361 return defaultMargin();
363 return (width_ - screen_width) / 2;
368 int BufferView::leftMargin() const
370 return rightMargin();
374 int BufferView::topMargin() const
376 // Original value was 20px at 100dpi. For internal buffers like in
377 // advanced search and replace, a value of 5px is enough.
378 return zoomedPixels(buffer().isInternal() ? 5 : 20);
382 int BufferView::bottomMargin() const
388 int BufferView::inPixels(Length const & len) const
390 Font const font = buffer().params().getFont();
391 return len.inPixels(workWidth(), theFontMetrics(font).em());
395 int BufferView::zoomedPixels(int pix) const
397 // FIXME: the dpi setting should really depend on the BufferView
398 // (think different monitors).
400 // Zoom factor specified by user in percent
401 double const zoom = lyxrc.currentZoom / 100.0; // [percent]
403 // DPI setting for monitor relative to 100dpi
404 double const dpizoom = lyxrc.dpi / 100.0; // [per 100dpi]
406 return support::iround(pix * zoom * dpizoom);
410 bool BufferView::isTopScreen() const
412 return 0 == d->scrollbarParameters_.min;
416 bool BufferView::isBottomScreen() const
418 return 0 == d->scrollbarParameters_.max;
422 Intl & BufferView::getIntl()
428 Intl const & BufferView::getIntl() const
434 CoordCache & BufferView::coordCache()
436 return d->coord_cache_;
440 CoordCache const & BufferView::coordCache() const
442 return d->coord_cache_;
446 bool BufferView::hasMathRow(MathData const * cell) const
448 return d->math_rows_.find(cell) != d->math_rows_.end();
452 MathRow const & BufferView::mathRow(MathData const * cell) const
454 auto it = d->math_rows_.find(cell);
455 LATTEST(it != d->math_rows_.end());
460 void BufferView::setMathRow(MathData const * cell, MathRow const & mrow)
462 d->math_rows_[cell] = mrow;
466 Buffer & BufferView::buffer()
472 Buffer const & BufferView::buffer() const
478 docstring const & BufferView::searchRequestCache() const
480 return theClipboard().getFindBuffer();
484 void BufferView::setSearchRequestCache(docstring const & text)
492 docstring const search = string2find(text, casesensitive, matchword,
493 forward, wrap, instant, onlysel);
494 theClipboard().setFindBuffer(search);
498 bool BufferView::needsFitCursor() const
500 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
501 frontend::FontMetrics const & fm =
502 theFontMetrics(d->cursor_.getFont().fontInfo());
503 int const asc = fm.maxAscent();
504 int const des = fm.maxDescent();
505 Point const p = getPos(d->cursor_);
506 if (p.y_ - asc >= 0 && p.y_ + des < height_)
515 // this is for debugging only.
516 string flagsAsString(Update::flags flags)
518 if (flags == Update::None)
520 return string((flags & Update::FitCursor) ? "FitCursor " : "")
521 + ((flags & Update::Force) ? "Force " : "")
522 + ((flags & Update::ForceDraw) ? "ForceDraw " : "")
523 + ((flags & Update::SinglePar) ? "SinglePar " : "")
524 + ((flags & Update::Decoration) ? "Decoration " : "");
529 void BufferView::processUpdateFlags(Update::flags flags)
531 LYXERR(Debug::PAINTING, "BufferView::processUpdateFlags( "
532 << flagsAsString(flags) << ") buffer: " << &buffer_);
534 // Case when no explicit update is requested.
535 if (flags == Update::None)
538 /* FIXME We would like to avoid doing this here, since it is very
539 * expensive and is called in updateBuffer already. However, even
540 * inserting a plain character can invalidate the overly fragile
541 * tables of child documents built by updateMacros. Some work is
542 * needed to avoid doing that when not necessary.
544 buffer_.updateMacros();
546 // First check whether the metrics and inset positions should be updated
547 if (flags & Update::Force) {
548 // This will update the CoordCache items and replace Force
549 // with ForceDraw in flags.
550 updateMetrics(flags);
553 // Detect whether we can only repaint a single paragraph (if we
554 // are not already redrawing all).
555 // We handle this before FitCursor because the later will require
556 // correct metrics at cursor position.
557 if (!(flags & Update::ForceDraw)
558 && (flags & Update::SinglePar)
559 && !singleParUpdate())
560 updateMetrics(flags);
562 // Then make sure that the screen contains the cursor if needed
563 if (flags & Update::FitCursor) {
564 if (needsFitCursor()) {
565 // First try to make the selection start visible
566 // (which is just the cursor when there is no selection)
567 scrollToCursor(d->cursor_.selectionBegin(), SCROLL_VISIBLE);
568 // Metrics have to be recomputed (maybe again)
570 // Is the cursor visible? (only useful if cursor is at end of selection)
571 if (needsFitCursor()) {
572 // then try to make cursor visible instead
573 scrollToCursor(d->cursor_, SCROLL_VISIBLE);
574 // Metrics have to be recomputed (maybe again)
575 updateMetrics(flags);
578 flags = flags & ~Update::FitCursor;
581 // Add flags to the the update flags. These will be reset to None
582 // after the redraw is actually done
583 d->update_flags_ = d->update_flags_ | flags;
584 LYXERR(Debug::PAINTING, "Cumulative flags: " << flagsAsString(flags));
586 // Now compute the update strategy
587 // Possibly values in flag are None, SinglePar, Decoration, ForceDraw
588 LATTEST((d->update_flags_ & ~(Update::None | Update::SinglePar
589 | Update::Decoration | Update::ForceDraw)) == 0);
591 if (d->update_flags_ & Update::ForceDraw)
592 d->update_strategy_ = FullScreenUpdate;
593 else if (d->update_flags_ & Update::Decoration)
594 d->update_strategy_ = DecorationUpdate;
595 else if (d->update_flags_ & Update::SinglePar)
596 d->update_strategy_ = SingleParUpdate;
598 // no need to redraw anything.
599 d->update_strategy_ = NoScreenUpdate;
602 updateHoveredInset();
605 buffer_.changed(false);
609 void BufferView::updateScrollbarParameters()
611 if (height_ == 0 && width_ == 0)
614 // We prefer fixed size line scrolling.
615 d->scrollbarParameters_.single_step = defaultRowHeight();
616 // We prefer full screen page scrolling.
617 d->scrollbarParameters_.page_step = height_;
619 Text & t = buffer_.text();
620 TextMetrics & tm = d->text_metrics_[&t];
622 LYXERR(Debug::SCROLLING, " Updating scrollbar: height: "
623 << t.paragraphs().size()
624 << " curr par: " << d->cursor_.bottom().pit()
625 << " default height " << defaultRowHeight());
627 size_t const parsize = t.paragraphs().size();
628 if (d->par_height_.size() != parsize) {
629 d->par_height_.clear();
630 // FIXME: We assume a default paragraph height of 2 rows. This
631 // should probably be pondered with the screen width.
632 d->par_height_.resize(parsize, defaultRowHeight() * 2);
635 // Look at paragraph heights on-screen
636 pair<pit_type, ParagraphMetrics const *> first = tm.first();
637 pair<pit_type, ParagraphMetrics const *> last = tm.last();
638 for (pit_type pit = first.first; pit <= last.first; ++pit) {
639 d->par_height_[pit] = tm.parMetrics(pit).height();
640 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
641 << d->par_height_[pit]);
644 int top_pos = first.second->position() - first.second->ascent();
645 int bottom_pos = last.second->position() + last.second->descent();
646 bool first_visible = first.first == 0 && top_pos >= 0;
647 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
648 if (first_visible && last_visible) {
649 d->scrollbarParameters_.min = 0;
650 d->scrollbarParameters_.max = 0;
654 d->scrollbarParameters_.min = top_pos;
655 for (size_t i = 0; i != size_t(first.first); ++i)
656 d->scrollbarParameters_.min -= d->par_height_[i];
657 d->scrollbarParameters_.max = bottom_pos;
658 for (size_t i = last.first + 1; i != parsize; ++i)
659 d->scrollbarParameters_.max += d->par_height_[i];
661 // The reference is the top position so we remove one page.
662 if (lyxrc.scroll_below_document)
663 d->scrollbarParameters_.max -= minVisiblePart();
665 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
667 // 0 must be inside the range as it denotes the current position
668 if (d->scrollbarParameters_.max < 0)
669 d->scrollbarParameters_.max = 0;
670 if (d->scrollbarParameters_.min > 0)
671 d->scrollbarParameters_.min = 0;
675 ScrollbarParameters const & BufferView::scrollbarParameters() const
677 return d->scrollbarParameters_;
681 docstring BufferView::toolTip(int x, int y) const
683 // Get inset under mouse, if there is one.
684 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
686 // No inset, no tooltip...
688 return covering_inset->toolTip(*this, x, y);
692 string BufferView::contextMenu(int x, int y) const
694 //If there is a selection, return the containing inset menu
695 if (d->cursor_.selection())
696 return d->cursor_.inset().contextMenu(*this, x, y);
698 // Get inset under mouse, if there is one.
699 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
700 if (covering_inset) {
701 if (covering_inset->asInsetMath()) {
702 CoordCache::Insets const & inset_cache =
703 coordCache().getInsets();
704 Inset const * inner_inset = mathContextMenu(
705 covering_inset->asInsetMath()->asNestInset(),
708 return inner_inset->contextMenu(*this, x, y);
710 return covering_inset->contextMenu(*this, x, y);
713 return buffer_.inset().contextMenu(*this, x, y);
717 Inset const * BufferView::mathContextMenu(InsetMathNest const * inset,
718 CoordCache::Insets const & inset_cache, int x, int y) const
720 for (size_t i = 0; i < inset->nargs(); ++i) {
721 MathData const & ar = inset->cell(i);
722 for (size_t j = 0; j < ar.size(); ++j) {
723 string const name = lyxerr.debugging(Debug::MATHED)
724 ? insetName(ar[j].nucleus()->lyxCode())
726 LYXERR(Debug::MATHED, "Examining inset: " << name);
727 if (!ar[j].nucleus()->contextMenuName().empty()) {
728 if (inset_cache.covers(ar[j].nucleus(), x, y)) {
729 LYXERR(Debug::MATHED, "Hit inset: "
731 return ar[j].nucleus();
734 InsetMathNest const * imn =
735 ar[j].nucleus()->asNestInset();
737 Inset const * inner =
738 mathContextMenu(imn, inset_cache, x, y);
748 void BufferView::scrollDocView(int const pixels, bool update)
750 // The scrollbar values are relative to the top of the screen, therefore the
751 // offset is equal to the target value.
753 // No scrolling at all? No need to redraw anything
757 // If the offset is less than 2 screen height, prefer to scroll instead.
758 if (abs(pixels) <= 2 * height_) {
759 d->anchor_ypos_ -= pixels;
760 processUpdateFlags(Update::Force);
764 // cut off at the top
765 if (pixels <= d->scrollbarParameters_.min) {
766 DocIterator dit = doc_iterator_begin(&buffer_);
767 showCursor(dit, SCROLL_VISIBLE, update);
768 LYXERR(Debug::SCROLLING, "scroll to top");
772 // cut off at the bottom
773 if (pixels >= d->scrollbarParameters_.max) {
774 DocIterator dit = doc_iterator_end(&buffer_);
776 showCursor(dit, SCROLL_VISIBLE, update);
777 LYXERR(Debug::SCROLLING, "scroll to bottom");
781 // find paragraph at target position
782 int par_pos = d->scrollbarParameters_.min;
784 for (; i != int(d->par_height_.size()); ++i) {
785 par_pos += d->par_height_[i];
786 if (par_pos >= pixels)
790 if (par_pos < pixels) {
791 // It seems we didn't find the correct pit so stay on the safe side and
793 LYXERR0("scrolling position not found!");
794 scrollDocView(d->scrollbarParameters_.max, update);
798 DocIterator dit = doc_iterator_begin(&buffer_);
800 LYXERR(Debug::SCROLLING, "pixels = " << pixels << " -> scroll to pit " << i);
801 showCursor(dit, SCROLL_VISIBLE, update);
805 // FIXME: this method is not working well.
806 void BufferView::setCursorFromScrollbar()
808 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
810 int const height = 2 * defaultRowHeight();
811 int const first = height;
812 int const last = height_ - height;
814 Cursor const & oldcur = d->cursor_;
816 switch (cursorStatus(oldcur)) {
824 int const y = getPos(oldcur).y_;
825 newy = min(last, max(y, first));
829 // We reset the cursor because cursorStatus() does not
830 // work when the cursor is within mathed.
833 tm.setCursorFromCoordinates(cur, 0, newy);
835 // update the bufferview cursor and notify insets
836 // FIXME: Care about the d->cursor_ flags to redraw if needed
837 Cursor old = d->cursor_;
839 // the DEPM call in mouseSetCursor() might have destroyed the
840 // paragraph the cursor is in.
841 bool badcursor = old.fixIfBroken();
842 badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
844 d->cursor_.fixIfBroken();
848 Change const BufferView::getCurrentChange() const
850 if (!d->cursor_.selection())
851 return Change(Change::UNCHANGED);
853 DocIterator dit = d->cursor_.selectionBegin();
854 // The selected content might have been changed (see #7685)
855 dit = dit.getInnerText();
856 return dit.paragraph().lookupChange(dit.pos());
860 // this could be used elsewhere as well?
861 // FIXME: This does not work within mathed!
862 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
864 Point const p = getPos(dit);
867 if (p.y_ > workHeight())
873 void BufferView::bookmarkEditPosition()
875 // Don't eat cpu time for each keystroke
876 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
879 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
883 void BufferView::saveBookmark(unsigned int idx)
885 if (buffer().isInternal())
888 // tentatively save bookmark, id and pos will be used to
889 // acturately locate a bookmark in a 'live' lyx session.
890 // pit and pos will be updated with bottom level pit/pos
892 theSession().bookmarks().save(
894 d->cursor_.bottom().pit(),
895 d->cursor_.bottom().pos(),
896 d->cursor_.paragraph().id(),
901 // emit message signal.
902 message(_("Save bookmark"));
906 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
907 int top_id, pos_type top_pos)
909 bool success = false;
912 d->cursor_.clearSelection();
914 // if a valid par_id is given, try it first
915 // This is the case for a 'live' bookmark when unique paragraph ID
916 // is used to track bookmarks.
918 dit = buffer_.getParFromID(top_id);
920 dit.pos() = min(dit.paragraph().size(), top_pos);
921 // Some slices of the iterator may not be
922 // reachable (e.g. closed collapsible inset)
923 // so the dociterator may need to be
924 // shortened. Otherwise, setCursor may crash
925 // lyx when the cursor can not be set to these
927 size_t const n = dit.depth();
928 for (size_t i = 0; i < n; ++i)
929 if (!dit[i].inset().editable()) {
937 // if top_id == 0, or searching through top_id failed
938 // This is the case for a 'restored' bookmark when only bottom
939 // (document level) pit was saved. Because of this, bookmark
940 // restoration is inaccurate. If a bookmark was within an inset,
941 // it will be restored to the left of the outmost inset that contains
943 if (!success && bottom_pit < int(buffer_.paragraphs().size())) {
944 dit = doc_iterator_begin(&buffer_);
946 dit.pit() = bottom_pit;
947 dit.pos() = min(bottom_pos, dit.paragraph().size());
952 // Note: only bottom (document) level pit is set.
954 // set the current font.
955 d->cursor_.setCurrentFont();
956 // Do not forget to reset the anchor (see #9912)
957 d->cursor_.resetAnchor();
958 processUpdateFlags(Update::Force | Update::FitCursor);
965 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
967 if (d->cursor_.real_current_font.isRightToLeft()) {
968 if (d->intl_.keymap == Intl::PRIMARY)
969 d->intl_.keyMapSec();
971 if (d->intl_.keymap == Intl::SECONDARY)
972 d->intl_.keyMapPrim();
975 d->intl_.getTransManager().translateAndInsert(c, t, cur);
979 int BufferView::workWidth() const
985 void BufferView::recenter()
987 showCursor(d->cursor_, SCROLL_CENTER, true);
991 void BufferView::showCursor()
993 showCursor(d->cursor_, SCROLL_VISIBLE, true);
997 void BufferView::showCursor(DocIterator const & dit, ScrollType how,
1000 if (scrollToCursor(dit, how) && update)
1001 processUpdateFlags(Update::Force);
1005 bool BufferView::scrollToCursor(DocIterator const & dit, ScrollType how)
1007 // We are not properly started yet, delay until resizing is done.
1011 if (how == SCROLL_CENTER)
1012 LYXERR(Debug::SCROLLING, "Centering cursor in workarea");
1013 else if (how == SCROLL_TOP)
1014 LYXERR(Debug::SCROLLING, "Setting cursor to top of workarea");
1016 LYXERR(Debug::SCROLLING, "Making sure cursor is visible in workarea");
1018 CursorSlice const & bot = dit.bottom();
1019 TextMetrics & tm = textMetrics(bot.text());
1021 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
1022 pos_type bot_pit = bot.pit();
1023 if (bot_pit > max_pit) {
1024 // FIXME: Why does this happen?
1025 LYXERR0("bottom pit is greater that max pit: "
1026 << bot_pit << " > " << max_pit);
1030 if (bot_pit == tm.first().first - 1)
1031 tm.newParMetricsUp();
1032 else if (bot_pit == tm.last().first + 1)
1033 tm.newParMetricsDown();
1035 if (tm.contains(bot_pit) && how == SCROLL_VISIBLE) {
1036 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
1037 LBUFERR(!pm.rows().empty());
1038 // FIXME: smooth scrolling doesn't work in mathed.
1039 CursorSlice const & cs = dit.innerTextSlice();
1040 int const ypos = pm.position() + coordOffset(dit).y_;
1041 ParagraphMetrics const & inner_pm =
1042 textMetrics(cs.text()).parMetrics(cs.pit());
1043 Dimension const & row_dim =
1044 inner_pm.getRow(cs.pos(), dit.boundary()).dim();
1047 // We try to visualize the whole row, if the row height is larger than
1048 // the screen height, we scroll to a heuristic value of height_ / 4.
1049 // FIXME: This heuristic value should be replaced by a recursive search
1050 // for a row in the inset that can be visualized completely.
1051 if (row_dim.height() > height_) {
1052 if (ypos < defaultRowHeight())
1053 scrolled = scroll(ypos - height_ / 4);
1054 else if (ypos > height_ - defaultRowHeight())
1055 scrolled = scroll(ypos - 3 * height_ / 4);
1058 // If the top part of the row falls of the screen, we scroll
1059 // up to align the top of the row with the top of the screen.
1060 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
1061 int const ynew = row_dim.ascent();
1062 scrolled = scrollUp(ynew - ypos);
1065 // If the bottom of the row falls of the screen, we scroll down.
1066 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
1067 int const ynew = height_ - row_dim.descent();
1068 scrolled = scrollDown(ypos - ynew);
1071 // else, nothing to do, the cursor is already visible so we just return.
1072 return scrolled != 0;
1075 // fix inline completion position
1076 if (d->inlineCompletionPos_.fixIfBroken())
1077 d->inlineCompletionPos_ = DocIterator();
1079 tm.redoParagraph(bot_pit);
1080 int const offset = coordOffset(dit).y_;
1081 pit_type const old_pit = d->anchor_pit_;
1082 d->anchor_pit_ = bot_pit;
1084 CursorSlice const & cs = dit.innerTextSlice();
1085 ParagraphMetrics const & inner_pm =
1086 textMetrics(cs.text()).parMetrics(cs.pit());
1087 Dimension const & row_dim =
1088 inner_pm.getRow(cs.pos(), dit.boundary()).dim();
1090 int const old_ypos = d->anchor_ypos_;
1091 d->anchor_ypos_ = - offset + row_dim.ascent();
1092 if (how == SCROLL_CENTER)
1093 d->anchor_ypos_ += height_/2 - row_dim.height() / 2;
1094 else if (!lyxrc.scroll_below_document && d->anchor_pit_ == max_pit)
1095 d->anchor_ypos_ = height_ - offset - row_dim.descent();
1096 else if (offset > height_)
1097 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
1099 d->anchor_ypos_ = defaultRowHeight() * 2;
1101 return d->anchor_ypos_ != old_ypos || d->anchor_pit_ != old_pit;
1105 void BufferView::makeDocumentClass()
1107 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1108 buffer_.params().makeDocumentClass(buffer_.isClone(), buffer_.isInternal());
1109 updateDocumentClass(olddc);
1113 void BufferView::updateDocumentClass(DocumentClassConstPtr olddc)
1115 StableDocIterator backcur(d->cursor_);
1116 ErrorList & el = buffer_.errorList("Class Switch");
1117 cap::switchBetweenClasses(
1118 olddc, buffer_.params().documentClassPtr(),
1119 static_cast<InsetText &>(buffer_.inset()), el);
1121 setCursor(backcur.asDocIterator(&buffer_));
1123 buffer_.errors("Class Switch");
1127 /** Return the change status at cursor position, taking into account the
1128 * status at each level of the document iterator (a table in a deleted
1129 * footnote is deleted).
1130 * When \param outer is true, the top slice is not looked at.
1132 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
1134 size_t const depth = dit.depth() - (outer ? 1 : 0);
1136 for (size_t i = 0 ; i < depth ; ++i) {
1137 CursorSlice const & slice = dit[i];
1138 if (!slice.inset().inMathed()
1139 && slice.pos() < slice.paragraph().size()) {
1140 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
1141 if (ch != Change::UNCHANGED)
1145 return Change::UNCHANGED;
1149 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1151 FuncCode const act = cmd.action();
1153 // Can we use a readonly buffer?
1154 if (buffer_.isReadonly()
1155 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1156 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1157 if (buffer_.hasReadonlyFlag())
1158 flag.message(from_utf8(N_("Document is read-only")));
1160 flag.message(from_utf8(N_("Document has been modified externally")));
1161 flag.setEnabled(false);
1165 // Are we in a DELETED change-tracking region?
1166 if (lookupChangeType(d->cursor_, true) == Change::DELETED
1167 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1168 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1169 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1170 flag.setEnabled(false);
1174 Cursor & cur = d->cursor_;
1176 if (cur.getStatus(cmd, flag))
1181 // FIXME: This is a bit problematic because we don't check if this is
1182 // a document BufferView or not for these LFUNs. We probably have to
1183 // dispatch both to currentBufferView() and, if that fails,
1184 // to documentBufferView(); same as we do now for current Buffer and
1185 // document Buffer. Ideally those LFUN should go to Buffer as they
1186 // operate on the full Buffer and the cursor is only needed either for
1187 // an Undo record or to restore a cursor position. But we don't know
1188 // how to do that inside Buffer of course.
1189 case LFUN_BUFFER_PARAMS_APPLY:
1190 case LFUN_LAYOUT_MODULES_CLEAR:
1191 case LFUN_LAYOUT_MODULE_ADD:
1192 case LFUN_LAYOUT_RELOAD:
1193 case LFUN_TEXTCLASS_APPLY:
1194 case LFUN_TEXTCLASS_LOAD:
1195 flag.setEnabled(!buffer_.isReadonly());
1199 // We do not use the LyXAction flag for readonly because Undo sets the
1200 // buffer clean/dirty status by itself.
1201 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1204 // We do not use the LyXAction flag for readonly because Redo sets the
1205 // buffer clean/dirty status by itself.
1206 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1208 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1209 case LFUN_FILE_INSERT_PLAINTEXT: {
1210 docstring const & fname = cmd.argument();
1211 if (!FileName::isAbsolute(to_utf8(fname))) {
1212 flag.message(_("Absolute filename expected."));
1215 flag.setEnabled(cur.inTexted());
1218 case LFUN_FILE_INSERT:
1219 case LFUN_BOOKMARK_SAVE:
1220 // FIXME: Actually, these LFUNS should be moved to Text
1221 flag.setEnabled(cur.inTexted());
1224 case LFUN_FONT_STATE:
1225 case LFUN_LABEL_INSERT:
1226 case LFUN_INFO_INSERT:
1227 case LFUN_PARAGRAPH_GOTO:
1228 case LFUN_NOTE_NEXT:
1229 case LFUN_REFERENCE_NEXT:
1230 case LFUN_WORD_FIND:
1231 case LFUN_WORD_FIND_FORWARD:
1232 case LFUN_WORD_FIND_BACKWARD:
1233 case LFUN_WORD_REPLACE:
1236 case LFUN_MARK_TOGGLE:
1237 case LFUN_SEARCH_STRING_SET:
1238 case LFUN_SCREEN_RECENTER:
1239 case LFUN_SCREEN_SHOW_CURSOR:
1240 case LFUN_BIBTEX_DATABASE_ADD:
1241 case LFUN_BIBTEX_DATABASE_DEL:
1242 case LFUN_BIBTEX_DATABASE_LIST:
1243 case LFUN_STATISTICS:
1244 case LFUN_KEYMAP_OFF:
1245 case LFUN_KEYMAP_PRIMARY:
1246 case LFUN_KEYMAP_SECONDARY:
1247 case LFUN_KEYMAP_TOGGLE:
1248 case LFUN_INSET_SELECT_ALL:
1249 flag.setEnabled(true);
1252 case LFUN_GRAPHICS_UNIFY:
1253 flag.setEnabled(cur.countInsetsInSelection(GRAPHICS_CODE)>1);
1256 case LFUN_WORD_FINDADV: {
1257 FindAndReplaceOptions opt;
1258 istringstream iss(to_utf8(cmd.argument()));
1260 flag.setEnabled(opt.repl_buf_name.empty()
1261 || !buffer_.isReadonly());
1265 case LFUN_LABEL_GOTO:
1266 flag.setEnabled(!cmd.argument().empty()
1267 || getInsetByCode<InsetRef>(cur, REF_CODE)
1268 || getInsetByCode<InsetMathRef>(cur, MATH_REF_CODE));
1271 case LFUN_CHANGES_MERGE:
1272 case LFUN_CHANGE_NEXT:
1273 case LFUN_CHANGE_PREVIOUS:
1274 case LFUN_ALL_CHANGES_ACCEPT:
1275 case LFUN_ALL_CHANGES_REJECT:
1276 flag.setEnabled(buffer_.areChangesPresent());
1279 case LFUN_SCREEN_UP:
1280 case LFUN_SCREEN_DOWN:
1282 case LFUN_SCREEN_UP_SELECT:
1283 case LFUN_SCREEN_DOWN_SELECT:
1284 case LFUN_INSET_FORALL:
1285 flag.setEnabled(true);
1288 case LFUN_LAYOUT_TABULAR:
1289 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1293 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1296 case LFUN_LAYOUT_PARAGRAPH:
1297 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1300 case LFUN_BRANCH_ADD_INSERT:
1301 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1304 case LFUN_DIALOG_SHOW_NEW_INSET:
1305 // FIXME: this is wrong, but I do not understand the
1307 if (cur.inset().lyxCode() == CAPTION_CODE)
1308 return cur.inset().getStatus(cur, cmd, flag);
1309 // FIXME we should consider passthru paragraphs too.
1310 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1313 case LFUN_CITATION_INSERT: {
1314 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1315 // FIXME: This could turn in a recursive hell.
1316 // Shouldn't we use Buffer::getStatus() instead?
1317 flag.setEnabled(lyx::getStatus(fr).enabled());
1320 case LFUN_INSET_APPLY: {
1321 string const name = cmd.getArg(0);
1322 Inset * inset = editedInset(name);
1324 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1325 if (!inset->getStatus(cur, fr, flag)) {
1326 // Every inset is supposed to handle this
1327 LASSERT(false, break);
1330 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1331 flag = lyx::getStatus(fr);
1337 flag.setEnabled(cur.selection());
1348 Inset * BufferView::editedInset(string const & name) const
1350 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1351 return it == d->edited_insets_.end() ? nullptr : it->second;
1355 void BufferView::editInset(string const & name, Inset * inset)
1358 d->edited_insets_[name] = inset;
1360 d->edited_insets_.erase(name);
1364 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1366 LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1368 string const argument = to_utf8(cmd.argument());
1369 Cursor & cur = d->cursor_;
1372 // Don't dispatch function that does not apply to internal buffers.
1373 if (buffer_.isInternal()
1374 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1377 // We'll set this back to false if need be.
1378 bool dispatched = true;
1379 buffer_.undo().beginUndoGroup();
1381 FuncCode const act = cmd.action();
1384 case LFUN_BUFFER_PARAMS_APPLY: {
1385 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1386 cur.recordUndoBufferParams();
1387 istringstream ss(to_utf8(cmd.argument()));
1390 int const unknown_tokens = buffer_.readHeader(lex);
1391 if (unknown_tokens != 0) {
1392 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1393 << unknown_tokens << " unknown token"
1394 << (unknown_tokens == 1 ? "" : "s"));
1396 updateDocumentClass(olddc);
1398 // We are most certainly here because of a change in the document
1399 // It is then better to make sure that all dialogs are in sync with
1400 // current document settings.
1401 dr.screenUpdate(Update::Force | Update::FitCursor);
1402 dr.forceBufferUpdate();
1406 case LFUN_LAYOUT_MODULES_CLEAR: {
1407 // FIXME: this modifies the document in cap::switchBetweenClasses
1408 // without calling recordUndo. Fix this before using
1409 // recordUndoBufferParams().
1410 cur.recordUndoFullBuffer();
1411 buffer_.params().clearLayoutModules();
1412 makeDocumentClass();
1413 dr.screenUpdate(Update::Force);
1414 dr.forceBufferUpdate();
1418 case LFUN_LAYOUT_MODULE_ADD: {
1419 BufferParams const & params = buffer_.params();
1420 if (!params.layoutModuleCanBeAdded(argument)) {
1421 LYXERR0("Module `" << argument <<
1422 "' cannot be added due to failed requirements or "
1423 "conflicts with installed modules.");
1426 // FIXME: this modifies the document in cap::switchBetweenClasses
1427 // without calling recordUndo. Fix this before using
1428 // recordUndoBufferParams().
1429 cur.recordUndoFullBuffer();
1430 buffer_.params().addLayoutModule(argument);
1431 makeDocumentClass();
1432 dr.screenUpdate(Update::Force);
1433 dr.forceBufferUpdate();
1437 case LFUN_TEXTCLASS_APPLY: {
1438 // since this shortcircuits, the second call is made only if
1440 bool const success =
1441 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1442 LayoutFileList::get().load(argument, buffer_.filePath());
1444 docstring s = bformat(_("The document class `%1$s' "
1445 "could not be loaded."), from_utf8(argument));
1446 frontend::Alert::error(_("Could not load class"), s);
1450 LayoutFile const * old_layout = buffer_.params().baseClass();
1451 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1453 if (old_layout == new_layout)
1457 // Save the old, possibly modular, layout for use in conversion.
1458 // FIXME: this modifies the document in cap::switchBetweenClasses
1459 // without calling recordUndo. Fix this before using
1460 // recordUndoBufferParams().
1461 cur.recordUndoFullBuffer();
1462 buffer_.params().setBaseClass(argument, buffer_.layoutPos());
1463 makeDocumentClass();
1464 dr.screenUpdate(Update::Force);
1465 dr.forceBufferUpdate();
1469 case LFUN_TEXTCLASS_LOAD: {
1470 // since this shortcircuits, the second call is made only if
1472 bool const success =
1473 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1474 LayoutFileList::get().load(argument, buffer_.filePath());
1476 docstring s = bformat(_("The document class `%1$s' "
1477 "could not be loaded."), from_utf8(argument));
1478 frontend::Alert::error(_("Could not load class"), s);
1483 case LFUN_LAYOUT_RELOAD: {
1484 LayoutFileIndex bc = buffer_.params().baseClassID();
1485 LayoutFileList::get().reset(bc);
1486 buffer_.params().setBaseClass(bc, buffer_.layoutPos());
1487 makeDocumentClass();
1488 dr.screenUpdate(Update::Force);
1489 dr.forceBufferUpdate();
1494 dr.setMessage(_("Undo"));
1495 cur.clearSelection();
1496 // We need to find out if the bibliography information
1497 // has changed. See bug #11055.
1498 // So these should not be references...
1499 string const engine = buffer().params().citeEngine();
1500 CiteEngineType const enginetype = buffer().params().citeEngineType();
1501 if (!cur.undoAction())
1502 dr.setMessage(_("No further undo information"));
1504 dr.screenUpdate(Update::Force | Update::FitCursor);
1505 dr.forceBufferUpdate();
1506 resetInlineCompletionPos();
1507 if (buffer().params().citeEngine() != engine ||
1508 buffer().params().citeEngineType() != enginetype)
1509 buffer().invalidateCiteLabels();
1515 dr.setMessage(_("Redo"));
1516 cur.clearSelection();
1517 // We need to find out if the bibliography information
1518 // has changed. See bug #11055.
1519 // So these should not be references...
1520 string const engine = buffer().params().citeEngine();
1521 CiteEngineType const enginetype = buffer().params().citeEngineType();
1522 if (!cur.redoAction())
1523 dr.setMessage(_("No further redo information"));
1525 dr.screenUpdate(Update::Force | Update::FitCursor);
1526 dr.forceBufferUpdate();
1527 resetInlineCompletionPos();
1528 if (buffer().params().citeEngine() != engine ||
1529 buffer().params().citeEngineType() != enginetype)
1530 buffer().invalidateCiteLabels();
1535 case LFUN_FONT_STATE:
1536 dr.setMessage(cur.currentState(false));
1539 case LFUN_BOOKMARK_SAVE:
1540 dr.screenUpdate(Update::Force);
1541 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1544 case LFUN_LABEL_GOTO: {
1545 docstring label = cmd.argument();
1546 if (label.empty()) {
1548 getInsetByCode<InsetRef>(cur, REF_CODE);
1550 label = inset->getParam("reference");
1551 // persistent=false: use temp_bookmark
1555 if (!label.empty()) {
1557 // at the moment, this is redundant, since gotoLabel will
1558 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1560 dr.screenUpdate(Update::Force | Update::FitCursor);
1562 InsetMathRef * minset =
1563 getInsetByCode<InsetMathRef>(cur, MATH_REF_CODE);
1565 lyx::dispatch(FuncRequest(LFUN_LABEL_GOTO,
1566 minset->getTarget()));
1571 case LFUN_PARAGRAPH_GOTO: {
1572 int const id = convert<int>(cmd.getArg(0));
1573 pos_type const pos = convert<int>(cmd.getArg(1));
1576 string const str_id_end = cmd.getArg(2);
1577 string const str_pos_end = cmd.getArg(3);
1579 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1580 b = theBufferList().next(b)) {
1583 curs.setCursor(b->getParFromID(id));
1585 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1589 LYXERR(Debug::INFO, "Paragraph " << curs.paragraph().id()
1590 << " found in buffer `"
1591 << b->absFileName() << "'.");
1593 if (b == &buffer_) {
1595 if (str_id_end.empty() || str_pos_end.empty()) {
1598 mouseSetCursor(curs);
1601 int const id_end = convert<int>(str_id_end);
1602 pos_type const pos_end = convert<int>(str_pos_end);
1603 success = setCursorFromEntries({id, pos},
1606 if (success && scrollToCursor(d->cursor_, SCROLL_TOP))
1607 dr.screenUpdate(Update::Force);
1609 // Switch to other buffer view and resend cmd
1610 lyx::dispatch(FuncRequest(
1611 LFUN_BUFFER_SWITCH, b->absFileName()));
1619 case LFUN_NOTE_NEXT:
1620 if (gotoInset(this, { NOTE_CODE }, false))
1621 dr.screenUpdate(Update::Force);
1624 case LFUN_REFERENCE_NEXT: {
1625 if (gotoInset(this, { LABEL_CODE, REF_CODE }, true))
1626 dr.screenUpdate(Update::Force);
1630 case LFUN_CHANGE_NEXT:
1631 findNextChange(this);
1632 if (cur.inset().isTable())
1633 // In tables, there might be whole changed rows or columns
1635 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1636 dr.screenUpdate(Update::Force | Update::FitCursor);
1639 case LFUN_CHANGE_PREVIOUS:
1640 findPreviousChange(this);
1641 if (cur.inset().isTable())
1642 // In tables, there might be whole changed rows or columns
1644 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1645 dr.screenUpdate(Update::Force | Update::FitCursor);
1648 case LFUN_CHANGES_MERGE:
1649 if (findNextChange(this) || findPreviousChange(this)) {
1650 dr.screenUpdate(Update::Force | Update::FitCursor);
1651 dr.forceBufferUpdate();
1652 showDialog("changes");
1656 case LFUN_ALL_CHANGES_ACCEPT: {
1657 // select complete document
1659 cur.selHandle(true);
1660 buffer_.text().cursorBottom(cur);
1661 // accept everything in a single step to support atomic undo
1662 // temporarily disable track changes in order to end with really
1663 // no new (e.g., DPSM-caused) changes (see #7487)
1664 bool const track = buffer_.params().track_changes;
1665 buffer_.params().track_changes = false;
1666 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1667 buffer_.params().track_changes = track;
1669 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1670 dr.screenUpdate(Update::Force | Update::FitCursor);
1671 dr.forceBufferUpdate();
1675 case LFUN_ALL_CHANGES_REJECT: {
1676 // select complete document
1678 cur.selHandle(true);
1679 buffer_.text().cursorBottom(cur);
1680 // reject everything in a single step to support atomic undo
1681 // temporarily disable track changes in order to end with really
1682 // no new (e.g., DPSM-caused) changes (see #7487)
1683 bool const track = buffer_.params().track_changes;
1684 buffer_.params().track_changes = false;
1685 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1686 buffer_.params().track_changes = track;
1688 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1689 dr.screenUpdate(Update::Force | Update::FitCursor);
1690 dr.forceBufferUpdate();
1694 case LFUN_WORD_FIND_FORWARD:
1695 case LFUN_WORD_FIND_BACKWARD: {
1696 docstring searched_string;
1698 if (!cmd.argument().empty()) {
1699 setSearchRequestCache(cmd.argument());
1700 searched_string = cmd.argument();
1702 searched_string = searchRequestCache();
1705 if (searched_string.empty())
1708 docstring const data =
1709 find2string(searched_string, false, false,
1710 act == LFUN_WORD_FIND_FORWARD, false, false, false);
1711 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1713 dr.screenUpdate(Update::Force | Update::FitCursor);
1715 dr.setMessage(_("Search string not found!"));
1719 case LFUN_WORD_FIND: {
1720 docstring arg = cmd.argument();
1722 arg = searchRequestCache();
1724 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1727 if (lyxfind(this, FuncRequest(act, arg)))
1728 dr.screenUpdate(Update::Force | Update::FitCursor);
1730 dr.setMessage(_("Search string not found!"));
1732 setSearchRequestCache(arg);
1736 case LFUN_SEARCH_STRING_SET: {
1737 docstring pattern = cmd.argument();
1738 if (!pattern.empty()) {
1739 setSearchRequestCache(pattern);
1742 if (cur.selection())
1743 pattern = cur.selectionAsString(false);
1744 else if (!cur.inTexted())
1745 break; // not suitable for selectWord at cursor
1747 pos_type spos = cur.pos();
1748 cur.innerText()->selectWord(cur, WHOLE_WORD);
1749 pattern = cur.selectionAsString(false);
1750 cur.selection(false);
1753 setSearchRequestCache(pattern);
1757 case LFUN_WORD_REPLACE: {
1758 if (lyxreplace(this, cmd)) {
1759 dr.forceBufferUpdate();
1760 dr.screenUpdate(Update::Force | Update::FitCursor);
1763 dr.setMessage(_("Search string not found!"));
1767 case LFUN_WORD_FINDADV: {
1768 FindAndReplaceOptions opt;
1769 istringstream iss(to_utf8(cmd.argument()));
1771 if (findAdv(this, opt)) {
1772 dr.screenUpdate(Update::Force | Update::FitCursor);
1782 case LFUN_INDEX_TAG_ALL: {
1787 Inset * ins = cur.nextInset();
1788 if (!ins || ins->lyxCode() != INDEX_CODE)
1789 // not at index inset
1792 // clone the index inset
1794 new InsetIndex(static_cast<InsetIndex &>(*cur.nextInset()));
1795 // In order to avoid duplication, we compare the
1796 // LaTeX output if we find another index inset after
1798 odocstringstream oilatex;
1799 otexstream oits(oilatex);
1800 OutputParams rp(&cur.buffer()->params().encoding());
1801 ins->latex(oits, rp);
1802 cap::copyInsetToTemp(cur, cins);
1804 // move backwards into preceding word
1805 // skip over other index insets
1806 cur.backwardPosIgnoreCollapsed();
1808 if (cur.inset().lyxCode() == INDEX_CODE)
1810 else if (cur.prevInset() && cur.prevInset()->lyxCode() == INDEX_CODE)
1811 cur.backwardPosIgnoreCollapsed();
1815 if (!cur.inTexted()) {
1816 // Nothing to do here.
1817 setCursorFromInset(ins);
1820 // Get word or selection
1821 cur.text()->selectWord(cur, WHOLE_WORD);
1822 docstring const searched_string = cur.selectionAsString(false);
1823 if (searched_string.empty())
1825 // Start from the beginning
1826 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
1827 while (findOne(this, searched_string,
1828 false,// case sensitive
1829 true,// match whole word only
1831 false,//find deleted
1835 false// only selection
1837 cur.clearSelection();
1838 Inset * ains = cur.nextInset();
1839 if (ains && ains->lyxCode() == INDEX_CODE) {
1840 // We have an index inset.
1841 // Check whether it has the same
1842 // LaTeX content and move on if so.
1843 odocstringstream filatex;
1844 otexstream fits(filatex);
1845 ains->latex(fits, rp);
1846 if (oilatex.str() == filatex.str())
1849 // Paste the inset and possibly continue
1850 cap::pasteFromTemp(cursor(), cursor().buffer()->errorList("Paste"));
1852 // Go back to start position.
1853 setCursorFromInset(ins);
1854 dr.screenUpdate(cur.result().screenUpdate());
1855 if (cur.result().needBufferUpdate())
1856 dr.forceBufferUpdate();
1861 cur.clearSelection();
1862 dr.setMessage(from_utf8(N_("Mark off")));
1866 cur.clearSelection();
1868 dr.setMessage(from_utf8(N_("Mark on")));
1871 case LFUN_MARK_TOGGLE:
1872 cur.selection(false);
1875 dr.setMessage(from_utf8(N_("Mark removed")));
1878 dr.setMessage(from_utf8(N_("Mark set")));
1883 case LFUN_SCREEN_SHOW_CURSOR:
1887 case LFUN_SCREEN_RECENTER:
1891 case LFUN_BIBTEX_DATABASE_ADD: {
1892 Cursor tmpcur = cur;
1893 findInset(tmpcur, { BIBTEX_CODE }, false);
1894 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1897 if (inset->addDatabase(cmd.argument()))
1898 dr.forceBufferUpdate();
1903 case LFUN_BIBTEX_DATABASE_DEL: {
1904 Cursor tmpcur = cur;
1905 findInset(tmpcur, { BIBTEX_CODE }, false);
1906 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1909 if (inset->delDatabase(cmd.argument()))
1910 dr.forceBufferUpdate();
1915 case LFUN_GRAPHICS_UNIFY: {
1917 cur.recordUndoFullBuffer();
1919 DocIterator from, to;
1920 from = cur.selectionBegin();
1921 to = cur.selectionEnd();
1923 string const newId = cmd.getArg(0);
1924 bool fetchId = newId.empty(); //if we wait for groupId from first graphics inset
1926 InsetGraphicsParams grp_par;
1928 InsetGraphics::string2params(graphics::getGroupParams(buffer_, newId), buffer_, grp_par);
1930 if (!from.nextInset()) //move to closest inset
1931 from.forwardInset();
1933 while (!from.empty() && from < to) {
1934 Inset * inset = from.nextInset();
1937 InsetGraphics * ig = inset->asInsetGraphics();
1939 InsetGraphicsParams inspar = ig->getParams();
1944 grp_par.filename = inspar.filename;
1945 ig->setParams(grp_par);
1948 from.forwardInset();
1950 dr.screenUpdate(Update::Force); //needed if triggered from context menu
1954 case LFUN_BIBTEX_DATABASE_LIST: {
1955 docstring_list const & files = buffer_.getBibfiles();
1958 char const separator(os::path_separator());
1959 for (auto const & file : files) {
1963 result += separator;
1965 FileName const fn = buffer_.getBibfilePath(file);
1966 string const path = fn.realPath();
1967 result += from_utf8(os::external_path(path));
1969 dr.setMessage(result);
1973 case LFUN_STATISTICS: {
1974 DocIterator from, to;
1975 if (cur.selection()) {
1976 from = cur.selectionBegin();
1977 to = cur.selectionEnd();
1979 from = doc_iterator_begin(&buffer_);
1980 to = doc_iterator_end(&buffer_);
1982 buffer_.updateStatistics(from, to);
1983 int const words = buffer_.wordCount();
1984 int const chars = buffer_.charCount(false);
1985 int const chars_blanks = buffer_.charCount(true);
1987 if (cur.selection())
1988 message = _("Statistics for the selection:");
1990 message = _("Statistics for the document:");
1993 message += bformat(_("%1$d words"), words);
1995 message += _("One word");
1997 if (chars_blanks != 1)
1998 message += bformat(_("%1$d characters"), chars_blanks);
2000 message += _("One character");
2003 message += bformat(_("%1$d characters (no blanks)"), chars);
2005 message += _("One character (no blanks)");
2007 Alert::information(_("Statistics"), message);
2011 case LFUN_SCREEN_UP:
2012 case LFUN_SCREEN_DOWN: {
2013 Point p = getPos(cur);
2014 // This code has been commented out to enable to scroll down a
2015 // document, even if there are large insets in it (see bug #5465).
2016 /*if (p.y_ < 0 || p.y_ > height_) {
2017 // The cursor is off-screen so recenter before proceeding.
2021 int const scrolled = scroll(act == LFUN_SCREEN_UP
2022 ? -height_ : height_);
2023 if (act == LFUN_SCREEN_UP && scrolled > -height_)
2025 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
2026 p = Point(width_, height_);
2027 bool const in_texted = cur.inTexted();
2028 cur.setCursor(doc_iterator_begin(cur.buffer()));
2029 cur.selHandle(false);
2030 // Force an immediate computation of metrics because we need it below
2032 processUpdateFlags(Update::Force);
2034 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
2035 true, act == LFUN_SCREEN_UP);
2036 //FIXME: what to do with cur.x_target()?
2037 bool update = in_texted && cur.bv().checkDepm(cur, old);
2040 if (update || cur.mark())
2041 dr.screenUpdate(Update::Force | Update::FitCursor);
2043 dr.forceBufferUpdate();
2048 string const scroll_type = cmd.getArg(0);
2049 int scroll_step = 0;
2050 if (scroll_type == "line")
2051 scroll_step = d->scrollbarParameters_.single_step;
2052 else if (scroll_type == "page")
2053 scroll_step = d->scrollbarParameters_.page_step;
2056 string const scroll_quantity = cmd.getArg(1);
2057 if (scroll_quantity == "up")
2058 scrollUp(scroll_step);
2059 else if (scroll_quantity == "down")
2060 scrollDown(scroll_step);
2062 int const scroll_value = convert<int>(scroll_quantity);
2064 scroll(scroll_step * scroll_value);
2066 dr.screenUpdate(Update::ForceDraw);
2067 dr.forceBufferUpdate();
2071 case LFUN_SCREEN_UP_SELECT: {
2072 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
2073 cur.selHandle(true);
2074 if (isTopScreen()) {
2075 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
2079 int y = getPos(cur).y_;
2080 int const ymin = y - height_ + defaultRowHeight();
2081 while (y > ymin && cur.up())
2085 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
2089 case LFUN_SCREEN_DOWN_SELECT: {
2090 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
2091 cur.selHandle(true);
2092 if (isBottomScreen()) {
2093 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
2097 int y = getPos(cur).y_;
2098 int const ymax = y + height_ - defaultRowHeight();
2099 while (y < ymax && cur.down())
2103 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
2108 case LFUN_INSET_SELECT_ALL: {
2109 // true if all cells are selected
2110 bool const all_selected = cur.depth() > 1
2111 && cur.selBegin().at_begin()
2112 && cur.selEnd().at_end();
2113 // true if some cells are selected
2114 bool const cells_selected = cur.depth() > 1
2115 && cur.selBegin().at_cell_begin()
2116 && cur.selEnd().at_cell_end();
2117 if (all_selected || (cells_selected && !cur.inset().isTable())) {
2118 // All the contents of the inset if selected, or only at
2119 // least one cell but inset is not a table.
2120 // Select the inset from outside.
2123 cur.selection(true);
2125 } else if (cells_selected) {
2126 // At least one complete cell is selected and inset is a table.
2132 cur.selection(true);
2133 cur.idx() = cur.lastidx();
2134 cur.pit() = cur.lastpit();
2135 cur.pos() = cur.lastpos();
2137 // select current cell
2141 cur.selection(true);
2142 cur.pit() = cur.lastpit();
2143 cur.pos() = cur.lastpos();
2145 cur.setCurrentFont();
2146 dr.screenUpdate(Update::Force);
2151 case LFUN_UNICODE_INSERT: {
2152 if (cmd.argument().empty())
2155 FuncCode code = cur.inset().currentMode() == Inset::MATH_MODE ?
2156 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
2159 docstring const arg = from_utf8(cmd.getArg(i));
2163 LYXERR0("Not a hexstring: " << arg);
2167 char_type c = hexToInt(arg);
2168 if (c >= 32 && c < 0x10ffff) {
2169 LYXERR(Debug::KEY, "Inserting c: " << c);
2170 lyx::dispatch(FuncRequest(code, docstring(1, c)));
2178 // This would be in Buffer class if only Cursor did not
2179 // require a bufferview
2180 case LFUN_INSET_FORALL: {
2181 docstring const name = from_utf8(cmd.getArg(0));
2182 string const commandstr = cmd.getLongArg(1);
2183 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
2185 // an arbitrary number to limit number of iterations
2186 const int max_iter = 100000;
2188 Cursor & bvcur = d->cursor_;
2189 Cursor const savecur = bvcur;
2191 if (!bvcur.nextInset())
2192 bvcur.forwardInset();
2193 bvcur.beginUndoGroup();
2194 while(bvcur && iterations < max_iter) {
2195 Inset * const ins = bvcur.nextInset();
2198 docstring insname = ins->layoutName();
2199 while (!insname.empty()) {
2200 if (insname == name || name == from_utf8("*")) {
2201 lyx::dispatch(fr, dr);
2202 // we do not want to remember selection here
2203 bvcur.clearSelection();
2207 size_t const i = insname.rfind(':');
2208 if (i == string::npos)
2210 insname = insname.substr(0, i);
2212 // if we did not delete the inset, skip it
2213 if (!bvcur.nextInset() || bvcur.nextInset() == ins)
2214 bvcur.forwardInset();
2217 bvcur.fixIfBroken();
2218 /** This is a dummy undo record only to remember the cursor
2219 * that has just been set; this will be used on a redo action
2220 * (see ticket #10097)
2222 * FIXME: a better fix would be to have a way to set the
2223 * cursor value directly, but I am not sure it is worth it.
2226 bvcur.endUndoGroup();
2227 dr.screenUpdate(Update::Force);
2228 dr.forceBufferUpdate();
2230 if (iterations >= max_iter) {
2232 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
2234 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
2239 case LFUN_BRANCH_ADD_INSERT: {
2240 docstring branch_name = from_utf8(cmd.getArg(0));
2241 if (branch_name.empty())
2242 if (!Alert::askForText(branch_name, _("Branch name")) ||
2243 branch_name.empty())
2246 DispatchResult drtmp;
2247 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
2248 if (drtmp.error()) {
2249 Alert::warning(_("Branch already exists"), drtmp.message());
2252 docstring const sep = buffer_.params().branchlist().separator();
2253 for (docstring const & branch : getVectorFromString(branch_name, sep))
2254 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch));
2258 case LFUN_KEYMAP_OFF:
2259 getIntl().keyMapOn(false);
2262 case LFUN_KEYMAP_PRIMARY:
2263 getIntl().keyMapPrim();
2266 case LFUN_KEYMAP_SECONDARY:
2267 getIntl().keyMapSec();
2270 case LFUN_KEYMAP_TOGGLE:
2271 getIntl().toggleKeyMap();
2274 case LFUN_DIALOG_SHOW_NEW_INSET: {
2275 string const name = cmd.getArg(0);
2276 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2277 if (decodeInsetParam(name, data, buffer_))
2278 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
2280 lyxerr << "Inset type '" << name <<
2281 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
2285 case LFUN_CITATION_INSERT: {
2286 if (argument.empty()) {
2287 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
2290 // we can have one optional argument, delimited by '|'
2291 // citation-insert <key>|<text_before>
2292 // this should be enhanced to also support text_after
2293 // and citation style
2294 string arg = argument;
2296 if (contains(argument, "|")) {
2297 arg = token(argument, '|', 0);
2298 opt1 = token(argument, '|', 1);
2301 // if our cursor is directly in front of or behind a citation inset,
2302 // we will instead add the new key to it.
2303 Inset * inset = cur.nextInset();
2304 if (!inset || inset->lyxCode() != CITE_CODE)
2305 inset = cur.prevInset();
2306 if (inset && inset->lyxCode() == CITE_CODE) {
2307 InsetCitation * icite = static_cast<InsetCitation *>(inset);
2308 if (icite->addKey(arg)) {
2309 dr.forceBufferUpdate();
2310 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
2312 LYXERR0("Discarding optional argument to citation-insert.");
2317 InsetCommandParams icp(CITE_CODE);
2318 icp["key"] = from_utf8(arg);
2320 icp["before"] = from_utf8(opt1);
2322 from_ascii(InsetCitation::last_literal ? "true" : "false");
2323 string icstr = InsetCommand::params2string(icp);
2324 FuncRequest fr(LFUN_INSET_INSERT, icstr);
2327 // if the request comes from the LyX server, then we
2328 // return a list of the undefined keys, in case some
2329 // action could be taken.
2330 if (cmd.origin() != FuncRequest::LYXSERVER)
2333 vector<docstring> keys = getVectorFromString(from_utf8(arg));
2334 vector<docstring>::iterator it = keys.begin();
2335 vector<docstring>::const_iterator end = keys.end();
2337 BiblioInfo const & bibInfo = buffer_.masterBibInfo();
2338 const BiblioInfo::const_iterator bibEnd = bibInfo.end();
2340 if (bibInfo.find(*it) != bibEnd) {
2341 it = keys.erase(it);
2346 dr.setMessage(getStringFromVector(keys));
2351 case LFUN_INSET_APPLY: {
2352 string const name = cmd.getArg(0);
2353 Inset * inset = editedInset(name);
2355 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2359 // put cursor in front of inset.
2360 if (!setCursorFromInset(inset)) {
2361 LASSERT(false, break);
2364 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2365 inset->dispatch(cur, fr);
2366 dr.screenUpdate(cur.result().screenUpdate());
2367 if (cur.result().needBufferUpdate())
2368 dr.forceBufferUpdate();
2373 // The change of language of buffer belongs to the Buffer class.
2374 // We have to do it here because we need a cursor for Undo.
2375 // When Undo::recordUndoBufferParams() is implemented someday
2376 // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
2377 case LFUN_BUFFER_LANGUAGE: {
2378 Language const * oldL = buffer_.params().language;
2379 Language const * newL = languages.getLanguage(argument);
2380 if (!newL || oldL == newL)
2382 if (oldL->rightToLeft() == newL->rightToLeft()) {
2383 cur.recordUndoFullBuffer();
2384 buffer_.changeLanguage(oldL, newL);
2385 cur.setCurrentFont();
2386 dr.forceBufferUpdate();
2391 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2392 case LFUN_FILE_INSERT_PLAINTEXT: {
2393 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
2394 string const fname = to_utf8(cmd.argument());
2395 if (!FileName::isAbsolute(fname))
2396 dr.setMessage(_("Absolute filename expected."));
2398 insertPlaintextFile(FileName(fname), as_paragraph);
2403 // With multi-cell table content, we pass down to the inset
2404 if (cur.inTexted() && cur.selection()
2405 && cur.selectionBegin().idx() != cur.selectionEnd().idx()) {
2406 buffer_.dispatch(cmd, dr);
2407 dispatched = dr.dispatched();
2410 cap::copySelection(cur);
2411 cur.message(_("Copy"));
2415 // OK, so try the Buffer itself...
2416 buffer_.dispatch(cmd, dr);
2417 dispatched = dr.dispatched();
2421 buffer_.undo().endUndoGroup();
2422 dr.dispatched(dispatched);
2424 // NOTE: The code below is copied from Cursor::dispatch. If you
2425 // need to modify this, please update the other one too.
2427 // notify insets we just entered/left
2428 if (cursor() != old) {
2429 old.beginUndoGroup();
2431 bool badcursor = notifyCursorLeavesOrEnters(old, cursor());
2433 cursor().fixIfBroken();
2434 resetInlineCompletionPos();
2441 docstring BufferView::requestSelection()
2443 Cursor & cur = d->cursor_;
2445 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2446 if (!cur.selection()) {
2447 d->xsel_cache_.set = false;
2451 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2452 if (!d->xsel_cache_.set ||
2453 cur.top() != d->xsel_cache_.cursor ||
2454 cur.realAnchor().top() != d->xsel_cache_.anchor)
2456 d->xsel_cache_.cursor = cur.top();
2457 d->xsel_cache_.anchor = cur.realAnchor().top();
2458 d->xsel_cache_.set = cur.selection();
2459 return cur.selectionAsString(false);
2465 void BufferView::clearSelection()
2467 d->cursor_.clearSelection();
2468 // Clear the selection buffer. Otherwise a subsequent
2469 // middle-mouse-button paste would use the selection buffer,
2470 // not the more current external selection.
2471 cap::clearSelection();
2472 d->xsel_cache_.set = false;
2473 // The buffer did not really change, but this causes the
2474 // redraw we need because we cleared the selection above.
2475 buffer_.changed(false);
2479 void BufferView::resize(int width, int height)
2481 // Update from work area
2485 // Clear the paragraph height cache.
2486 d->par_height_.clear();
2487 // Redo the metrics.
2492 Inset const * BufferView::getCoveringInset(Text const & text,
2495 TextMetrics & tm = d->text_metrics_[&text];
2496 Inset * inset = tm.checkInsetHit(x, y);
2500 if (!inset->descendable(*this))
2501 // No need to go further down if the inset is not
2505 size_t cell_number = inset->nargs();
2506 // Check all the inner cell.
2507 for (size_t i = 0; i != cell_number; ++i) {
2508 Text const * inner_text = inset->getText(i);
2511 Inset const * inset_deeper =
2512 getCoveringInset(*inner_text, x, y);
2514 return inset_deeper;
2522 Inset const * BufferView::clickableMathInset(InsetMathNest const * inset,
2523 CoordCache::Insets const & inset_cache, int x, int y) const
2525 for (size_t i = 0; i < inset->nargs(); ++i) {
2526 MathData const & ar = inset->cell(i);
2527 for (size_t j = 0; j < ar.size(); ++j) {
2528 string const name = lyxerr.debugging(Debug::MATHED)
2529 ? insetName(ar[j].nucleus()->lyxCode())
2531 LYXERR(Debug::MATHED, "Checking inset: " << name);
2532 if (ar[j].nucleus()->clickable(*this, x, y)) {
2533 if (inset_cache.covers(ar[j].nucleus(), x, y)) {
2534 LYXERR(Debug::MATHED, "Clickable inset: "
2536 return ar[j].nucleus();
2539 InsetMathNest const * imn =
2540 ar[j].nucleus()->asNestInset();
2542 Inset const * inner =
2543 clickableMathInset(imn, inset_cache, x, y);
2553 void BufferView::updateHoveredInset() const
2555 // Get inset under mouse, if there is one.
2556 int const x = d->mouse_position_cache_.x_;
2557 int const y = d->mouse_position_cache_.y_;
2558 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2559 if (covering_inset && covering_inset->asInsetMath()) {
2560 Inset const * inner_inset = clickableMathInset(
2561 covering_inset->asInsetMath()->asNestInset(),
2562 coordCache().getInsets(), x, y);
2564 covering_inset = inner_inset;
2567 d->clickable_inset_ = covering_inset && covering_inset->clickable(*this, x, y);
2569 if (covering_inset == d->last_inset_)
2570 // Same inset, no need to do anything...
2573 bool need_redraw = false;
2574 if (d->last_inset_) {
2575 // Remove the hint on the last hovered inset (if any).
2576 need_redraw |= d->last_inset_->setMouseHover(this, false);
2577 d->last_inset_ = nullptr;
2580 if (covering_inset && covering_inset->setMouseHover(this, true)) {
2582 // Only the insets that accept the hover state, do
2583 // clear the last_inset_, so only set the last_inset_
2584 // member if the hovered setting is accepted.
2585 d->last_inset_ = covering_inset;
2589 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2590 << d->mouse_position_cache_.x_ << ", "
2591 << d->mouse_position_cache_.y_ << ")");
2593 d->update_strategy_ = DecorationUpdate;
2595 // This event (moving without mouse click) is not passed further.
2596 // This should be changed if it is further utilized.
2597 buffer_.changed(false);
2602 void BufferView::clearLastInset(Inset * inset) const
2604 if (d->last_inset_ != inset) {
2605 LYXERR0("Wrong last_inset!");
2608 d->last_inset_ = nullptr;
2612 bool BufferView::mouseSelecting() const
2614 return d->mouse_selecting_;
2618 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2620 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2622 // This is only called for mouse related events including
2623 // LFUN_FILE_OPEN generated by drag-and-drop.
2624 FuncRequest cmd = cmd0;
2626 Cursor old = cursor();
2628 cur.push(buffer_.inset());
2629 cur.selection(d->cursor_.selection());
2631 // Either the inset under the cursor or the
2632 // surrounding Text will handle this event.
2634 // make sure we stay within the screen...
2635 cmd.set_y(min(max(cmd.y(), -1), height_));
2637 d->mouse_position_cache_.x_ = cmd.x();
2638 d->mouse_position_cache_.y_ = cmd.y();
2640 d->mouse_selecting_ =
2641 cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::button1;
2643 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2644 updateHoveredInset();
2648 // Build temporary cursor.
2649 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2651 // If inset is not editable, cur.pos() might point behind the
2652 // inset (depending on cmd.x(), cmd.y()). This is needed for
2653 // editing to fix bug 9628, but e.g. the context menu needs a
2654 // cursor in front of the inset.
2655 if ((inset->hasSettings() || !inset->contextMenuName().empty()
2656 || inset->lyxCode() == SEPARATOR_CODE) &&
2657 cur.nextInset() != inset && cur.prevInset() == inset)
2659 } else if (cur.inTexted() && cur.pos()
2660 && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
2661 // Always place cursor in front of a separator inset.
2665 // Put anchor at the same position.
2668 old.beginUndoGroup();
2670 // Try to dispatch to an non-editable inset near this position
2671 // via the temp cursor. If the inset wishes to change the real
2672 // cursor it has to do so explicitly by using
2673 // cur.bv().cursor() = cur; (or similar)
2675 inset->dispatch(cur, cmd);
2677 // Now dispatch to the temporary cursor. If the real cursor should
2678 // be modified, the inset's dispatch has to do so explicitly.
2679 if (!inset || !cur.result().dispatched())
2682 // Notify left insets
2684 bool badcursor = old.fixIfBroken() || cur.fixIfBroken();
2685 badcursor = badcursor || notifyCursorLeavesOrEnters(old, cur);
2687 cursor().fixIfBroken();
2692 // Do we have a selection?
2693 theSelection().haveSelection(cursor().selection());
2695 if (cur.needBufferUpdate() || buffer().needUpdate()) {
2696 cur.clearBufferUpdate();
2697 buffer().updateBuffer();
2700 // If the command has been dispatched,
2701 if (cur.result().dispatched() || cur.result().screenUpdate())
2702 processUpdateFlags(cur.result().screenUpdate());
2706 int BufferView::minVisiblePart()
2708 return 2 * defaultRowHeight();
2712 int BufferView::scroll(int pixels)
2715 return scrollDown(pixels);
2717 return scrollUp(-pixels);
2722 int BufferView::scrollDown(int pixels)
2724 Text * text = &buffer_.text();
2725 TextMetrics & tm = d->text_metrics_[text];
2726 int const ymax = height_ + pixels;
2728 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2729 int bottom_pos = last.second->position() + last.second->descent();
2730 if (lyxrc.scroll_below_document)
2731 bottom_pos += height_ - minVisiblePart();
2732 if (last.first + 1 == int(text->paragraphs().size())) {
2733 if (bottom_pos <= height_)
2735 pixels = min(pixels, bottom_pos - height_);
2738 if (bottom_pos > ymax)
2740 tm.newParMetricsDown();
2742 d->anchor_ypos_ -= pixels;
2747 int BufferView::scrollUp(int pixels)
2749 Text * text = &buffer_.text();
2750 TextMetrics & tm = d->text_metrics_[text];
2751 int ymin = - pixels;
2753 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2754 int top_pos = first.second->position() - first.second->ascent();
2755 if (first.first == 0) {
2758 pixels = min(pixels, - top_pos);
2763 tm.newParMetricsUp();
2765 d->anchor_ypos_ += pixels;
2770 bool BufferView::setCursorFromRow(int row)
2772 TexRow::TextEntry start, end;
2773 tie(start,end) = buffer_.texrow().getEntriesFromRow(row);
2774 LYXERR(Debug::OUTFILE,
2775 "setCursorFromRow: for row " << row << ", TexRow has found "
2776 "start (id=" << start.id << ",pos=" << start.pos << "), "
2777 "end (id=" << end.id << ",pos=" << end.pos << ")");
2778 return setCursorFromEntries(start, end);
2782 bool BufferView::setCursorFromEntries(TexRow::TextEntry start,
2783 TexRow::TextEntry end)
2785 DocIterator dit_start, dit_end;
2786 tie(dit_start,dit_end) =
2787 TexRow::getDocIteratorsFromEntries(start, end, buffer_);
2790 // Setting selection start
2791 d->cursor_.clearSelection();
2792 setCursor(dit_start);
2793 // Setting selection end
2795 d->cursor_.resetAnchor();
2796 setCursorSelectionTo(dit_end);
2802 bool BufferView::setCursorFromInset(Inset const * inset)
2804 // are we already there?
2805 if (cursor().nextInset() == inset)
2808 // Inset is not at cursor position. Find it in the document.
2811 while (cur && cur.nextInset() != inset)
2822 void BufferView::gotoLabel(docstring const & label)
2825 bool have_inactive = false;
2826 for (Buffer const * buf : buffer().allRelatives()) {
2828 for (TocItem const & item : *buf->tocBackend().toc("label")) {
2829 if (label == item.str() && item.isOutput()) {
2830 lyx::dispatch(item.action());
2833 // If we find an inactive label, save it for the case
2834 // that no active one is there
2835 if (label == item.str() && !have_inactive) {
2836 have_inactive = true;
2837 action = item.action();
2841 // We only found an inactive label. Go there.
2843 lyx::dispatch(action);
2847 TextMetrics const & BufferView::textMetrics(Text const * t) const
2849 return const_cast<BufferView *>(this)->textMetrics(t);
2853 TextMetrics & BufferView::textMetrics(Text const * t)
2856 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2857 if (tmc_it == d->text_metrics_.end()) {
2858 tmc_it = d->text_metrics_.emplace(std::piecewise_construct,
2859 std::forward_as_tuple(t),
2860 std::forward_as_tuple(this, const_cast<Text *>(t))).first;
2862 return tmc_it->second;
2866 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2869 return textMetrics(t).parMetrics(pit);
2873 int BufferView::workHeight() const
2879 void BufferView::setCursor(DocIterator const & dit)
2882 size_t const n = dit.depth();
2883 for (size_t i = 0; i < n; ++i)
2884 dit[i].inset().edit(d->cursor_, true);
2886 d->cursor_.setCursor(dit);
2887 d->cursor_.selection(false);
2888 d->cursor_.setCurrentFont();
2890 // It seems on general grounds as if this is probably needed, but
2891 // it is not yet clear.
2892 // See bug #7394 and r38388.
2893 // d->cursor.resetAnchor();
2897 void BufferView::setCursorSelectionTo(DocIterator const & dit)
2899 size_t const n = dit.depth();
2900 for (size_t i = 0; i < n; ++i)
2901 dit[i].inset().edit(d->cursor_, true);
2903 d->cursor_.selection(true);
2904 d->cursor_.setCursorSelectionTo(dit);
2905 d->cursor_.setCurrentFont();
2909 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2911 // Would be wrong to delete anything if we have a selection.
2912 if (cur.selection())
2915 bool need_anchor_change = false;
2916 bool changed = Text::deleteEmptyParagraphMechanism(cur, old,
2917 need_anchor_change);
2919 if (need_anchor_change)
2927 // we would rather not do this here, but it needs to be done before
2928 // the changed() signal is sent.
2929 buffer_.updateBuffer();
2931 buffer_.changed(true);
2936 bool BufferView::mouseSetCursor(Cursor & cur, bool const select)
2938 LASSERT(&cur.bv() == this, return false);
2941 // this event will clear selection so we save selection for
2942 // persistent selection
2943 cap::saveSelection(cursor());
2945 d->cursor_.macroModeClose();
2946 // If a macro has been finalized, the cursor might have been broken
2949 // Has the cursor just left the inset?
2950 bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2952 d->cursor_.fixIfBroken();
2954 // do the dEPM magic if needed
2955 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2956 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2957 // the leftinset bool would not be necessary (badcursor instead).
2958 bool update = leftinset;
2961 d->cursor_.setSelection();
2962 d->cursor_.setCursorSelectionTo(cur);
2964 if (d->cursor_.inTexted())
2965 update |= checkDepm(cur, d->cursor_);
2966 d->cursor_.resetAnchor();
2967 d->cursor_.setCursor(cur);
2968 d->cursor_.clearSelection();
2970 d->cursor_.boundary(cur.boundary());
2971 d->cursor_.finishUndo();
2972 d->cursor_.setCurrentFont();
2974 cur.forceBufferUpdate();
2979 void BufferView::putSelectionAt(DocIterator const & cur,
2980 int length, bool backwards)
2982 d->cursor_.clearSelection();
2988 d->cursor_.pos() += length;
2989 d->cursor_.setSelection(d->cursor_, -length);
2991 d->cursor_.setSelection(d->cursor_, length);
2996 bool BufferView::selectIfEmpty(DocIterator & cur)
2998 if ((cur.inTexted() && !cur.paragraph().empty())
2999 || (cur.inMathed() && !cur.cell().empty()))
3002 pit_type const beg_pit = cur.pit();
3004 // The paragraph associated to this item isn't
3005 // the first one, so it can be selected
3008 // We have to resort to select the space between the
3009 // end of this item and the begin of the next one
3013 // If it is the only item in the document,
3014 // nothing can be selected
3017 pit_type const end_pit = cur.pit();
3018 pos_type const end_pos = cur.pos();
3019 d->cursor_.clearSelection();
3021 d->cursor_.setCursor(cur);
3022 d->cursor_.pit() = beg_pit;
3023 d->cursor_.pos() = 0;
3024 d->cursor_.selection(false);
3025 d->cursor_.resetAnchor();
3026 d->cursor_.pit() = end_pit;
3027 d->cursor_.pos() = end_pos;
3028 d->cursor_.setSelection();
3033 Cursor & BufferView::cursor()
3039 Cursor const & BufferView::cursor() const
3045 bool BufferView::singleParUpdate()
3047 Text & buftext = buffer_.text();
3048 pit_type const bottom_pit = d->cursor_.bottom().pit();
3049 TextMetrics & tm = textMetrics(&buftext);
3050 Dimension const old_dim = tm.parMetrics(bottom_pit).dim();
3052 // make sure inline completion pointer is ok
3053 if (d->inlineCompletionPos_.fixIfBroken())
3054 d->inlineCompletionPos_ = DocIterator();
3056 // In Single Paragraph mode, rebreak only
3057 // the (main text, not inset!) paragraph containing the cursor.
3058 // (if this paragraph contains insets etc., rebreaking will
3059 // recursively descend)
3060 tm.redoParagraph(bottom_pit);
3061 ParagraphMetrics & pm = tm.parMetrics(bottom_pit);
3062 if (pm.height() != old_dim.height()) {
3063 // Paragraph height has changed so we cannot proceed to
3064 // the singlePar optimisation.
3067 // Since position() points to the baseline of the first row, we
3068 // may have to update it. See ticket #11601 for an example where
3069 // the height does not change but the ascent does.
3070 pm.setPosition(pm.position() - old_dim.ascent() + pm.ascent());
3072 tm.updatePosCache(bottom_pit);
3074 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
3075 << " y2: " << pm.position() + pm.descent()
3076 << " pit: " << bottom_pit
3077 << " singlepar: 1");
3082 void BufferView::updateMetrics()
3084 updateMetrics(d->update_flags_);
3085 d->update_strategy_ = FullScreenUpdate;
3089 void BufferView::updateMetrics(Update::flags & update_flags)
3091 if (height_ == 0 || width_ == 0)
3094 Text & buftext = buffer_.text();
3095 pit_type const npit = int(buftext.paragraphs().size());
3097 // Clear out the position cache in case of full screen redraw,
3098 d->coord_cache_.clear();
3099 d->math_rows_.clear();
3101 // Clear out paragraph metrics to avoid having invalid metrics
3102 // in the cache from paragraphs not relayouted below
3103 // The complete text metrics will be redone.
3104 d->text_metrics_.clear();
3106 TextMetrics & tm = textMetrics(&buftext);
3108 // make sure inline completion pointer is ok
3109 if (d->inlineCompletionPos_.fixIfBroken())
3110 d->inlineCompletionPos_ = DocIterator();
3112 if (d->anchor_pit_ >= npit)
3113 // The anchor pit must have been deleted...
3114 d->anchor_pit_ = npit - 1;
3116 // Rebreak anchor paragraph.
3117 tm.redoParagraph(d->anchor_pit_);
3118 ParagraphMetrics & anchor_pm = tm.parMetrics(d->anchor_pit_);
3121 if (d->anchor_pit_ == 0) {
3122 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
3124 // Complete buffer visible? Then it's easy.
3125 if (scrollRange == 0)
3126 d->anchor_ypos_ = anchor_pm.ascent();
3128 // avoid empty space above the first row
3129 d->anchor_ypos_ = min(d->anchor_ypos_, anchor_pm.ascent());
3132 anchor_pm.setPosition(d->anchor_ypos_);
3133 tm.updatePosCache(d->anchor_pit_);
3135 LYXERR(Debug::PAINTING, "metrics: "
3136 << " anchor pit = " << d->anchor_pit_
3137 << " anchor ypos = " << d->anchor_ypos_);
3139 // Redo paragraphs above anchor if necessary.
3140 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
3141 // We are now just above the anchor paragraph.
3142 pit_type pit1 = d->anchor_pit_ - 1;
3143 for (; pit1 >= 0 && y1 >= 0; --pit1) {
3144 tm.redoParagraph(pit1);
3145 ParagraphMetrics & pm = tm.parMetrics(pit1);
3147 // Save the paragraph position in the cache.
3149 tm.updatePosCache(pit1);
3153 // Redo paragraphs below the anchor if necessary.
3154 int y2 = d->anchor_ypos_ + anchor_pm.descent();
3155 // We are now just below the anchor paragraph.
3156 pit_type pit2 = d->anchor_pit_ + 1;
3157 for (; pit2 < npit && y2 <= height_; ++pit2) {
3158 tm.redoParagraph(pit2);
3159 ParagraphMetrics & pm = tm.parMetrics(pit2);
3161 // Save the paragraph position in the cache.
3163 tm.updatePosCache(pit2);
3167 LYXERR(Debug::PAINTING, "Metrics: "
3168 << " anchor pit = " << d->anchor_pit_
3169 << " anchor ypos = " << d->anchor_ypos_
3172 << " pit1 = " << pit1
3173 << " pit2 = " << pit2);
3175 // metrics is done, full drawing is necessary now
3176 update_flags = (update_flags & ~Update::Force) | Update::ForceDraw;
3178 // Now update the positions of insets in the cache.
3181 if (lyxerr.debugging(Debug::WORKAREA)) {
3182 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
3183 d->coord_cache_.dump();
3188 void BufferView::updatePosCache()
3190 // this is the "nodraw" drawing stage: only set the positions of the
3191 // insets in metrics cache.
3192 frontend::NullPainter np;
3197 void BufferView::insertLyXFile(FileName const & fname, bool const ignorelang)
3199 LASSERT(d->cursor_.inTexted(), return);
3201 // Get absolute path of file and add ".lyx"
3202 // to the filename if necessary
3203 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
3205 docstring const disp_fn = makeDisplayPath(filename.absFileName());
3206 // emit message signal.
3207 message(bformat(_("Inserting document %1$s..."), disp_fn));
3210 Buffer buf(filename.absFileName(), false);
3211 if (buf.loadLyXFile() == Buffer::ReadSuccess) {
3212 ErrorList & el = buffer_.errorList("Parse");
3213 // Copy the inserted document error list into the current buffer one.
3214 el = buf.errorList("Parse");
3215 ParagraphList & pars = buf.paragraphs();
3217 // set main language of imported file to context language
3218 buf.changeLanguage(buf.language(), d->cursor_.getFont().language());
3219 buffer_.undo().recordUndo(d->cursor_);
3220 cap::replaceSelection(d->cursor_);
3221 cap::pasteParagraphList(d->cursor_, pars,
3222 buf.params().documentClassPtr(),
3223 buf.params().authors(), el);
3224 res = _("Document %1$s inserted.");
3226 res = _("Could not insert document %1$s");
3229 buffer_.changed(true);
3230 // emit message signal.
3231 message(bformat(res, disp_fn));
3235 Point BufferView::coordOffset(DocIterator const & dit) const
3241 // Addup contribution of nested insets, from inside to outside,
3242 // keeping the outer paragraph for a special handling below
3243 for (size_t i = dit.depth() - 1; i >= 1; --i) {
3244 CursorSlice const & sl = dit[i];
3248 // get relative position inside sl.inset()
3249 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
3251 // Make relative position inside of the edited inset relative to sl.inset()
3255 // In case of an RTL inset, the edited inset will be positioned to the left
3258 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
3259 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
3264 // remember width for the case that sl.inset() is positioned in an RTL inset
3265 lastw = sl.inset().dimension(*this).wid;
3267 //lyxerr << "Cursor::getPos, i: "
3268 // << i << " x: " << xx << " y: " << y << endl;
3271 // Add contribution of initial rows of outermost paragraph
3272 CursorSlice const & sl = dit[0];
3273 TextMetrics const & tm = textMetrics(sl.text());
3274 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
3276 LBUFERR(!pm.rows().empty());
3277 y -= pm.rows()[0].ascent();
3279 // FIXME: document this mess
3281 if (sl.pos() > 0 && dit.depth() == 1) {
3283 if (pos && dit.boundary())
3285 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
3286 rend = pm.pos2row(pos);
3288 rend = pm.pos2row(sl.pos());
3290 size_t rend = pm.pos2row(sl.pos());
3292 for (size_t rit = 0; rit != rend; ++rit)
3293 y += pm.rows()[rit].height();
3294 y += pm.rows()[rend].ascent();
3296 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
3298 // Make relative position from the nested inset now bufferview absolute.
3299 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
3302 // In the RTL case place the nested inset at the left of the cursor in
3303 // the outer paragraph
3304 bool boundary_1 = dit.boundary() && 1 == dit.depth();
3305 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
3313 Point BufferView::getPos(DocIterator const & dit) const
3315 if (!paragraphVisible(dit))
3316 return Point(-1, -1);
3318 CursorSlice const & bot = dit.bottom();
3319 TextMetrics const & tm = textMetrics(bot.text());
3321 // offset from outer paragraph
3322 Point p = coordOffset(dit);
3323 p.y_ += tm.parMetrics(bot.pit()).position();
3328 bool BufferView::paragraphVisible(DocIterator const & dit) const
3330 CursorSlice const & bot = dit.bottom();
3331 TextMetrics const & tm = textMetrics(bot.text());
3333 return tm.contains(bot.pit());
3337 void BufferView::caretPosAndDim(Point & p, Dimension & dim) const
3339 Cursor const & cur = cursor();
3340 if (cur.inMathed() && hasMathRow(&cur.cell())) {
3341 MathRow const & mrow = mathRow(&cur.cell());
3342 dim = mrow.caret_dim;
3344 Font const font = cur.real_current_font;
3345 frontend::FontMetrics const & fm = theFontMetrics(font);
3346 // lineWidth() can be 0 to mean 'thin line' on HiDpi, but the
3347 // caret drawing code is not prepared for that.
3348 dim.wid = max(fm.lineWidth(), 1);
3349 dim.asc = fm.maxAscent();
3350 dim.des = fm.maxDescent();
3352 if (lyxrc.cursor_width > 0)
3353 dim.wid = lyxrc.cursor_width;
3356 // center fat carets horizontally
3357 p.x_ -= dim.wid / 2;
3363 void BufferView::buildCaretGeometry(bool complet)
3367 caretPosAndDim(p, dim);
3369 Cursor const & cur = d->cursor_;
3370 Font const & realfont = cur.real_current_font;
3371 frontend::FontMetrics const & fm = theFontMetrics(realfont.fontInfo());
3372 bool const isrtl = realfont.isVisibleRightToLeft();
3373 int const dir = isrtl ? -1 : 1;
3375 frontend::CaretGeometry & cg = d->caret_geometry_;
3378 // The caret itself, slanted for italics in text edit mode except
3379 // for selections because the selection rect does not slant
3380 bool const slant = fm.italic() && cur.inTexted() && !cur.selection();
3381 double const slope = slant ? fm.italicSlope() : 0;
3382 cg.shapes.push_back(
3383 {{iround(p.x_ + dim.asc * slope), p.y_},
3384 {iround(p.x_ - dim.des * slope), p.y_ + dim.height()},
3385 {iround(p.x_ + dir * dim.wid - dim.des * slope), p.y_ + dim.height()},
3386 {iround(p.x_ + dir * dim.wid + dim.asc * slope), p.y_}}
3389 // The language indicator _| (if needed)
3390 Language const * doclang = buffer().params().language;
3391 if (!((realfont.language() == doclang && isrtl == doclang->rightToLeft())
3392 || realfont.language() == latex_language)) {
3393 int const lx = dim.height() / 3;
3394 int const xx = iround(p.x_ - dim.des * slope);
3395 int const yy = p.y_ + dim.height();
3396 cg.shapes.push_back(
3397 {{xx, yy - dim.wid},
3398 {xx + dir * (dim.wid + lx - 1), yy - dim.wid},
3399 {xx + dir * (dim.wid + lx - 1), yy},
3404 // The completion triangle |> (if needed)
3406 int const m = p.y_ + dim.height() / 2;
3407 int const d = dim.height() / 8;
3408 // offset for slanted carret
3409 int const sx = iround((dim.asc - (dim.height() / 2 - d)) * slope);
3410 // starting position x
3411 int const xx = p.x_ + dir * dim.wid + sx;
3412 cg.shapes.push_back(
3416 {xx, m + d - dim.wid},
3417 {xx + dir * d - dim.wid, m},
3418 {xx, m - d + dim.wid}}
3422 // compute extremal x values
3424 cg.right = -1000000;
3426 cg.bottom = -1000000;
3427 for (auto const & shape : cg.shapes)
3428 for (Point const & p : shape) {
3429 cg.left = min(cg.left, p.x_);
3430 cg.right = max(cg.right, p.x_);
3431 cg.top = min(cg.top, p.y_);
3432 cg.bottom = max(cg.bottom, p.y_);
3437 frontend::CaretGeometry const & BufferView::caretGeometry() const
3439 return d->caret_geometry_;
3443 bool BufferView::caretInView() const
3445 if (!paragraphVisible(cursor()))
3449 caretPosAndDim(p, dim);
3451 // does the cursor touch the screen ?
3452 if (p.y_ + dim.height() < 0 || p.y_ >= workHeight())
3458 int BufferView::horizScrollOffset() const
3460 return d->horiz_scroll_offset_;
3464 int BufferView::horizScrollOffset(Text const * text,
3465 pit_type pit, pos_type pos) const
3467 // Is this a row that is currently scrolled?
3468 if (!d->current_row_slice_.empty()
3469 && &text->inset() == d->current_row_slice_.inset().asInsetText()
3470 && pit == d->current_row_slice_.pit()
3471 && pos == d->current_row_slice_.pos())
3472 return d->horiz_scroll_offset_;
3477 void BufferView::setCurrentRowSlice(CursorSlice const & rowSlice)
3479 // nothing to do if the cursor was already on this row
3480 if (d->current_row_slice_ == rowSlice)
3483 // if the (previous) current row was scrolled, we have to
3484 // remember it in order to repaint it next time.
3485 if (d->horiz_scroll_offset_ != 0) {
3486 // search the old row in cache and mark it changed
3487 for (auto & tm_pair : d->text_metrics_) {
3488 if (&tm_pair.first->inset() == rowSlice.inset().asInsetText()) {
3489 tm_pair.second.setRowChanged(rowSlice.pit(), rowSlice.pos());
3490 // We found it, no need to continue.
3496 // Since we changed row, the scroll offset is not valid anymore
3497 d->horiz_scroll_offset_ = 0;
3498 d->current_row_slice_ = rowSlice;
3502 void BufferView::checkCursorScrollOffset()
3504 CursorSlice rowSlice = d->cursor_.bottom();
3505 TextMetrics const & tm = textMetrics(rowSlice.text());
3507 // Stop if metrics have not been computed yet, since it means
3508 // that there is nothing to do.
3509 if (!tm.contains(rowSlice.pit()))
3511 ParagraphMetrics const & pm = tm.parMetrics(rowSlice.pit());
3512 Row const & row = pm.getRow(rowSlice.pos(),
3513 d->cursor_.boundary() && rowSlice == d->cursor_.top());
3514 rowSlice.pos() = row.pos();
3516 // Set the row on which the cursor lives.
3517 setCurrentRowSlice(rowSlice);
3519 // Current x position of the cursor in pixels
3520 int cur_x = getPos(d->cursor_).x_;
3522 // Horizontal scroll offset of the cursor row in pixels
3523 int offset = d->horiz_scroll_offset_;
3524 int const MARGIN = 2 * theFontMetrics(d->cursor_.real_current_font).em()
3526 if (row.right_x() <= workWidth() - row.right_margin) {
3527 // Row is narrower than the work area, no offset needed.
3530 if (cur_x - offset < MARGIN) {
3531 // cursor would be too far right
3532 offset = cur_x - MARGIN;
3533 } else if (cur_x - offset > workWidth() - MARGIN) {
3534 // cursor would be too far left
3535 offset = cur_x - workWidth() + MARGIN;
3537 // Correct the offset to make sure that we do not scroll too much
3540 if (row.right_x() - offset < workWidth() - row.right_margin)
3541 offset = row.right_x() - workWidth() + row.right_margin;
3544 //lyxerr << "cur_x=" << cur_x << ", offset=" << offset << ", row.wid=" << row.width() << ", margin=" << MARGIN << endl;
3546 if (offset != d->horiz_scroll_offset_) {
3547 LYXERR(Debug::PAINTING, "Horiz. scroll offset changed from "
3548 << d->horiz_scroll_offset_ << " to " << offset);
3550 if (d->update_strategy_ == NoScreenUpdate)
3551 d->update_strategy_ = SingleParUpdate;
3554 d->horiz_scroll_offset_ = offset;
3558 bool BufferView::busy() const
3560 return buffer().undo().activeUndoGroup();
3564 void BufferView::draw(frontend::Painter & pain, bool paint_caret)
3566 if (height_ == 0 || width_ == 0)
3568 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t--- START NODRAW ---"
3569 : "\t\t*** START DRAWING ***"));
3570 Text & text = buffer_.text();
3571 TextMetrics const & tm = d->text_metrics_[&text];
3572 int const y = tm.first().second->position();
3573 PainterInfo pi(this, pain);
3575 // Check whether the row where the cursor lives needs to be scrolled.
3576 // Update the drawing strategy if needed.
3577 checkCursorScrollOffset();
3579 switch (d->update_strategy_) {
3581 case NoScreenUpdate:
3582 // no screen painting is actually needed. In nodraw stage
3583 // however, the different coordinates of insets and paragraphs
3584 // needs to be updated.
3585 LYXERR(Debug::PAINTING, "Strategy: NoScreenUpdate");
3586 if (pain.isNull()) {
3587 pi.full_repaint = true;
3590 pi.full_repaint = false;
3595 case SingleParUpdate:
3596 pi.full_repaint = false;
3597 LYXERR(Debug::PAINTING, "Strategy: SingleParUpdate");
3598 // In general, only the current row of the outermost paragraph
3599 // will be redrawn. Particular cases where selection spans
3600 // multiple paragraph are correctly detected in TextMetrics.
3604 case DecorationUpdate:
3605 // FIXME: We should also distinguish DecorationUpdate to avoid text
3606 // drawing if possible. This is not possible to do easily right now
3607 // because of the single backing pixmap.
3609 case FullScreenUpdate:
3611 LYXERR(Debug::PAINTING,
3612 ((d->update_strategy_ == FullScreenUpdate)
3613 ? "Strategy: FullScreenUpdate"
3614 : "Strategy: DecorationUpdate"));
3616 // The whole screen, including insets, will be refreshed.
3617 pi.full_repaint = true;
3619 // Clear background.
3620 pain.fillRectangle(0, 0, width_, height_,
3621 pi.backgroundColor(&buffer_.inset()));
3626 // and possibly grey out below
3627 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3628 int const y2 = lastpm.second->position() + lastpm.second->descent();
3631 Color color = buffer().isInternal()
3632 ? Color_background : Color_bottomarea;
3633 pain.fillRectangle(0, y2, width_, height_ - y2, color);
3637 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t --- END NODRAW ---"
3638 : "\t\t *** END DRAWING ***"));
3640 // The scrollbar needs an update.
3641 // FIXME: does it always? see ticket #11947.
3642 updateScrollbarParameters();
3644 // Normalize anchor for next time
3645 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
3646 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3647 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
3648 ParagraphMetrics const & pm = tm.parMetrics(pit);
3649 if (pm.position() + pm.descent() > 0) {
3650 if (d->anchor_pit_ != pit
3651 || d->anchor_ypos_ != pm.position())
3652 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
3653 << " anchor ypos = " << d->anchor_ypos_);
3654 d->anchor_pit_ = pit;
3655 d->anchor_ypos_ = pm.position();
3659 if (!pain.isNull()) {
3660 // reset the update flags, everything has been done
3661 d->update_flags_ = Update::None;
3664 // If a caret has to be painted, mark its text row as dirty to
3665 //make sure that it will be repainted on next redraw.
3666 /* FIXME: investigate whether this can be avoided when the cursor did not
3670 Cursor cur(d->cursor_);
3671 while (cur.depth() > 1) {
3672 if (!cur.inTexted())
3674 TextMetrics const & tm = textMetrics(cur.text());
3675 if (d->caret_geometry_.left >= tm.origin().x_
3676 && d->caret_geometry_.right <= tm.origin().x_ + tm.dim().width())
3680 cur.textRow().changed(true);
3685 void BufferView::message(docstring const & msg)
3688 d->gui_->message(msg);
3692 void BufferView::showDialog(string const & name)
3695 d->gui_->showDialog(name, string());
3699 void BufferView::showDialog(string const & name,
3700 string const & data, Inset * inset)
3703 d->gui_->showDialog(name, data, inset);
3707 void BufferView::updateDialog(string const & name, string const & data)
3710 d->gui_->updateDialog(name, data);
3714 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
3720 // FIXME: Move this out of BufferView again
3721 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
3723 if (!fname.isReadableFile()) {
3724 docstring const error = from_ascii(strerror(errno));
3725 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3726 docstring const text =
3727 bformat(_("Could not read the specified document\n"
3728 "%1$s\ndue to the error: %2$s"), file, error);
3729 Alert::error(_("Could not read file"), text);
3733 if (!fname.isReadableFile()) {
3734 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3735 docstring const text =
3736 bformat(_("%1$s\n is not readable."), file);
3737 Alert::error(_("Could not open file"), text);
3741 // FIXME UNICODE: We don't know the encoding of the file
3742 docstring file_content = fname.fileContents("UTF-8");
3743 if (file_content.empty()) {
3744 Alert::error(_("Reading not UTF-8 encoded file"),
3745 _("The file is not UTF-8 encoded.\n"
3746 "It will be read as local 8Bit-encoded.\n"
3747 "If this does not give the correct result\n"
3748 "then please change the encoding of the file\n"
3749 "to UTF-8 with a program other than LyX.\n"));
3750 file_content = fname.fileContents("local8bit");
3753 return normalize_c(file_content);
3757 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
3759 docstring const tmpstr = contentsOfPlaintextFile(f);
3764 Cursor & cur = cursor();
3765 cap::replaceSelection(cur);
3766 buffer_.undo().recordUndo(cur);
3768 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3770 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3772 buffer_.changed(true);
3776 docstring const & BufferView::inlineCompletion() const
3778 return d->inlineCompletion_;
3782 size_t BufferView::inlineCompletionUniqueChars() const
3784 return d->inlineCompletionUniqueChars_;
3788 DocIterator const & BufferView::inlineCompletionPos() const
3790 return d->inlineCompletionPos_;
3794 void BufferView::resetInlineCompletionPos()
3796 d->inlineCompletionPos_ = DocIterator();
3800 bool samePar(DocIterator const & a, DocIterator const & b)
3802 if (a.empty() && b.empty())
3804 if (a.empty() || b.empty())
3806 if (a.depth() != b.depth())
3808 return &a.innerParagraph() == &b.innerParagraph();
3812 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3813 docstring const & completion, size_t uniqueChars)
3815 uniqueChars = min(completion.size(), uniqueChars);
3816 bool changed = d->inlineCompletion_ != completion
3817 || d->inlineCompletionUniqueChars_ != uniqueChars;
3818 bool singlePar = true;
3819 d->inlineCompletion_ = completion;
3820 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3822 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3825 DocIterator const & old = d->inlineCompletionPos_;
3827 //lyxerr << "inlineCompletionPos changed" << std::endl;
3828 // old or pos are in another paragraph?
3829 if ((!samePar(cur, pos) && !pos.empty())
3830 || (!samePar(cur, old) && !old.empty())) {
3832 //lyxerr << "different paragraph" << std::endl;
3834 d->inlineCompletionPos_ = pos;
3839 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3840 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3842 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3847 bool BufferView::clickableInset() const
3849 return d->clickable_inset_;