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 "buffer_funcs.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "CoordCache.h"
26 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
34 #include "InsetIterator.h"
36 #include "LaTeXFeatures.h"
37 #include "LayoutFile.h"
41 #include "LyXAction.h"
45 #include "MetricsInfo.h"
46 #include "Paragraph.h"
47 #include "ParagraphParameters.h"
48 #include "ParIterator.h"
49 #include "RowPainter.h"
52 #include "TextClass.h"
53 #include "TextMetrics.h"
55 #include "TocBackend.h"
56 #include "WordLangTuple.h"
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCitation.h"
60 #include "insets/InsetCommand.h" // ChangeRefs
61 #include "insets/InsetExternal.h"
62 #include "insets/InsetGraphics.h"
63 #include "insets/InsetNote.h"
64 #include "insets/InsetRef.h"
65 #include "insets/InsetText.h"
67 #include "mathed/MathData.h"
68 #include "mathed/InsetMathNest.h"
70 #include "frontends/alert.h"
71 #include "frontends/Application.h"
72 #include "frontends/Delegates.h"
73 #include "frontends/FontMetrics.h"
74 #include "frontends/NullPainter.h"
75 #include "frontends/Painter.h"
76 #include "frontends/Selection.h"
78 #include "support/convert.h"
79 #include "support/debug.h"
80 #include "support/ExceptionMessage.h"
81 #include "support/filetools.h"
82 #include "support/gettext.h"
83 #include "support/lassert.h"
84 #include "support/lstrings.h"
85 #include "support/lyxlib.h"
86 #include "support/Package.h"
87 #include "support/types.h"
97 using namespace lyx::support;
101 namespace Alert = frontend::Alert;
105 /// Return an inset of this class if it exists at the current cursor position
107 T * getInsetByCode(Cursor const & cur, InsetCode code)
109 DocIterator it = cur;
110 Inset * inset = it.nextInset();
111 if (inset && inset->lyxCode() == code)
112 return static_cast<T*>(inset);
117 /// Note that comparing contents can only be used for InsetCommand
118 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
119 docstring const & contents)
121 DocIterator tmpdit = dit;
124 Inset const * inset = tmpdit.nextInset();
126 bool const valid_code = std::find(codes.begin(), codes.end(),
127 inset->lyxCode()) != codes.end();
128 InsetCommand const * ic = inset->asInsetCommand();
129 bool const same_or_no_contents = contents.empty()
130 || (ic && (ic->getFirstNonOptParam() == contents));
132 if (valid_code && same_or_no_contents) {
137 tmpdit.forwardInset();
144 /// Looks for next inset with one of the given codes.
145 /// Note that same_content can only be used for InsetCommand
146 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
150 DocIterator tmpdit = dit;
151 tmpdit.forwardInset();
155 Inset const * inset = tmpdit.nextInset();
156 if (same_content && inset) {
157 InsetCommand const * ic = inset->asInsetCommand();
159 bool const valid_code = std::find(codes.begin(), codes.end(),
160 ic->lyxCode()) != codes.end();
162 contents = ic->getFirstNonOptParam();
166 if (!findNextInset(tmpdit, codes, contents)) {
167 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
168 inset = &tmpdit.bottom().inset();
169 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
170 if (!findNextInset(tmpdit, codes, contents))
182 /// Looks for next inset with the given code
183 void findInset(DocIterator & dit, InsetCode code, bool same_content)
185 findInset(dit, vector<InsetCode>(1, code), same_content);
189 /// Moves cursor to the next inset with one of the given codes.
190 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
193 Cursor tmpcur = bv->cursor();
194 if (!findInset(tmpcur, codes, same_content)) {
195 bv->cursor().message(_("No more insets"));
199 tmpcur.clearSelection();
200 bv->setCursor(tmpcur);
205 /// Moves cursor to the next inset with given code.
206 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
208 gotoInset(bv, vector<InsetCode>(1, code), same_content);
212 /// A map from a Text to the associated text metrics
213 typedef map<Text const *, TextMetrics> TextMetricsCache;
215 enum ScreenUpdateStrategy {
225 /////////////////////////////////////////////////////////////////////
229 /////////////////////////////////////////////////////////////////////
231 struct BufferView::Private
233 Private(BufferView & bv) : update_strategy_(FullScreenUpdate),
234 update_flags_(Update::Force),
236 anchor_pit_(0), anchor_ypos_(0),
237 inlineCompletionUniqueChars_(0),
238 last_inset_(0), clickable_inset_(false),
239 mouse_position_cache_(),
240 bookmark_edit_position_(-1), gui_(0),
241 horiz_scroll_offset_(0), repaint_caret_row_(false)
243 xsel_cache_.set = false;
247 ScrollbarParameters scrollbarParameters_;
249 ScreenUpdateStrategy update_strategy_;
251 Update::flags update_flags_;
253 CoordCache coord_cache_;
255 /// Estimated average par height for scrollbar.
257 /// this is used to handle XSelection events in the right manner.
266 pit_type anchor_pit_;
270 vector<int> par_height_;
273 DocIterator inlineCompletionPos_;
275 docstring inlineCompletion_;
277 size_t inlineCompletionUniqueChars_;
279 /// keyboard mapping object.
282 /// last visited inset.
283 /** kept to send setMouseHover(false).
284 * Not owned, so don't delete.
286 Inset const * last_inset_;
287 /// are we hovering something that we can click
288 bool clickable_inset_;
290 /// position of the mouse at the time of the last mouse move
291 /// This is used to update the hovering status of inset in
292 /// cases where the buffer is scrolled, but the mouse didn't move.
293 Point mouse_position_cache_;
295 // cache for id of the paragraph which was edited the last time
296 int bookmark_edit_position_;
298 mutable TextMetricsCache text_metrics_;
301 /** Not owned, so don't delete.
303 frontend::GuiBufferViewDelegate * gui_;
305 /// Cache for Find Next
306 FuncRequest search_request_cache_;
309 map<string, Inset *> edited_insets_;
311 /// When the row where the cursor lies is scrolled, this
312 /// contains the scroll offset
313 int horiz_scroll_offset_;
314 /// a slice pointing to the start of the row where the cursor
315 /// is (at last draw time)
316 CursorSlice current_row_slice_;
317 /// a slice pointing to the start of the row where cursor was
318 /// at previous draw event
319 CursorSlice last_row_slice_;
321 /// a slice pointing to where the cursor has been drawn after the current
323 CursorSlice caret_slice_;
324 /// indicates whether the caret slice needs to be repainted in this draw() run.
325 bool repaint_caret_row_;
329 BufferView::BufferView(Buffer & buf)
330 : width_(0), height_(0), full_screen_(false), buffer_(buf),
331 d(new Private(*this))
333 d->xsel_cache_.set = false;
334 d->intl_.initKeyMapper(lyxrc.use_kbmap);
336 d->cursor_.setBuffer(&buf);
337 d->cursor_.push(buffer_.inset());
338 d->cursor_.resetAnchor();
339 d->cursor_.setCurrentFont();
341 buffer_.updatePreviews();
345 BufferView::~BufferView()
347 // current buffer is going to be switched-off, save cursor pos
348 // Ideally, the whole cursor stack should be saved, but session
349 // currently can only handle bottom (whole document) level pit and pos.
350 // That is to say, if a cursor is in a nested inset, it will be
351 // restore to the left of the top level inset.
352 LastFilePosSection::FilePos fp;
353 fp.pit = d->cursor_.bottom().pit();
354 fp.pos = d->cursor_.bottom().pos();
355 theSession().lastFilePos().save(buffer_.fileName(), fp);
358 d->last_inset_->setMouseHover(this, false);
364 int BufferView::rightMargin() const
366 // The value used to be hardcoded to 10
367 int const default_margin = zoomedPixels(10);
368 // The additional test for the case the outliner is opened.
369 if (!full_screen_ || !lyxrc.full_screen_limit
370 || width_ < lyxrc.full_screen_width + 2 * default_margin)
371 return default_margin;
373 return (width_ - lyxrc.full_screen_width) / 2;
377 int BufferView::leftMargin() const
379 return rightMargin();
383 int BufferView::inPixels(Length const & len) const
385 Font const font = buffer().params().getFont();
386 return len.inPixels(workWidth(), theFontMetrics(font).em());
390 int BufferView::zoomedPixels(int pix) const
392 // FIXME: the dpi setting should really depend on the BufferView
393 // (think different monitors).
395 // Zoom factor specified by user in percent
396 double const zoom = lyxrc.currentZoom / 100.0; // [percent]
398 // DPI setting for monitor relative to 100dpi
399 double const dpizoom = lyxrc.dpi / 100.0; // [per 100dpi]
401 return support::iround(pix * zoom * dpizoom);
405 bool BufferView::isTopScreen() const
407 return 0 == d->scrollbarParameters_.min;
411 bool BufferView::isBottomScreen() const
413 return 0 == d->scrollbarParameters_.max;
417 Intl & BufferView::getIntl()
423 Intl const & BufferView::getIntl() const
429 CoordCache & BufferView::coordCache()
431 return d->coord_cache_;
435 CoordCache const & BufferView::coordCache() const
437 return d->coord_cache_;
441 Buffer & BufferView::buffer()
447 Buffer const & BufferView::buffer() const
453 bool BufferView::needsFitCursor() const
455 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
456 frontend::FontMetrics const & fm =
457 theFontMetrics(d->cursor_.getFont().fontInfo());
458 int const asc = fm.maxAscent();
459 int const des = fm.maxDescent();
460 Point const p = getPos(d->cursor_);
461 if (p.y_ - asc >= 0 && p.y_ + des < height_)
470 // this is for debugging only.
471 string flagsAsString(Update::flags flags)
473 if (flags == Update::None)
475 return string((flags & Update::FitCursor) ? "FitCursor " : "")
476 + ((flags & Update::Force) ? "Force " : "")
477 + ((flags & Update::ForceDraw) ? "ForceDraw " : "")
478 + ((flags & Update::SinglePar) ? "SinglePar " : "");
483 void BufferView::processUpdateFlags(Update::flags flags)
485 LYXERR(Debug::PAINTING, "BufferView::processUpdateFlags( "
486 << flagsAsString(flags) << ") buffer: " << &buffer_);
488 // Case when no explicit update is requested.
489 if (flags == Update::None)
492 // SinglePar is ignored for now (this should probably change). We
493 // set it ourselves below, at the price of always rebreaking the
494 // paragraph at cursor. This can be expensive for large tables.
495 flags = flags & ~Update::SinglePar;
497 // First check whether the metrics and inset positions should be updated
498 if (flags & Update::Force) {
499 // This will update the CoordCache items and replace Force
500 // with ForceDraw in flags.
501 updateMetrics(flags);
504 // Then make sure that the screen contains the cursor if needed
505 if (flags & Update::FitCursor) {
506 if (needsFitCursor()) {
507 scrollToCursor(d->cursor_, false);
508 // Metrics have to be recomputed (maybe again)
509 updateMetrics(flags);
511 flags = flags & ~Update::FitCursor;
514 // Finally detect whether we can only repaint a single paragraph
515 if (!(flags & Update::ForceDraw)) {
516 if (singleParUpdate())
517 flags = flags | Update::SinglePar;
519 updateMetrics(flags);
522 // Add flags to the the update flags. These will be reset to None
523 // after the redraw is actually done
524 d->update_flags_ = d->update_flags_ | flags;
525 LYXERR(Debug::PAINTING, "Cumulative flags: " << flagsAsString(flags));
527 // Now compute the update strategy
528 // Possibly values in flag are None, Decoration, ForceDraw
529 LATTEST((d->update_flags_ & ~(Update::None | Update::SinglePar
530 | Update::Decoration | Update::ForceDraw)) == 0);
532 if (d->update_flags_ & Update::ForceDraw)
533 d->update_strategy_ = FullScreenUpdate;
534 else if (d->update_flags_ & Update::Decoration)
535 d->update_strategy_ = DecorationUpdate;
536 else if (d->update_flags_ & Update::SinglePar)
537 d->update_strategy_ = SingleParUpdate;
539 // no need to redraw anything.
540 d->update_strategy_ = NoScreenUpdate;
543 updateHoveredInset();
546 buffer_.changed(false);
550 void BufferView::updateScrollbar()
552 if (height_ == 0 && width_ == 0)
555 // We prefer fixed size line scrolling.
556 d->scrollbarParameters_.single_step = defaultRowHeight();
557 // We prefer full screen page scrolling.
558 d->scrollbarParameters_.page_step = height_;
560 Text & t = buffer_.text();
561 TextMetrics & tm = d->text_metrics_[&t];
563 LYXERR(Debug::GUI, " Updating scrollbar: height: "
564 << t.paragraphs().size()
565 << " curr par: " << d->cursor_.bottom().pit()
566 << " default height " << defaultRowHeight());
568 size_t const parsize = t.paragraphs().size();
569 if (d->par_height_.size() != parsize) {
570 d->par_height_.clear();
571 // FIXME: We assume a default paragraph height of 2 rows. This
572 // should probably be pondered with the screen width.
573 d->par_height_.resize(parsize, defaultRowHeight() * 2);
576 // Look at paragraph heights on-screen
577 pair<pit_type, ParagraphMetrics const *> first = tm.first();
578 pair<pit_type, ParagraphMetrics const *> last = tm.last();
579 for (pit_type pit = first.first; pit <= last.first; ++pit) {
580 d->par_height_[pit] = tm.parMetrics(pit).height();
581 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
582 << d->par_height_[pit]);
585 int top_pos = first.second->position() - first.second->ascent();
586 int bottom_pos = last.second->position() + last.second->descent();
587 bool first_visible = first.first == 0 && top_pos >= 0;
588 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
589 if (first_visible && last_visible) {
590 d->scrollbarParameters_.min = 0;
591 d->scrollbarParameters_.max = 0;
595 d->scrollbarParameters_.min = top_pos;
596 for (size_t i = 0; i != size_t(first.first); ++i)
597 d->scrollbarParameters_.min -= d->par_height_[i];
598 d->scrollbarParameters_.max = bottom_pos;
599 for (size_t i = last.first + 1; i != parsize; ++i)
600 d->scrollbarParameters_.max += d->par_height_[i];
602 // The reference is the top position so we remove one page.
603 if (lyxrc.scroll_below_document)
604 d->scrollbarParameters_.max -= minVisiblePart();
606 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
608 // 0 must be inside the range as it denotes the current position
609 if (d->scrollbarParameters_.max < 0)
610 d->scrollbarParameters_.max = 0;
611 if (d->scrollbarParameters_.min > 0)
612 d->scrollbarParameters_.min = 0;
616 ScrollbarParameters const & BufferView::scrollbarParameters() const
618 return d->scrollbarParameters_;
622 docstring BufferView::toolTip(int x, int y) const
624 // Get inset under mouse, if there is one.
625 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
627 // No inset, no tooltip...
629 return covering_inset->toolTip(*this, x, y);
633 string BufferView::contextMenu(int x, int y) const
635 //If there is a selection, return the containing inset menu
636 if (d->cursor_.selection())
637 return d->cursor_.inset().contextMenu(*this, x, y);
639 // Get inset under mouse, if there is one.
640 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
642 return covering_inset->contextMenu(*this, x, y);
644 return buffer_.inset().contextMenu(*this, x, y);
649 void BufferView::scrollDocView(int const value, bool update)
651 // The scrollbar values are relative to the top of the screen, therefore the
652 // offset is equal to the target value.
654 // No scrolling at all? No need to redraw anything
658 // If the offset is less than 2 screen height, prefer to scroll instead.
659 if (abs(value) <= 2 * height_) {
660 d->anchor_ypos_ -= value;
661 processUpdateFlags(Update::Force);
665 // cut off at the top
666 if (value <= d->scrollbarParameters_.min) {
667 DocIterator dit = doc_iterator_begin(&buffer_);
668 showCursor(dit, false, update);
669 LYXERR(Debug::SCROLLING, "scroll to top");
673 // cut off at the bottom
674 if (value >= d->scrollbarParameters_.max) {
675 DocIterator dit = doc_iterator_end(&buffer_);
677 showCursor(dit, false, update);
678 LYXERR(Debug::SCROLLING, "scroll to bottom");
682 // find paragraph at target position
683 int par_pos = d->scrollbarParameters_.min;
685 for (; i != int(d->par_height_.size()); ++i) {
686 par_pos += d->par_height_[i];
687 if (par_pos >= value)
691 if (par_pos < value) {
692 // It seems we didn't find the correct pit so stay on the safe side and
694 LYXERR0("scrolling position not found!");
695 scrollDocView(d->scrollbarParameters_.max, update);
699 DocIterator dit = doc_iterator_begin(&buffer_);
701 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
702 showCursor(dit, false, update);
706 // FIXME: this method is not working well.
707 void BufferView::setCursorFromScrollbar()
709 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
711 int const height = 2 * defaultRowHeight();
712 int const first = height;
713 int const last = height_ - height;
715 Cursor const & oldcur = d->cursor_;
717 switch (cursorStatus(oldcur)) {
725 int const y = getPos(oldcur).y_;
726 newy = min(last, max(y, first));
730 // We reset the cursor because cursorStatus() does not
731 // work when the cursor is within mathed.
734 tm.setCursorFromCoordinates(cur, 0, newy);
736 // update the bufferview cursor and notify insets
737 // FIXME: Care about the d->cursor_ flags to redraw if needed
738 Cursor old = d->cursor_;
740 // the DEPM call in mouseSetCursor() might have destroyed the
741 // paragraph the cursor is in.
742 bool badcursor = old.fixIfBroken();
743 badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
745 d->cursor_.fixIfBroken();
749 Change const BufferView::getCurrentChange() const
751 if (!d->cursor_.selection())
752 return Change(Change::UNCHANGED);
754 DocIterator dit = d->cursor_.selectionBegin();
755 // The selected content might have been changed (see #7685)
756 dit = dit.getInnerText();
757 return dit.paragraph().lookupChange(dit.pos());
761 // this could be used elsewhere as well?
762 // FIXME: This does not work within mathed!
763 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
765 Point const p = getPos(dit);
768 if (p.y_ > workHeight())
774 void BufferView::bookmarkEditPosition()
776 // Don't eat cpu time for each keystroke
777 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
780 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
784 void BufferView::saveBookmark(unsigned int idx)
786 // tentatively save bookmark, id and pos will be used to
787 // acturately locate a bookmark in a 'live' lyx session.
788 // pit and pos will be updated with bottom level pit/pos
790 if (!buffer_.isInternal()) {
791 theSession().bookmarks().save(
793 d->cursor_.bottom().pit(),
794 d->cursor_.bottom().pos(),
795 d->cursor_.paragraph().id(),
800 // emit message signal.
801 message(_("Save bookmark"));
806 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
807 int top_id, pos_type top_pos)
809 bool success = false;
812 d->cursor_.clearSelection();
814 // if a valid par_id is given, try it first
815 // This is the case for a 'live' bookmark when unique paragraph ID
816 // is used to track bookmarks.
818 dit = buffer_.getParFromID(top_id);
820 dit.pos() = min(dit.paragraph().size(), top_pos);
821 // Some slices of the iterator may not be
822 // reachable (e.g. closed collapsible inset)
823 // so the dociterator may need to be
824 // shortened. Otherwise, setCursor may crash
825 // lyx when the cursor can not be set to these
827 size_t const n = dit.depth();
828 for (size_t i = 0; i < n; ++i)
829 if (!dit[i].inset().editable()) {
837 // if top_id == 0, or searching through top_id failed
838 // This is the case for a 'restored' bookmark when only bottom
839 // (document level) pit was saved. Because of this, bookmark
840 // restoration is inaccurate. If a bookmark was within an inset,
841 // it will be restored to the left of the outmost inset that contains
843 if (bottom_pit < int(buffer_.paragraphs().size())) {
844 dit = doc_iterator_begin(&buffer_);
846 dit.pit() = bottom_pit;
847 dit.pos() = min(bottom_pos, dit.paragraph().size());
852 // Note: only bottom (document) level pit is set.
854 // set the current font.
855 d->cursor_.setCurrentFont();
856 // Do not forget to reset the anchor (see #9912)
857 d->cursor_.resetAnchor();
858 processUpdateFlags(Update::FitCursor);
865 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
867 if (d->cursor_.real_current_font.isRightToLeft()) {
868 if (d->intl_.keymap == Intl::PRIMARY)
869 d->intl_.keyMapSec();
871 if (d->intl_.keymap == Intl::SECONDARY)
872 d->intl_.keyMapPrim();
875 d->intl_.getTransManager().translateAndInsert(c, t, cur);
879 int BufferView::workWidth() const
885 void BufferView::recenter()
887 showCursor(d->cursor_, true, true);
891 void BufferView::showCursor()
893 showCursor(d->cursor_, false, true);
897 void BufferView::showCursor(DocIterator const & dit,
898 bool recenter, bool update)
900 if (scrollToCursor(dit, recenter) && update)
901 processUpdateFlags(Update::Force);
905 void BufferView::scrollToCursor()
907 if (scrollToCursor(d->cursor_, false))
908 processUpdateFlags(Update::Force);
912 bool BufferView::scrollToCursor(DocIterator const & dit, bool const recenter)
914 // We are not properly started yet, delay until resizing is
919 LYXERR(Debug::SCROLLING, "recentering!");
921 CursorSlice const & bot = dit.bottom();
922 TextMetrics & tm = d->text_metrics_[bot.text()];
924 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
925 int bot_pit = bot.pit();
926 if (bot_pit > max_pit) {
927 // FIXME: Why does this happen?
928 LYXERR0("bottom pit is greater that max pit: "
929 << bot_pit << " > " << max_pit);
933 if (bot_pit == tm.first().first - 1)
934 tm.newParMetricsUp();
935 else if (bot_pit == tm.last().first + 1)
936 tm.newParMetricsDown();
938 if (tm.contains(bot_pit)) {
939 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
940 LBUFERR(!pm.rows().empty());
941 // FIXME: smooth scrolling doesn't work in mathed.
942 CursorSlice const & cs = dit.innerTextSlice();
943 int offset = coordOffset(dit).y_;
944 int ypos = pm.position() + offset;
945 Dimension const & row_dim =
946 pm.getRow(cs.pos(), dit.boundary()).dimension();
949 scrolled = scroll(ypos - height_/2);
951 // We try to visualize the whole row, if the row height is larger than
952 // the screen height, we scroll to a heuristic value of height_ / 4.
953 // FIXME: This heuristic value should be replaced by a recursive search
954 // for a row in the inset that can be visualized completely.
955 else if (row_dim.height() > height_) {
956 if (ypos < defaultRowHeight())
957 scrolled = scroll(ypos - height_ / 4);
958 else if (ypos > height_ - defaultRowHeight())
959 scrolled = scroll(ypos - 3 * height_ / 4);
962 // If the top part of the row falls of the screen, we scroll
963 // up to align the top of the row with the top of the screen.
964 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
965 int ynew = row_dim.ascent();
966 scrolled = scrollUp(ynew - ypos);
969 // If the bottom of the row falls of the screen, we scroll down.
970 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
971 int ynew = height_ - row_dim.descent();
972 scrolled = scrollDown(ypos - ynew);
975 // else, nothing to do, the cursor is already visible so we just return.
976 return scrolled != 0;
979 // fix inline completion position
980 if (d->inlineCompletionPos_.fixIfBroken())
981 d->inlineCompletionPos_ = DocIterator();
983 tm.redoParagraph(bot_pit);
984 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
985 int offset = coordOffset(dit).y_;
987 d->anchor_pit_ = bot_pit;
988 CursorSlice const & cs = dit.innerTextSlice();
989 Dimension const & row_dim =
990 pm.getRow(cs.pos(), dit.boundary()).dimension();
993 d->anchor_ypos_ = height_/2;
994 else if (d->anchor_pit_ == 0)
995 d->anchor_ypos_ = offset + pm.ascent();
996 else if (d->anchor_pit_ == max_pit)
997 d->anchor_ypos_ = height_ - offset - row_dim.descent();
998 else if (offset > height_)
999 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
1001 d->anchor_ypos_ = defaultRowHeight() * 2;
1007 void BufferView::makeDocumentClass()
1009 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1010 buffer_.params().makeDocumentClass();
1011 updateDocumentClass(olddc);
1015 void BufferView::updateDocumentClass(DocumentClassConstPtr olddc)
1017 message(_("Converting document to new document class..."));
1019 StableDocIterator backcur(d->cursor_);
1020 ErrorList & el = buffer_.errorList("Class Switch");
1021 cap::switchBetweenClasses(
1022 olddc, buffer_.params().documentClassPtr(),
1023 static_cast<InsetText &>(buffer_.inset()), el);
1025 setCursor(backcur.asDocIterator(&buffer_));
1027 buffer_.errors("Class Switch");
1031 /** Return the change status at cursor position, taking into account the
1032 * status at each level of the document iterator (a table in a deleted
1033 * footnote is deleted).
1034 * When \param outer is true, the top slice is not looked at.
1036 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
1038 size_t const depth = dit.depth() - (outer ? 1 : 0);
1040 for (size_t i = 0 ; i < depth ; ++i) {
1041 CursorSlice const & slice = dit[i];
1042 if (!slice.inset().inMathed()
1043 && slice.pos() < slice.paragraph().size()) {
1044 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
1045 if (ch != Change::UNCHANGED)
1049 return Change::UNCHANGED;
1053 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1055 FuncCode const act = cmd.action();
1057 // Can we use a readonly buffer?
1058 if (buffer_.isReadonly()
1059 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1060 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1061 if (buffer_.hasReadonlyFlag())
1062 flag.message(from_utf8(N_("Document is read-only")));
1064 flag.message(from_utf8(N_("Document has been modified externally")));
1065 flag.setEnabled(false);
1069 // Are we in a DELETED change-tracking region?
1070 if (lookupChangeType(d->cursor_, true) == Change::DELETED
1071 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1072 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1073 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1074 flag.setEnabled(false);
1078 Cursor & cur = d->cursor_;
1080 if (cur.getStatus(cmd, flag))
1085 // FIXME: This is a bit problematic because we don't check if this is
1086 // a document BufferView or not for these LFUNs. We probably have to
1087 // dispatch both to currentBufferView() and, if that fails,
1088 // to documentBufferView(); same as we do now for current Buffer and
1089 // document Buffer. Ideally those LFUN should go to Buffer as they
1090 // operate on the full Buffer and the cursor is only needed either for
1091 // an Undo record or to restore a cursor position. But we don't know
1092 // how to do that inside Buffer of course.
1093 case LFUN_BUFFER_PARAMS_APPLY:
1094 case LFUN_LAYOUT_MODULES_CLEAR:
1095 case LFUN_LAYOUT_MODULE_ADD:
1096 case LFUN_LAYOUT_RELOAD:
1097 case LFUN_TEXTCLASS_APPLY:
1098 case LFUN_TEXTCLASS_LOAD:
1099 flag.setEnabled(!buffer_.isReadonly());
1103 // We do not use the LyXAction flag for readonly because Undo sets the
1104 // buffer clean/dirty status by itself.
1105 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1108 // We do not use the LyXAction flag for readonly because Redo sets the
1109 // buffer clean/dirty status by itself.
1110 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1112 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1113 case LFUN_FILE_INSERT_PLAINTEXT: {
1114 docstring const fname = cmd.argument();
1115 if (!FileName::isAbsolute(to_utf8(fname))) {
1116 flag.message(_("Absolute filename expected."));
1119 flag.setEnabled(cur.inTexted());
1122 case LFUN_FILE_INSERT:
1123 case LFUN_BOOKMARK_SAVE:
1124 // FIXME: Actually, these LFUNS should be moved to Text
1125 flag.setEnabled(cur.inTexted());
1128 case LFUN_FONT_STATE:
1129 case LFUN_LABEL_INSERT:
1130 case LFUN_INFO_INSERT:
1131 case LFUN_PARAGRAPH_GOTO:
1132 case LFUN_NOTE_NEXT:
1133 case LFUN_REFERENCE_NEXT:
1134 case LFUN_WORD_FIND:
1135 case LFUN_WORD_FIND_FORWARD:
1136 case LFUN_WORD_FIND_BACKWARD:
1137 case LFUN_WORD_REPLACE:
1140 case LFUN_MARK_TOGGLE:
1141 case LFUN_SCREEN_RECENTER:
1142 case LFUN_SCREEN_SHOW_CURSOR:
1143 case LFUN_BIBTEX_DATABASE_ADD:
1144 case LFUN_BIBTEX_DATABASE_DEL:
1145 case LFUN_STATISTICS:
1146 case LFUN_KEYMAP_OFF:
1147 case LFUN_KEYMAP_PRIMARY:
1148 case LFUN_KEYMAP_SECONDARY:
1149 case LFUN_KEYMAP_TOGGLE:
1150 case LFUN_INSET_SELECT_ALL:
1151 flag.setEnabled(true);
1154 case LFUN_GRAPHICS_UNIFY:
1155 flag.setEnabled(cur.selection());
1158 case LFUN_WORD_FINDADV: {
1159 FindAndReplaceOptions opt;
1160 istringstream iss(to_utf8(cmd.argument()));
1162 flag.setEnabled(opt.repl_buf_name.empty()
1163 || !buffer_.isReadonly());
1167 case LFUN_LABEL_GOTO:
1168 flag.setEnabled(!cmd.argument().empty()
1169 || getInsetByCode<InsetRef>(cur, REF_CODE));
1172 case LFUN_CHANGES_MERGE:
1173 case LFUN_CHANGE_NEXT:
1174 case LFUN_CHANGE_PREVIOUS:
1175 case LFUN_ALL_CHANGES_ACCEPT:
1176 case LFUN_ALL_CHANGES_REJECT:
1177 flag.setEnabled(buffer_.areChangesPresent());
1180 case LFUN_SCREEN_UP:
1181 case LFUN_SCREEN_DOWN:
1183 case LFUN_SCREEN_UP_SELECT:
1184 case LFUN_SCREEN_DOWN_SELECT:
1185 case LFUN_INSET_FORALL:
1186 flag.setEnabled(true);
1189 case LFUN_LAYOUT_TABULAR:
1190 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1194 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1197 case LFUN_LAYOUT_PARAGRAPH:
1198 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1201 case LFUN_BRANCH_ADD_INSERT:
1202 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1205 case LFUN_DIALOG_SHOW_NEW_INSET:
1206 // FIXME: this is wrong, but I do not understand the
1208 if (cur.inset().lyxCode() == CAPTION_CODE)
1209 return cur.inset().getStatus(cur, cmd, flag);
1210 // FIXME we should consider passthru paragraphs too.
1211 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1214 case LFUN_CITATION_INSERT: {
1215 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1216 // FIXME: This could turn in a recursive hell.
1217 // Shouldn't we use Buffer::getStatus() instead?
1218 flag.setEnabled(lyx::getStatus(fr).enabled());
1221 case LFUN_INSET_APPLY: {
1222 string const name = cmd.getArg(0);
1223 Inset * inset = editedInset(name);
1225 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1226 if (!inset->getStatus(cur, fr, flag)) {
1227 // Every inset is supposed to handle this
1228 LASSERT(false, break);
1231 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1232 flag = lyx::getStatus(fr);
1245 Inset * BufferView::editedInset(string const & name) const
1247 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1248 return it == d->edited_insets_.end() ? 0 : it->second;
1252 void BufferView::editInset(string const & name, Inset * inset)
1254 d->edited_insets_[name] = inset;
1258 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1260 LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1262 string const argument = to_utf8(cmd.argument());
1263 Cursor & cur = d->cursor_;
1266 // Don't dispatch function that does not apply to internal buffers.
1267 if (buffer_.isInternal()
1268 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1271 // We'll set this back to false if need be.
1272 bool dispatched = true;
1273 buffer_.undo().beginUndoGroup();
1275 FuncCode const act = cmd.action();
1278 case LFUN_BUFFER_PARAMS_APPLY: {
1279 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1280 cur.recordUndoBufferParams();
1281 istringstream ss(to_utf8(cmd.argument()));
1284 int const unknown_tokens = buffer_.readHeader(lex);
1285 if (unknown_tokens != 0) {
1286 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1287 << unknown_tokens << " unknown token"
1288 << (unknown_tokens == 1 ? "" : "s"));
1290 updateDocumentClass(olddc);
1292 // We are most certainly here because of a change in the document
1293 // It is then better to make sure that all dialogs are in sync with
1294 // current document settings.
1295 dr.screenUpdate(Update::Force | Update::FitCursor);
1296 dr.forceBufferUpdate();
1300 case LFUN_LAYOUT_MODULES_CLEAR: {
1301 // FIXME: this modifies the document in cap::switchBetweenClasses
1302 // without calling recordUndo. Fix this before using
1303 // recordUndoBufferParams().
1304 cur.recordUndoFullBuffer();
1305 buffer_.params().clearLayoutModules();
1306 makeDocumentClass();
1307 dr.screenUpdate(Update::Force);
1308 dr.forceBufferUpdate();
1312 case LFUN_LAYOUT_MODULE_ADD: {
1313 BufferParams const & params = buffer_.params();
1314 if (!params.layoutModuleCanBeAdded(argument)) {
1315 LYXERR0("Module `" << argument <<
1316 "' cannot be added due to failed requirements or "
1317 "conflicts with installed modules.");
1320 // FIXME: this modifies the document in cap::switchBetweenClasses
1321 // without calling recordUndo. Fix this before using
1322 // recordUndoBufferParams().
1323 cur.recordUndoFullBuffer();
1324 buffer_.params().addLayoutModule(argument);
1325 makeDocumentClass();
1326 dr.screenUpdate(Update::Force);
1327 dr.forceBufferUpdate();
1331 case LFUN_TEXTCLASS_APPLY: {
1332 // since this shortcircuits, the second call is made only if
1334 bool const success =
1335 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1336 LayoutFileList::get().load(argument, buffer_.filePath());
1338 docstring s = bformat(_("The document class `%1$s' "
1339 "could not be loaded."), from_utf8(argument));
1340 frontend::Alert::error(_("Could not load class"), s);
1344 LayoutFile const * old_layout = buffer_.params().baseClass();
1345 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1347 if (old_layout == new_layout)
1351 // Save the old, possibly modular, layout for use in conversion.
1352 // FIXME: this modifies the document in cap::switchBetweenClasses
1353 // without calling recordUndo. Fix this before using
1354 // recordUndoBufferParams().
1355 cur.recordUndoFullBuffer();
1356 buffer_.params().setBaseClass(argument);
1357 makeDocumentClass();
1358 dr.screenUpdate(Update::Force);
1359 dr.forceBufferUpdate();
1363 case LFUN_TEXTCLASS_LOAD: {
1364 // since this shortcircuits, the second call is made only if
1366 bool const success =
1367 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1368 LayoutFileList::get().load(argument, buffer_.filePath());
1370 docstring s = bformat(_("The document class `%1$s' "
1371 "could not be loaded."), from_utf8(argument));
1372 frontend::Alert::error(_("Could not load class"), s);
1377 case LFUN_LAYOUT_RELOAD: {
1378 LayoutFileIndex bc = buffer_.params().baseClassID();
1379 LayoutFileList::get().reset(bc);
1380 buffer_.params().setBaseClass(bc);
1381 makeDocumentClass();
1382 dr.screenUpdate(Update::Force);
1383 dr.forceBufferUpdate();
1388 dr.setMessage(_("Undo"));
1389 cur.clearSelection();
1390 // We need to find out if the bibliography information
1391 // has changed. See bug #11055.
1392 // So these should not be references...
1393 LayoutModuleList const engines = buffer().params().citeEngine();
1394 CiteEngineType const enginetype = buffer().params().citeEngineType();
1395 if (!cur.textUndo())
1396 dr.setMessage(_("No further undo information"));
1398 dr.screenUpdate(Update::Force | Update::FitCursor);
1399 dr.forceBufferUpdate();
1400 if (buffer().params().citeEngine() != engines ||
1401 buffer().params().citeEngineType() != enginetype)
1402 buffer().invalidateCiteLabels();
1408 dr.setMessage(_("Redo"));
1409 cur.clearSelection();
1410 // We need to find out if the bibliography information
1411 // has changed. See bug #11055.
1412 // So these should not be references...
1413 LayoutModuleList const engines = buffer().params().citeEngine();
1414 CiteEngineType const enginetype = buffer().params().citeEngineType();
1415 if (!cur.textRedo())
1416 dr.setMessage(_("No further redo information"));
1418 dr.screenUpdate(Update::Force | Update::FitCursor);
1419 dr.forceBufferUpdate();
1420 if (buffer().params().citeEngine() != engines ||
1421 buffer().params().citeEngineType() != enginetype)
1422 buffer().invalidateCiteLabels();
1427 case LFUN_FONT_STATE:
1428 dr.setMessage(cur.currentState(false));
1431 case LFUN_BOOKMARK_SAVE:
1432 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1435 case LFUN_LABEL_GOTO: {
1436 docstring label = cmd.argument();
1437 if (label.empty()) {
1439 getInsetByCode<InsetRef>(cur, REF_CODE);
1441 label = inset->getParam("reference");
1442 // persistent=false: use temp_bookmark
1446 if (!label.empty()) {
1448 // at the moment, this is redundant, since gotoLabel will
1449 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1451 dr.screenUpdate(Update::Force | Update::FitCursor);
1456 case LFUN_PARAGRAPH_GOTO: {
1457 int const id = convert<int>(cmd.getArg(0));
1458 pos_type const pos = convert<int>(cmd.getArg(1));
1461 string const str_id_end = cmd.getArg(2);
1462 string const str_pos_end = cmd.getArg(3);
1464 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1465 b = theBufferList().next(b)) {
1468 curs.setCursor(b->getParFromID(id));
1470 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1474 LYXERR(Debug::INFO, "Paragraph " << curs.paragraph().id()
1475 << " found in buffer `"
1476 << b->absFileName() << "'.");
1478 if (b == &buffer_) {
1480 if (str_id_end.empty() || str_pos_end.empty()) {
1483 mouseSetCursor(curs);
1486 int const id_end = convert<int>(str_id_end);
1487 pos_type const pos_end = convert<int>(str_pos_end);
1488 success = setCursorFromEntries({id, pos},
1492 dr.screenUpdate(Update::Force | Update::FitCursor);
1494 // Switch to other buffer view and resend cmd
1495 lyx::dispatch(FuncRequest(
1496 LFUN_BUFFER_SWITCH, b->absFileName()));
1504 case LFUN_NOTE_NEXT:
1505 gotoInset(this, NOTE_CODE, false);
1508 case LFUN_REFERENCE_NEXT: {
1509 vector<InsetCode> tmp;
1510 tmp.push_back(LABEL_CODE);
1511 tmp.push_back(REF_CODE);
1512 gotoInset(this, tmp, true);
1516 case LFUN_CHANGE_NEXT:
1517 findNextChange(this);
1518 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1519 dr.screenUpdate(Update::Force | Update::FitCursor);
1522 case LFUN_CHANGE_PREVIOUS:
1523 findPreviousChange(this);
1524 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1525 dr.screenUpdate(Update::Force | Update::FitCursor);
1528 case LFUN_CHANGES_MERGE:
1529 if (findNextChange(this) || findPreviousChange(this)) {
1530 dr.screenUpdate(Update::Force | Update::FitCursor);
1531 dr.forceBufferUpdate();
1532 showDialog("changes");
1536 case LFUN_ALL_CHANGES_ACCEPT:
1537 // select complete document
1539 cur.selHandle(true);
1540 buffer_.text().cursorBottom(cur);
1541 // accept everything in a single step to support atomic undo
1542 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1544 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1545 dr.screenUpdate(Update::Force | Update::FitCursor);
1546 dr.forceBufferUpdate();
1549 case LFUN_ALL_CHANGES_REJECT:
1550 // select complete document
1552 cur.selHandle(true);
1553 buffer_.text().cursorBottom(cur);
1554 // reject everything in a single step to support atomic undo
1555 // Note: reject does not work recursively; the user may have to repeat the operation
1556 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1558 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1559 dr.screenUpdate(Update::Force | Update::FitCursor);
1560 dr.forceBufferUpdate();
1563 case LFUN_WORD_FIND_FORWARD:
1564 case LFUN_WORD_FIND_BACKWARD: {
1566 // Would it maybe be better if this variable were view specific anyway?
1567 static docstring last_search;
1568 docstring searched_string;
1570 if (!cmd.argument().empty()) {
1571 last_search = cmd.argument();
1572 searched_string = cmd.argument();
1574 searched_string = last_search;
1577 if (searched_string.empty())
1580 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1581 docstring const data =
1582 find2string(searched_string, true, false, fw);
1583 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1585 dr.screenUpdate(Update::Force | Update::FitCursor);
1589 case LFUN_WORD_FIND: {
1590 FuncRequest req = cmd;
1591 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1592 req = d->search_request_cache_;
1593 if (req.argument().empty()) {
1594 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1597 if (lyxfind(this, req))
1598 dr.screenUpdate(Update::Force | Update::FitCursor);
1600 d->search_request_cache_ = req;
1604 case LFUN_WORD_REPLACE: {
1605 bool has_deleted = false;
1606 if (cur.selection()) {
1607 DocIterator beg = cur.selectionBegin();
1608 DocIterator end = cur.selectionEnd();
1609 if (beg.pit() == end.pit()) {
1610 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1611 if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1618 if (lyxreplace(this, cmd, has_deleted)) {
1619 dr.forceBufferUpdate();
1620 dr.screenUpdate(Update::Force | Update::FitCursor);
1625 case LFUN_WORD_FINDADV: {
1626 FindAndReplaceOptions opt;
1627 istringstream iss(to_utf8(cmd.argument()));
1629 if (findAdv(this, opt)) {
1630 dr.screenUpdate(Update::Force | Update::FitCursor);
1641 cur.clearSelection();
1642 dr.setMessage(from_utf8(N_("Mark off")));
1646 cur.clearSelection();
1648 dr.setMessage(from_utf8(N_("Mark on")));
1651 case LFUN_MARK_TOGGLE:
1652 cur.selection(false);
1655 dr.setMessage(from_utf8(N_("Mark removed")));
1658 dr.setMessage(from_utf8(N_("Mark set")));
1663 case LFUN_SCREEN_SHOW_CURSOR:
1667 case LFUN_SCREEN_RECENTER:
1671 case LFUN_BIBTEX_DATABASE_ADD: {
1672 Cursor tmpcur = cur;
1673 findInset(tmpcur, BIBTEX_CODE, false);
1674 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1677 if (inset->addDatabase(cmd.argument()))
1678 dr.forceBufferUpdate();
1683 case LFUN_BIBTEX_DATABASE_DEL: {
1684 Cursor tmpcur = cur;
1685 findInset(tmpcur, BIBTEX_CODE, false);
1686 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1689 if (inset->delDatabase(cmd.argument()))
1690 dr.forceBufferUpdate();
1695 case LFUN_GRAPHICS_UNIFY: {
1697 cur.recordUndoFullBuffer();
1699 DocIterator from, to;
1700 from = cur.selectionBegin();
1701 to = cur.selectionEnd();
1703 string const newId = cmd.getArg(0);
1704 bool fetchId = newId.empty(); //if we wait for groupId from first graphics inset
1706 InsetGraphicsParams grp_par;
1708 InsetGraphics::string2params(graphics::getGroupParams(buffer_, newId), buffer_, grp_par);
1710 if (!from.nextInset()) //move to closest inset
1711 from.forwardInset();
1713 while (!from.empty() && from < to) {
1714 Inset * inset = from.nextInset();
1717 InsetGraphics * ig = inset->asInsetGraphics();
1719 InsetGraphicsParams inspar = ig->getParams();
1724 grp_par.filename = inspar.filename;
1725 ig->setParams(grp_par);
1728 from.forwardInset();
1730 dr.screenUpdate(Update::Force); //needed if triggered from context menu
1734 case LFUN_STATISTICS: {
1735 DocIterator from, to;
1736 if (cur.selection()) {
1737 from = cur.selectionBegin();
1738 to = cur.selectionEnd();
1740 from = doc_iterator_begin(&buffer_);
1741 to = doc_iterator_end(&buffer_);
1743 buffer_.updateStatistics(from, to);
1744 int const words = buffer_.wordCount();
1745 int const chars = buffer_.charCount(false);
1746 int const chars_blanks = buffer_.charCount(true);
1748 if (cur.selection())
1749 message = _("Statistics for the selection:");
1751 message = _("Statistics for the document:");
1754 message += bformat(_("%1$d words"), words);
1756 message += _("One word");
1758 if (chars_blanks != 1)
1759 message += bformat(_("%1$d characters (including blanks)"),
1762 message += _("One character (including blanks)");
1765 message += bformat(_("%1$d characters (excluding blanks)"),
1768 message += _("One character (excluding blanks)");
1770 Alert::information(_("Statistics"), message);
1774 case LFUN_SCREEN_UP:
1775 case LFUN_SCREEN_DOWN: {
1776 Point p = getPos(cur);
1777 // This code has been commented out to enable to scroll down a
1778 // document, even if there are large insets in it (see bug #5465).
1779 /*if (p.y_ < 0 || p.y_ > height_) {
1780 // The cursor is off-screen so recenter before proceeding.
1784 int const scrolled = scroll(act == LFUN_SCREEN_UP
1785 ? -height_ : height_);
1786 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1788 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1789 p = Point(width_, height_);
1790 bool const in_texted = cur.inTexted();
1791 cur.setCursor(doc_iterator_begin(cur.buffer()));
1792 cur.selHandle(false);
1793 // Force an immediate computation of metrics because we need it below
1794 processUpdateFlags(Update::Force);
1796 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1797 true, act == LFUN_SCREEN_UP);
1798 //FIXME: what to do with cur.x_target()?
1799 bool update = in_texted && cur.bv().checkDepm(cur, old);
1802 if (update || cur.mark())
1803 dr.screenUpdate(Update::Force | Update::FitCursor);
1805 dr.forceBufferUpdate();
1810 string const scroll_type = cmd.getArg(0);
1811 int scroll_step = 0;
1812 if (scroll_type == "line")
1813 scroll_step = d->scrollbarParameters_.single_step;
1814 else if (scroll_type == "page")
1815 scroll_step = d->scrollbarParameters_.page_step;
1818 string const scroll_quantity = cmd.getArg(1);
1819 if (scroll_quantity == "up")
1820 scrollUp(scroll_step);
1821 else if (scroll_quantity == "down")
1822 scrollDown(scroll_step);
1824 int const scroll_value = convert<int>(scroll_quantity);
1826 scroll(scroll_step * scroll_value);
1828 dr.screenUpdate(Update::ForceDraw);
1829 dr.forceBufferUpdate();
1833 case LFUN_SCREEN_UP_SELECT: {
1834 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
1835 cur.selHandle(true);
1836 if (isTopScreen()) {
1837 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1841 int y = getPos(cur).y_;
1842 int const ymin = y - height_ + defaultRowHeight();
1843 while (y > ymin && cur.up())
1847 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1851 case LFUN_SCREEN_DOWN_SELECT: {
1852 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
1853 cur.selHandle(true);
1854 if (isBottomScreen()) {
1855 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1859 int y = getPos(cur).y_;
1860 int const ymax = y + height_ - defaultRowHeight();
1861 while (y < ymax && cur.down())
1865 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1870 case LFUN_INSET_SELECT_ALL: {
1871 // true if all cells are selected
1872 bool const all_selected = cur.depth() > 1
1873 && cur.selBegin().at_begin()
1874 && cur.selEnd().at_end();
1875 // true if some cells are selected
1876 bool const cells_selected = cur.depth() > 1
1877 && cur.selBegin().at_cell_begin()
1878 && cur.selEnd().at_cell_end();
1879 if (all_selected || (cells_selected && !cur.inset().isTable())) {
1880 // All the contents of the inset if selected, or only at
1881 // least one cell but inset is not a table.
1882 // Select the inset from outside.
1885 cur.selection(true);
1887 } else if (cells_selected) {
1888 // At least one complete cell is selected and inset is a table.
1893 cur.selection(true);
1894 cur.idx() = cur.lastidx();
1895 cur.pos() = cur.lastpos();
1897 // select current cell
1901 cur.selection(true);
1902 cur.pit() = cur.lastpit();
1903 cur.pos() = cur.lastpos();
1905 cur.setCurrentFont();
1906 dr.screenUpdate(Update::Force);
1911 case LFUN_UNICODE_INSERT: {
1912 if (cmd.argument().empty())
1915 FuncCode code = cur.inset().currentMode() == Inset::MATH_MODE ?
1916 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
1919 docstring const arg = from_utf8(cmd.getArg(i));
1923 LYXERR0("Not a hexstring: " << arg);
1927 char_type c = hexToInt(arg);
1928 if (c >= 32 && c < 0x10ffff) {
1929 LYXERR(Debug::KEY, "Inserting c: " << c);
1930 lyx::dispatch(FuncRequest(code, docstring(1, c)));
1938 // This would be in Buffer class if only Cursor did not
1939 // require a bufferview
1940 case LFUN_INSET_FORALL: {
1941 docstring const name = from_utf8(cmd.getArg(0));
1942 string const commandstr = cmd.getLongArg(1);
1943 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1945 // an arbitrary number to limit number of iterations
1946 const int max_iter = 100000;
1948 Cursor & curs = d->cursor_;
1949 Cursor const savecur = curs;
1951 if (!curs.nextInset())
1952 curs.forwardInset();
1953 curs.beginUndoGroup();
1954 while(curs && iterations < max_iter) {
1955 Inset * const ins = curs.nextInset();
1958 docstring insname = ins->layoutName();
1959 while (!insname.empty()) {
1960 if (insname == name || name == from_utf8("*")) {
1962 lyx::dispatch(fr, dr);
1966 size_t const i = insname.rfind(':');
1967 if (i == string::npos)
1969 insname = insname.substr(0, i);
1971 // if we did not delete the inset, skip it
1972 if (!curs.nextInset() || curs.nextInset() == ins)
1973 curs.forwardInset();
1977 /** This is a dummy undo record only to remember the cursor
1978 * that has just been set; this will be used on a redo action
1979 * (see ticket #10097)
1981 * FIXME: a better fix would be to have a way to set the
1982 * cursor value directly, but I am not sure it is worth it.
1985 curs.endUndoGroup();
1986 dr.screenUpdate(Update::Force);
1987 dr.forceBufferUpdate();
1989 if (iterations >= max_iter) {
1991 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1993 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1998 case LFUN_BRANCH_ADD_INSERT: {
1999 docstring branch_name = from_utf8(cmd.getArg(0));
2000 if (branch_name.empty())
2001 if (!Alert::askForText(branch_name, _("Branch name")) ||
2002 branch_name.empty())
2005 DispatchResult drtmp;
2006 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
2007 if (drtmp.error()) {
2008 Alert::warning(_("Branch already exists"), drtmp.message());
2011 docstring const sep = buffer_.params().branchlist().separator();
2012 for (docstring const & branch : getVectorFromString(branch_name, sep))
2013 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch));
2017 case LFUN_KEYMAP_OFF:
2018 getIntl().keyMapOn(false);
2021 case LFUN_KEYMAP_PRIMARY:
2022 getIntl().keyMapPrim();
2025 case LFUN_KEYMAP_SECONDARY:
2026 getIntl().keyMapSec();
2029 case LFUN_KEYMAP_TOGGLE:
2030 getIntl().toggleKeyMap();
2033 case LFUN_DIALOG_SHOW_NEW_INSET: {
2034 string const name = cmd.getArg(0);
2035 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2036 if (decodeInsetParam(name, data, buffer_))
2037 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
2039 lyxerr << "Inset type '" << name <<
2040 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
2044 case LFUN_CITATION_INSERT: {
2045 if (argument.empty()) {
2046 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
2049 // we can have one optional argument, delimited by '|'
2050 // citation-insert <key>|<text_before>
2051 // this should be enhanced to also support text_after
2052 // and citation style
2053 string arg = argument;
2055 if (contains(argument, "|")) {
2056 arg = token(argument, '|', 0);
2057 opt1 = token(argument, '|', 1);
2060 // if our cursor is directly in front of or behind a citation inset,
2061 // we will instead add the new key to it.
2062 Inset * inset = cur.nextInset();
2063 if (!inset || inset->lyxCode() != CITE_CODE)
2064 inset = cur.prevInset();
2065 if (inset && inset->lyxCode() == CITE_CODE) {
2066 InsetCitation * icite = static_cast<InsetCitation *>(inset);
2067 if (icite->addKey(arg)) {
2068 dr.forceBufferUpdate();
2069 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
2071 LYXERR0("Discarding optional argument to citation-insert.");
2076 InsetCommandParams icp(CITE_CODE);
2077 icp["key"] = from_utf8(arg);
2079 icp["before"] = from_utf8(opt1);
2081 from_ascii(InsetCitation::last_literal ? "true" : "false");
2082 string icstr = InsetCommand::params2string(icp);
2083 FuncRequest fr(LFUN_INSET_INSERT, icstr);
2088 case LFUN_INSET_APPLY: {
2089 string const name = cmd.getArg(0);
2090 Inset * inset = editedInset(name);
2092 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2096 // put cursor in front of inset.
2097 if (!setCursorFromInset(inset)) {
2098 LASSERT(false, break);
2101 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2102 inset->dispatch(cur, fr);
2103 dr.screenUpdate(cur.result().screenUpdate());
2104 if (cur.result().needBufferUpdate())
2105 dr.forceBufferUpdate();
2110 // The change of language of buffer belongs to the Buffer class.
2111 // We have to do it here because we need a cursor for Undo.
2112 // When Undo::recordUndoBufferParams() is implemented someday
2113 // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
2114 case LFUN_BUFFER_LANGUAGE: {
2115 Language const * oldL = buffer_.params().language;
2116 Language const * newL = languages.getLanguage(argument);
2117 if (!newL || oldL == newL)
2119 if (oldL->rightToLeft() == newL->rightToLeft()) {
2120 cur.recordUndoFullBuffer();
2121 buffer_.changeLanguage(oldL, newL);
2122 cur.setCurrentFont();
2123 dr.forceBufferUpdate();
2128 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2129 case LFUN_FILE_INSERT_PLAINTEXT: {
2130 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
2131 string const fname = to_utf8(cmd.argument());
2132 if (!FileName::isAbsolute(fname))
2133 dr.setMessage(_("Absolute filename expected."));
2135 insertPlaintextFile(FileName(fname), as_paragraph);
2140 // OK, so try the Buffer itself...
2141 buffer_.dispatch(cmd, dr);
2142 dispatched = dr.dispatched();
2146 buffer_.undo().endUndoGroup();
2147 dr.dispatched(dispatched);
2149 // NOTE: The code below is copied from Cursor::dispatch. If you
2150 // need to modify this, please update the other one too.
2152 // notify insets we just entered/left
2153 if (cursor() != old) {
2154 old.beginUndoGroup();
2156 bool badcursor = notifyCursorLeavesOrEnters(old, cursor());
2158 cursor().fixIfBroken();
2159 resetInlineCompletionPos();
2166 docstring const BufferView::requestSelection()
2168 Cursor & cur = d->cursor_;
2170 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2171 if (!cur.selection()) {
2172 d->xsel_cache_.set = false;
2176 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2177 if (!d->xsel_cache_.set ||
2178 cur.top() != d->xsel_cache_.cursor ||
2179 cur.realAnchor().top() != d->xsel_cache_.anchor)
2181 d->xsel_cache_.cursor = cur.top();
2182 d->xsel_cache_.anchor = cur.realAnchor().top();
2183 d->xsel_cache_.set = cur.selection();
2184 return cur.selectionAsString(false);
2190 void BufferView::clearSelection()
2192 d->cursor_.clearSelection();
2193 // Clear the selection buffer. Otherwise a subsequent
2194 // middle-mouse-button paste would use the selection buffer,
2195 // not the more current external selection.
2196 cap::clearSelection();
2197 d->xsel_cache_.set = false;
2198 // The buffer did not really change, but this causes the
2199 // redraw we need because we cleared the selection above.
2200 buffer_.changed(false);
2204 void BufferView::resize(int width, int height)
2206 // Update from work area
2210 // Clear the paragraph height cache.
2211 d->par_height_.clear();
2212 // Redo the metrics.
2217 Inset const * BufferView::getCoveringInset(Text const & text,
2220 TextMetrics & tm = d->text_metrics_[&text];
2221 Inset * inset = tm.checkInsetHit(x, y);
2225 if (!inset->descendable(*this))
2226 // No need to go further down if the inset is not
2230 size_t cell_number = inset->nargs();
2231 // Check all the inner cell.
2232 for (size_t i = 0; i != cell_number; ++i) {
2233 Text const * inner_text = inset->getText(i);
2236 Inset const * inset_deeper =
2237 getCoveringInset(*inner_text, x, y);
2239 return inset_deeper;
2247 void BufferView::updateHoveredInset() const
2249 // Get inset under mouse, if there is one.
2250 int const x = d->mouse_position_cache_.x_;
2251 int const y = d->mouse_position_cache_.y_;
2252 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2254 d->clickable_inset_ = covering_inset && covering_inset->clickable(*this, x, y);
2256 if (covering_inset == d->last_inset_)
2257 // Same inset, no need to do anything...
2260 bool need_redraw = false;
2261 if (d->last_inset_) {
2262 // Remove the hint on the last hovered inset (if any).
2263 need_redraw |= d->last_inset_->setMouseHover(this, false);
2267 if (covering_inset && covering_inset->setMouseHover(this, true)) {
2269 // Only the insets that accept the hover state, do
2270 // clear the last_inset_, so only set the last_inset_
2271 // member if the hovered setting is accepted.
2272 d->last_inset_ = covering_inset;
2276 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2277 << d->mouse_position_cache_.x_ << ", "
2278 << d->mouse_position_cache_.y_ << ")");
2280 d->update_strategy_ = DecorationUpdate;
2282 // This event (moving without mouse click) is not passed further.
2283 // This should be changed if it is further utilized.
2284 buffer_.changed(false);
2289 void BufferView::clearLastInset(Inset * inset) const
2291 if (d->last_inset_ != inset) {
2292 LYXERR0("Wrong last_inset!");
2299 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2301 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2303 // This is only called for mouse related events including
2304 // LFUN_FILE_OPEN generated by drag-and-drop.
2305 FuncRequest cmd = cmd0;
2307 Cursor old = cursor();
2309 cur.push(buffer_.inset());
2310 cur.selection(d->cursor_.selection());
2312 // Either the inset under the cursor or the
2313 // surrounding Text will handle this event.
2315 // make sure we stay within the screen...
2316 cmd.set_y(min(max(cmd.y(), -1), height_));
2318 d->mouse_position_cache_.x_ = cmd.x();
2319 d->mouse_position_cache_.y_ = cmd.y();
2321 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2322 updateHoveredInset();
2326 // Build temporary cursor.
2327 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2329 // If inset is not editable, cur.pos() might point behind the
2330 // inset (depending on cmd.x(), cmd.y()). This is needed for
2331 // editing to fix bug 9628, but e.g. the context menu needs a
2332 // cursor in front of the inset.
2333 if ((inset->hasSettings() || !inset->contextMenuName().empty()
2334 || inset->lyxCode() == SEPARATOR_CODE) &&
2335 cur.nextInset() != inset && cur.prevInset() == inset)
2337 } else if (cur.inTexted() && cur.pos()
2338 && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
2339 // Always place cursor in front of a separator inset.
2343 // Put anchor at the same position.
2346 cur.beginUndoGroup();
2348 // Try to dispatch to an non-editable inset near this position
2349 // via the temp cursor. If the inset wishes to change the real
2350 // cursor it has to do so explicitly by using
2351 // cur.bv().cursor() = cur; (or similar)
2353 inset->dispatch(cur, cmd);
2355 // Now dispatch to the temporary cursor. If the real cursor should
2356 // be modified, the inset's dispatch has to do so explicitly.
2357 if (!inset || !cur.result().dispatched())
2360 // Notify left insets
2362 bool badcursor = old.fixIfBroken() | cur.fixIfBroken();
2363 badcursor |= notifyCursorLeavesOrEnters(old, cur);
2365 cursor().fixIfBroken();
2370 // Do we have a selection?
2371 theSelection().haveSelection(cursor().selection());
2373 if (cur.needBufferUpdate()) {
2374 cur.clearBufferUpdate();
2375 buffer().updateBuffer();
2378 // If the command has been dispatched,
2379 if (cur.result().dispatched() || cur.result().screenUpdate())
2380 processUpdateFlags(cur.result().screenUpdate());
2384 int BufferView::minVisiblePart()
2386 return 2 * defaultRowHeight();
2390 int BufferView::scroll(int y)
2393 return scrollDown(y);
2395 return scrollUp(-y);
2400 int BufferView::scrollDown(int offset)
2402 Text * text = &buffer_.text();
2403 TextMetrics & tm = d->text_metrics_[text];
2404 int const ymax = height_ + offset;
2406 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2407 int bottom_pos = last.second->position() + last.second->descent();
2408 if (lyxrc.scroll_below_document)
2409 bottom_pos += height_ - minVisiblePart();
2410 if (last.first + 1 == int(text->paragraphs().size())) {
2411 if (bottom_pos <= height_)
2413 offset = min(offset, bottom_pos - height_);
2416 if (bottom_pos > ymax)
2418 tm.newParMetricsDown();
2420 d->anchor_ypos_ -= offset;
2425 int BufferView::scrollUp(int offset)
2427 Text * text = &buffer_.text();
2428 TextMetrics & tm = d->text_metrics_[text];
2429 int ymin = - offset;
2431 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2432 int top_pos = first.second->position() - first.second->ascent();
2433 if (first.first == 0) {
2436 offset = min(offset, - top_pos);
2441 tm.newParMetricsUp();
2443 d->anchor_ypos_ += offset;
2448 bool BufferView::setCursorFromRow(int row)
2450 TexRow::TextEntry start, end;
2451 tie(start,end) = buffer_.texrow().getEntriesFromRow(row);
2452 LYXERR(Debug::LATEX,
2453 "setCursorFromRow: for row " << row << ", TexRow has found "
2454 "start (id=" << start.id << ",pos=" << start.pos << "), "
2455 "end (id=" << end.id << ",pos=" << end.pos << ")");
2456 return setCursorFromEntries(start, end);
2460 bool BufferView::setCursorFromEntries(TexRow::TextEntry start,
2461 TexRow::TextEntry end)
2463 DocIterator dit_start, dit_end;
2464 tie(dit_start,dit_end) =
2465 TexRow::getDocIteratorsFromEntries(start, end, buffer_);
2468 // Setting selection start
2469 d->cursor_.clearSelection();
2470 setCursor(dit_start);
2471 // Setting selection end
2473 d->cursor_.resetAnchor();
2474 setCursorSelectionTo(dit_end);
2480 bool BufferView::setCursorFromInset(Inset const * inset)
2482 // are we already there?
2483 if (cursor().nextInset() == inset)
2486 // Inset is not at cursor position. Find it in the document.
2489 while (cur && cur.nextInset() != inset)
2500 void BufferView::gotoLabel(docstring const & label)
2502 for (Buffer const * buf : buffer().allRelatives()) {
2504 for (TocItem const & item : *buf->tocBackend().toc("label")) {
2505 if (label == item.str()) {
2506 lyx::dispatch(item.action());
2514 TextMetrics const & BufferView::textMetrics(Text const * t) const
2516 return const_cast<BufferView *>(this)->textMetrics(t);
2520 TextMetrics & BufferView::textMetrics(Text const * t)
2523 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2524 if (tmc_it == d->text_metrics_.end()) {
2525 tmc_it = d->text_metrics_.insert(
2526 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2528 return tmc_it->second;
2532 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2535 return textMetrics(t).parMetrics(pit);
2539 int BufferView::workHeight() const
2545 void BufferView::setCursor(DocIterator const & dit)
2548 size_t const n = dit.depth();
2549 for (size_t i = 0; i < n; ++i)
2550 dit[i].inset().edit(d->cursor_, true);
2552 d->cursor_.setCursor(dit);
2553 d->cursor_.selection(false);
2554 d->cursor_.setCurrentFont();
2556 // It seems on general grounds as if this is probably needed, but
2557 // it is not yet clear.
2558 // See bug #7394 and r38388.
2559 // d->cursor.resetAnchor();
2563 void BufferView::setCursorSelectionTo(DocIterator const & dit)
2565 size_t const n = dit.depth();
2566 for (size_t i = 0; i < n; ++i)
2567 dit[i].inset().edit(d->cursor_, true);
2569 d->cursor_.selection(true);
2570 d->cursor_.setCursorSelectionTo(dit);
2571 d->cursor_.setCurrentFont();
2575 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2577 // Would be wrong to delete anything if we have a selection.
2578 if (cur.selection())
2581 bool need_anchor_change = false;
2582 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2583 need_anchor_change);
2585 if (need_anchor_change)
2593 // we would rather not do this here, but it needs to be done before
2594 // the changed() signal is sent.
2595 buffer_.updateBuffer();
2597 buffer_.changed(true);
2602 bool BufferView::mouseSetCursor(Cursor & cur, bool const select)
2604 LASSERT(&cur.bv() == this, return false);
2607 // this event will clear selection so we save selection for
2608 // persistent selection
2609 cap::saveSelection(cursor());
2611 d->cursor_.macroModeClose();
2612 // If a macro has been finalized, the cursor might have been broken
2615 // Has the cursor just left the inset?
2616 bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2618 d->cursor_.fixIfBroken();
2620 // do the dEPM magic if needed
2621 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2622 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2623 // the leftinset bool would not be necessary (badcursor instead).
2624 bool update = leftinset;
2627 d->cursor_.setSelection();
2628 d->cursor_.setCursorSelectionTo(cur);
2630 if (d->cursor_.inTexted())
2631 update |= checkDepm(cur, d->cursor_);
2632 d->cursor_.resetAnchor();
2633 d->cursor_.setCursor(cur);
2634 d->cursor_.clearSelection();
2636 d->cursor_.boundary(cur.boundary());
2637 d->cursor_.finishUndo();
2638 d->cursor_.setCurrentFont();
2640 cur.forceBufferUpdate();
2645 void BufferView::putSelectionAt(DocIterator const & cur,
2646 int length, bool backwards)
2648 d->cursor_.clearSelection();
2654 d->cursor_.pos() += length;
2655 d->cursor_.setSelection(d->cursor_, -length);
2657 d->cursor_.setSelection(d->cursor_, length);
2662 bool BufferView::selectIfEmpty(DocIterator & cur)
2664 if ((cur.inTexted() && !cur.paragraph().empty())
2665 || (cur.inMathed() && !cur.cell().empty()))
2668 pit_type const beg_pit = cur.pit();
2670 // The paragraph associated to this item isn't
2671 // the first one, so it can be selected
2674 // We have to resort to select the space between the
2675 // end of this item and the begin of the next one
2679 // If it is the only item in the document,
2680 // nothing can be selected
2683 pit_type const end_pit = cur.pit();
2684 pos_type const end_pos = cur.pos();
2685 d->cursor_.clearSelection();
2687 d->cursor_.setCursor(cur);
2688 d->cursor_.pit() = beg_pit;
2689 d->cursor_.pos() = 0;
2690 d->cursor_.selection(false);
2691 d->cursor_.resetAnchor();
2692 d->cursor_.pit() = end_pit;
2693 d->cursor_.pos() = end_pos;
2694 d->cursor_.setSelection();
2699 Cursor & BufferView::cursor()
2705 Cursor const & BufferView::cursor() const
2711 bool BufferView::singleParUpdate()
2713 Text & buftext = buffer_.text();
2714 pit_type const bottom_pit = d->cursor_.bottom().pit();
2715 TextMetrics & tm = textMetrics(&buftext);
2716 int old_height = tm.parMetrics(bottom_pit).height();
2718 // make sure inline completion pointer is ok
2719 if (d->inlineCompletionPos_.fixIfBroken())
2720 d->inlineCompletionPos_ = DocIterator();
2722 // In Single Paragraph mode, rebreak only
2723 // the (main text, not inset!) paragraph containing the cursor.
2724 // (if this paragraph contains insets etc., rebreaking will
2725 // recursively descend)
2726 tm.redoParagraph(bottom_pit);
2727 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2728 if (pm.height() != old_height)
2729 // Paragraph height has changed so we cannot proceed to
2730 // the singlePar optimisation.
2733 tm.updatePosCache(bottom_pit);
2735 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2736 << " y2: " << pm.position() + pm.descent()
2737 << " pit: " << bottom_pit
2738 << " singlepar: 1");
2743 void BufferView::updateMetrics()
2745 updateMetrics(d->update_flags_);
2746 d->update_strategy_ = FullScreenUpdate;
2750 void BufferView::updateMetrics(Update::flags & update_flags)
2752 if (height_ == 0 || width_ == 0)
2755 Text & buftext = buffer_.text();
2756 pit_type const npit = int(buftext.paragraphs().size());
2758 // Clear out the position cache in case of full screen redraw,
2759 d->coord_cache_.clear();
2761 // Clear out paragraph metrics to avoid having invalid metrics
2762 // in the cache from paragraphs not relayouted below
2763 // The complete text metrics will be redone.
2764 d->text_metrics_.clear();
2766 TextMetrics & tm = textMetrics(&buftext);
2768 // make sure inline completion pointer is ok
2769 if (d->inlineCompletionPos_.fixIfBroken())
2770 d->inlineCompletionPos_ = DocIterator();
2772 if (d->anchor_pit_ >= npit)
2773 // The anchor pit must have been deleted...
2774 d->anchor_pit_ = npit - 1;
2776 // Rebreak anchor paragraph.
2777 tm.redoParagraph(d->anchor_pit_);
2778 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2781 if (d->anchor_pit_ == 0) {
2782 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2784 // Complete buffer visible? Then it's easy.
2785 if (scrollRange == 0)
2786 d->anchor_ypos_ = anchor_pm.ascent();
2788 // avoid empty space above the first row
2789 d->anchor_ypos_ = min(d->anchor_ypos_, anchor_pm.ascent());
2792 anchor_pm.setPosition(d->anchor_ypos_);
2793 tm.updatePosCache(d->anchor_pit_);
2795 LYXERR(Debug::PAINTING, "metrics: "
2796 << " anchor pit = " << d->anchor_pit_
2797 << " anchor ypos = " << d->anchor_ypos_);
2799 // Redo paragraphs above anchor if necessary.
2800 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2801 // We are now just above the anchor paragraph.
2802 pit_type pit1 = d->anchor_pit_ - 1;
2803 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2804 tm.redoParagraph(pit1);
2805 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2807 // Save the paragraph position in the cache.
2809 tm.updatePosCache(pit1);
2813 // Redo paragraphs below the anchor if necessary.
2814 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2815 // We are now just below the anchor paragraph.
2816 pit_type pit2 = d->anchor_pit_ + 1;
2817 for (; pit2 < npit && y2 <= height_; ++pit2) {
2818 tm.redoParagraph(pit2);
2819 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2821 // Save the paragraph position in the cache.
2823 tm.updatePosCache(pit2);
2827 LYXERR(Debug::PAINTING, "Metrics: "
2828 << " anchor pit = " << d->anchor_pit_
2829 << " anchor ypos = " << d->anchor_ypos_
2832 << " pit1 = " << pit1
2833 << " pit2 = " << pit2);
2835 // metrics is done, full drawing is necessary now
2836 update_flags = (update_flags & ~Update::Force) | Update::ForceDraw;
2838 // Now update the positions of insets in the cache.
2841 if (lyxerr.debugging(Debug::WORKAREA)) {
2842 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2843 d->coord_cache_.dump();
2848 void BufferView::updatePosCache()
2850 // this is the "nodraw" drawing stage: only set the positions of the
2851 // insets in metrics cache.
2852 frontend::NullPainter np;
2857 void BufferView::insertLyXFile(FileName const & fname)
2859 LASSERT(d->cursor_.inTexted(), return);
2861 // Get absolute path of file and add ".lyx"
2862 // to the filename if necessary
2863 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2865 docstring const disp_fn = makeDisplayPath(filename.absFileName());
2866 // emit message signal.
2867 message(bformat(_("Inserting document %1$s..."), disp_fn));
2870 Buffer buf(filename.absFileName(), false);
2871 if (buf.loadLyXFile() == Buffer::ReadSuccess) {
2872 ErrorList & el = buffer_.errorList("Parse");
2873 // Copy the inserted document error list into the current buffer one.
2874 el = buf.errorList("Parse");
2875 buffer_.undo().recordUndo(d->cursor_);
2876 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2877 buf.params().documentClassPtr(), el);
2878 res = _("Document %1$s inserted.");
2880 res = _("Could not insert document %1$s");
2883 buffer_.changed(true);
2884 // emit message signal.
2885 message(bformat(res, disp_fn));
2889 Point BufferView::coordOffset(DocIterator const & dit) const
2895 // Addup contribution of nested insets, from inside to outside,
2896 // keeping the outer paragraph for a special handling below
2897 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2898 CursorSlice const & sl = dit[i];
2902 // get relative position inside sl.inset()
2903 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2905 // Make relative position inside of the edited inset relative to sl.inset()
2909 // In case of an RTL inset, the edited inset will be positioned to the left
2912 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2913 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2918 // remember width for the case that sl.inset() is positioned in an RTL inset
2919 lastw = sl.inset().dimension(*this).wid;
2921 //lyxerr << "Cursor::getPos, i: "
2922 // << i << " x: " << xx << " y: " << y << endl;
2925 // Add contribution of initial rows of outermost paragraph
2926 CursorSlice const & sl = dit[0];
2927 TextMetrics const & tm = textMetrics(sl.text());
2928 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2930 LBUFERR(!pm.rows().empty());
2931 y -= pm.rows()[0].ascent();
2933 // FIXME: document this mess
2935 if (sl.pos() > 0 && dit.depth() == 1) {
2937 if (pos && dit.boundary())
2939 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2940 rend = pm.pos2row(pos);
2942 rend = pm.pos2row(sl.pos());
2944 size_t rend = pm.pos2row(sl.pos());
2946 for (size_t rit = 0; rit != rend; ++rit)
2947 y += pm.rows()[rit].height();
2948 y += pm.rows()[rend].ascent();
2950 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2952 // Make relative position from the nested inset now bufferview absolute.
2953 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2956 // In the RTL case place the nested inset at the left of the cursor in
2957 // the outer paragraph
2958 bool boundary_1 = dit.boundary() && 1 == dit.depth();
2959 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2967 Point BufferView::getPos(DocIterator const & dit) const
2969 if (!paragraphVisible(dit))
2970 return Point(-1, -1);
2972 CursorSlice const & bot = dit.bottom();
2973 TextMetrics const & tm = textMetrics(bot.text());
2975 // offset from outer paragraph
2976 Point p = coordOffset(dit);
2977 p.y_ += tm.parMetrics(bot.pit()).position();
2982 bool BufferView::paragraphVisible(DocIterator const & dit) const
2984 CursorSlice const & bot = dit.bottom();
2985 TextMetrics const & tm = textMetrics(bot.text());
2987 return tm.contains(bot.pit());
2991 void BufferView::caretPosAndHeight(Point & p, int & h) const
2993 Cursor const & cur = cursor();
2994 Font const font = cur.real_current_font;
2995 frontend::FontMetrics const & fm = theFontMetrics(font);
2996 int const asc = fm.maxAscent();
2997 int const des = fm.maxDescent();
3004 bool BufferView::cursorInView(Point const & p, int h) const
3006 Cursor const & cur = cursor();
3007 // does the cursor touch the screen ?
3008 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
3014 int BufferView::horizScrollOffset() const
3016 return d->horiz_scroll_offset_;
3020 int BufferView::horizScrollOffset(Text const * text,
3021 pit_type pit, pos_type pos) const
3023 // Is this a row that is currently scrolled?
3024 if (!d->current_row_slice_.empty()
3025 && &text->inset() == d->current_row_slice_.inset().asInsetText()
3026 && pit == d->current_row_slice_.pit()
3027 && pos == d->current_row_slice_.pos())
3028 return d->horiz_scroll_offset_;
3033 bool BufferView::hadHorizScrollOffset(Text const * text,
3034 pit_type pit, pos_type pos) const
3036 return !d->last_row_slice_.empty()
3037 && &text->inset() == d->last_row_slice_.inset().asInsetText()
3038 && pit == d->last_row_slice_.pit()
3039 && pos == d->last_row_slice_.pos();
3043 void BufferView::setCurrentRowSlice(CursorSlice const & rowSlice)
3045 // nothing to do if the cursor was already on this row
3046 if (d->current_row_slice_ == rowSlice) {
3047 d->last_row_slice_ = CursorSlice();
3051 // if the (previous) current row was scrolled, we have to
3052 // remember it in order to repaint it next time.
3053 if (d->horiz_scroll_offset_ != 0)
3054 d->last_row_slice_ = d->current_row_slice_;
3056 d->last_row_slice_ = CursorSlice();
3058 // Since we changed row, the scroll offset is not valid anymore
3059 d->horiz_scroll_offset_ = 0;
3060 d->current_row_slice_ = rowSlice;
3066 bool sliceInRow(CursorSlice const & cs, Text const * text, Row const & row)
3068 /* The normal case is the last line. The previous line takes care
3069 * of empty rows (e.g. empty paragraphs). Cursor boundary issues
3070 * are taken care of when setting caret_slice_ in
3073 return !cs.empty() && cs.text() == text && cs.pit() == row.pit()
3074 && ((row.pos() == row.endpos() && row.pos() == cs.pos())
3075 || (row.pos() <= cs.pos() && cs.pos() < row.endpos()));
3081 bool BufferView::needRepaint(Text const * text, Row const & row) const
3083 return d->repaint_caret_row_ && sliceInRow(d->caret_slice_, text, row);
3087 void BufferView::checkCursorScrollOffset()
3089 CursorSlice rowSlice = d->cursor_.bottom();
3090 TextMetrics const & tm = textMetrics(rowSlice.text());
3092 // Stop if metrics have not been computed yet, since it means
3093 // that there is nothing to do.
3094 if (!tm.contains(rowSlice.pit()))
3096 ParagraphMetrics const & pm = tm.parMetrics(rowSlice.pit());
3097 Row const & row = pm.getRow(rowSlice.pos(),
3098 d->cursor_.boundary() && rowSlice == d->cursor_.top());
3099 rowSlice.pos() = row.pos();
3101 // Set the row on which the cursor lives.
3102 setCurrentRowSlice(rowSlice);
3104 // Current x position of the cursor in pixels
3105 int cur_x = getPos(d->cursor_).x_;
3107 // Horizontal scroll offset of the cursor row in pixels
3108 int offset = d->horiz_scroll_offset_;
3109 int const MARGIN = 2 * theFontMetrics(d->cursor_.real_current_font).em()
3111 if (row.right_x() <= workWidth() - row.right_margin) {
3112 // Row is narrower than the work area, no offset needed.
3115 if (cur_x - offset < MARGIN) {
3116 // cursor would be too far right
3117 offset = cur_x - MARGIN;
3118 } else if (cur_x - offset > workWidth() - MARGIN) {
3119 // cursor would be too far left
3120 offset = cur_x - workWidth() + MARGIN;
3122 // Correct the offset to make sure that we do not scroll too much
3125 if (row.right_x() - offset < workWidth() - row.right_margin)
3126 offset = row.right_x() - workWidth() + row.right_margin;
3129 //lyxerr << "cur_x=" << cur_x << ", offset=" << offset << ", row.wid=" << row.width() << ", margin=" << MARGIN << endl;
3131 if (offset != d->horiz_scroll_offset_)
3132 LYXERR(Debug::PAINTING, "Horiz. scroll offset changed from "
3133 << d->horiz_scroll_offset_ << " to " << offset);
3135 if (d->update_strategy_ == NoScreenUpdate
3136 && (offset != d->horiz_scroll_offset_
3137 || !d->last_row_slice_.empty())) {
3138 // FIXME: if one uses SingleParUpdate, then home/end
3139 // will not work on long rows. Why?
3140 d->update_strategy_ = FullScreenUpdate;
3143 d->horiz_scroll_offset_ = offset;
3147 void BufferView::draw(frontend::Painter & pain, bool paint_caret)
3149 if (height_ == 0 || width_ == 0)
3151 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t--- START NODRAW ---"
3152 : "\t\t*** START DRAWING ***"));
3153 Text & text = buffer_.text();
3154 TextMetrics const & tm = d->text_metrics_[&text];
3155 int const y = tm.first().second->position();
3156 PainterInfo pi(this, pain);
3158 /** A repaint of the previous caret row is needed if there is
3159 * caret painted on screen and either
3160 * 1/ a new caret has to be painted at a place different from
3162 * 2/ there is no need for a caret anymore.
3164 d->repaint_caret_row_ = !d->caret_slice_.empty() &&
3165 ((paint_caret && d->cursor_.top() != d->caret_slice_)
3168 // Check whether the row where the cursor lives needs to be scrolled.
3169 // Update the drawing strategy if needed.
3170 checkCursorScrollOffset();
3172 switch (d->update_strategy_) {
3174 case NoScreenUpdate:
3175 // no screen painting is actually needed. In nodraw stage
3176 // however, the different coordinates of insets and paragraphs
3177 // needs to be updated.
3178 LYXERR(Debug::PAINTING, "Strategy: NoScreenUpdate");
3179 pi.full_repaint = false;
3180 if (pain.isNull()) {
3181 pi.full_repaint = true;
3183 } else if (d->repaint_caret_row_) {
3184 pi.full_repaint = false;
3189 case SingleParUpdate:
3190 pi.full_repaint = false;
3191 LYXERR(Debug::PAINTING, "Strategy: SingleParUpdate");
3192 // In general, only the current row of the outermost paragraph
3193 // will be redrawn. Particular cases where selection spans
3194 // multiple paragraph are correctly detected in TextMetrics.
3198 case DecorationUpdate:
3199 // FIXME: We should also distinguish DecorationUpdate to avoid text
3200 // drawing if possible. This is not possible to do easily right now
3201 // because of the single backing pixmap.
3203 case FullScreenUpdate:
3205 LYXERR(Debug::PAINTING,
3206 ((d->update_strategy_ == FullScreenUpdate)
3207 ? "Strategy: FullScreenUpdate"
3208 : "Strategy: DecorationUpdate"));
3210 // The whole screen, including insets, will be refreshed.
3211 pi.full_repaint = true;
3213 // Clear background.
3214 pain.fillRectangle(0, 0, width_, height_,
3215 pi.backgroundColor(&buffer_.inset()));
3220 // and possibly grey out below
3221 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3222 int const y2 = lastpm.second->position() + lastpm.second->descent();
3225 Color color = buffer().isInternal()
3226 ? Color_background : Color_bottomarea;
3227 pain.fillRectangle(0, y2, width_, height_ - y2, color);
3231 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t --- END NODRAW ---"
3232 : "\t\t *** END DRAWING ***"));
3234 // The scrollbar needs an update.
3237 // Normalize anchor for next time
3238 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
3239 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3240 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
3241 ParagraphMetrics const & pm = tm.parMetrics(pit);
3242 if (pm.position() + pm.descent() > 0) {
3243 if (d->anchor_pit_ != pit
3244 || d->anchor_ypos_ != pm.position())
3245 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
3246 << " anchor ypos = " << d->anchor_ypos_);
3247 d->anchor_pit_ = pit;
3248 d->anchor_ypos_ = pm.position();
3252 if (!pain.isNull()) {
3253 // reset the update flags, everything has been done
3254 d->update_flags_ = Update::None;
3257 // Remember what has just been done for the next draw() step
3259 d->caret_slice_ = d->cursor_.top();
3260 if (d->caret_slice_.pos() > 0
3261 && (d->cursor_.boundary()
3262 || d->caret_slice_.pos() == d->caret_slice_.lastpos()))
3263 --d->caret_slice_.pos();
3265 d->caret_slice_ = CursorSlice();
3269 void BufferView::message(docstring const & msg)
3272 d->gui_->message(msg);
3276 void BufferView::showDialog(string const & name)
3279 d->gui_->showDialog(name, string());
3283 void BufferView::showDialog(string const & name,
3284 string const & data, Inset * inset)
3287 d->gui_->showDialog(name, data, inset);
3291 void BufferView::updateDialog(string const & name, string const & data)
3294 d->gui_->updateDialog(name, data);
3298 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
3304 // FIXME: Move this out of BufferView again
3305 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
3307 if (!fname.isReadableFile()) {
3308 docstring const error = from_ascii(strerror(errno));
3309 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3310 docstring const text =
3311 bformat(_("Could not read the specified document\n"
3312 "%1$s\ndue to the error: %2$s"), file, error);
3313 Alert::error(_("Could not read file"), text);
3317 if (!fname.isReadableFile()) {
3318 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3319 docstring const text =
3320 bformat(_("%1$s\n is not readable."), file);
3321 Alert::error(_("Could not open file"), text);
3325 // FIXME UNICODE: We don't know the encoding of the file
3326 docstring file_content = fname.fileContents("UTF-8");
3327 if (file_content.empty()) {
3328 Alert::error(_("Reading not UTF-8 encoded file"),
3329 _("The file is not UTF-8 encoded.\n"
3330 "It will be read as local 8Bit-encoded.\n"
3331 "If this does not give the correct result\n"
3332 "then please change the encoding of the file\n"
3333 "to UTF-8 with a program other than LyX.\n"));
3334 file_content = fname.fileContents("local8bit");
3337 return normalize_c(file_content);
3341 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
3343 docstring const tmpstr = contentsOfPlaintextFile(f);
3348 Cursor & cur = cursor();
3349 cap::replaceSelection(cur);
3350 buffer_.undo().recordUndo(cur);
3352 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3354 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3356 buffer_.changed(true);
3360 docstring const & BufferView::inlineCompletion() const
3362 return d->inlineCompletion_;
3366 size_t const & BufferView::inlineCompletionUniqueChars() const
3368 return d->inlineCompletionUniqueChars_;
3372 DocIterator const & BufferView::inlineCompletionPos() const
3374 return d->inlineCompletionPos_;
3378 void BufferView::resetInlineCompletionPos()
3380 d->inlineCompletionPos_ = DocIterator();
3384 bool samePar(DocIterator const & a, DocIterator const & b)
3386 if (a.empty() && b.empty())
3388 if (a.empty() || b.empty())
3390 if (a.depth() != b.depth())
3392 return &a.innerParagraph() == &b.innerParagraph();
3396 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3397 docstring const & completion, size_t uniqueChars)
3399 uniqueChars = min(completion.size(), uniqueChars);
3400 bool changed = d->inlineCompletion_ != completion
3401 || d->inlineCompletionUniqueChars_ != uniqueChars;
3402 bool singlePar = true;
3403 d->inlineCompletion_ = completion;
3404 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3406 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3409 DocIterator const & old = d->inlineCompletionPos_;
3411 //lyxerr << "inlineCompletionPos changed" << std::endl;
3412 // old or pos are in another paragraph?
3413 if ((!samePar(cur, pos) && !pos.empty())
3414 || (!samePar(cur, old) && !old.empty())) {
3416 //lyxerr << "different paragraph" << std::endl;
3418 d->inlineCompletionPos_ = pos;
3423 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3424 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3426 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3431 bool BufferView::clickableInset() const
3433 return d->clickable_inset_;