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"
69 #include "frontends/alert.h"
70 #include "frontends/Application.h"
71 #include "frontends/Delegates.h"
72 #include "frontends/FontMetrics.h"
73 #include "frontends/NullPainter.h"
74 #include "frontends/Painter.h"
75 #include "frontends/Selection.h"
77 #include "support/convert.h"
78 #include "support/debug.h"
79 #include "support/ExceptionMessage.h"
80 #include "support/filetools.h"
81 #include "support/gettext.h"
82 #include "support/lassert.h"
83 #include "support/lstrings.h"
84 #include "support/lyxlib.h"
85 #include "support/Package.h"
86 #include "support/types.h"
96 using namespace lyx::support;
100 namespace Alert = frontend::Alert;
104 /// Return an inset of this class if it exists at the current cursor position
106 T * getInsetByCode(Cursor const & cur, InsetCode code)
108 DocIterator it = cur;
109 Inset * inset = it.nextInset();
110 if (inset && inset->lyxCode() == code)
111 return static_cast<T*>(inset);
116 /// Note that comparing contents can only be used for InsetCommand
117 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
118 docstring const & contents)
120 DocIterator tmpdit = dit;
123 Inset const * inset = tmpdit.nextInset();
125 bool const valid_code = std::find(codes.begin(), codes.end(),
126 inset->lyxCode()) != codes.end();
127 InsetCommand const * ic = inset->asInsetCommand();
128 bool const same_or_no_contents = contents.empty()
129 || (ic && (ic->getFirstNonOptParam() == contents));
131 if (valid_code && same_or_no_contents) {
136 tmpdit.forwardInset();
143 /// Looks for next inset with one of the given codes.
144 /// Note that same_content can only be used for InsetCommand
145 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
149 DocIterator tmpdit = dit;
150 tmpdit.forwardInset();
154 Inset const * inset = tmpdit.nextInset();
155 if (same_content && inset) {
156 InsetCommand const * ic = inset->asInsetCommand();
158 bool const valid_code = std::find(codes.begin(), codes.end(),
159 ic->lyxCode()) != codes.end();
161 contents = ic->getFirstNonOptParam();
165 if (!findNextInset(tmpdit, codes, contents)) {
166 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
167 Inset * inset = &tmpdit.bottom().inset();
168 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
169 if (!findNextInset(tmpdit, codes, contents))
181 /// Looks for next inset with the given code
182 void findInset(DocIterator & dit, InsetCode code, bool same_content)
184 findInset(dit, vector<InsetCode>(1, code), same_content);
188 /// Moves cursor to the next inset with one of the given codes.
189 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
192 Cursor tmpcur = bv->cursor();
193 if (!findInset(tmpcur, codes, same_content)) {
194 bv->cursor().message(_("No more insets"));
198 tmpcur.clearSelection();
199 bv->setCursor(tmpcur);
204 /// Moves cursor to the next inset with given code.
205 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
207 gotoInset(bv, vector<InsetCode>(1, code), same_content);
211 /// A map from a Text to the associated text metrics
212 typedef map<Text const *, TextMetrics> TextMetricsCache;
214 enum ScreenUpdateStrategy {
224 /////////////////////////////////////////////////////////////////////
228 /////////////////////////////////////////////////////////////////////
230 struct BufferView::Private
232 Private(BufferView & bv) : update_strategy_(FullScreenUpdate),
233 update_flags_(Update::Force),
235 anchor_pit_(0), anchor_ypos_(0),
236 inlineCompletionUniqueChars_(0),
237 last_inset_(0), clickable_inset_(false),
238 mouse_position_cache_(),
239 bookmark_edit_position_(-1), gui_(0),
240 horiz_scroll_offset_(0), repaint_caret_row_(false)
242 xsel_cache_.set = false;
246 ScrollbarParameters scrollbarParameters_;
248 ScreenUpdateStrategy update_strategy_;
250 Update::flags update_flags_;
252 CoordCache coord_cache_;
254 /// Estimated average par height for scrollbar.
256 /// this is used to handle XSelection events in the right manner.
265 pit_type anchor_pit_;
269 vector<int> par_height_;
272 DocIterator inlineCompletionPos_;
274 docstring inlineCompletion_;
276 size_t inlineCompletionUniqueChars_;
278 /// keyboard mapping object.
281 /// last visited inset.
282 /** kept to send setMouseHover(false).
283 * Not owned, so don't delete.
285 Inset const * last_inset_;
286 /// are we hovering something that we can click
287 bool clickable_inset_;
289 /// position of the mouse at the time of the last mouse move
290 /// This is used to update the hovering status of inset in
291 /// cases where the buffer is scrolled, but the mouse didn't move.
292 Point mouse_position_cache_;
294 // cache for id of the paragraph which was edited the last time
295 int bookmark_edit_position_;
297 mutable TextMetricsCache text_metrics_;
300 /** Not owned, so don't delete.
302 frontend::GuiBufferViewDelegate * gui_;
304 /// Cache for Find Next
305 FuncRequest search_request_cache_;
308 map<string, Inset *> edited_insets_;
310 /// When the row where the cursor lies is scrolled, this
311 /// contains the scroll offset
312 int horiz_scroll_offset_;
313 /// a slice pointing to the start of the row where the cursor
314 /// is (at last draw time)
315 CursorSlice current_row_slice_;
316 /// a slice pointing to the start of the row where cursor was
317 /// at previous draw event
318 CursorSlice last_row_slice_;
320 /// a slice pointing to where the cursor has been drawn after the current
322 CursorSlice caret_slice_;
323 /// indicates whether the caret slice needs to be repainted in this draw() run.
324 bool repaint_caret_row_;
328 BufferView::BufferView(Buffer & buf)
329 : width_(0), height_(0), full_screen_(false), buffer_(buf),
330 d(new Private(*this))
332 d->xsel_cache_.set = false;
333 d->intl_.initKeyMapper(lyxrc.use_kbmap);
335 d->cursor_.setBuffer(&buf);
336 d->cursor_.push(buffer_.inset());
337 d->cursor_.resetAnchor();
338 d->cursor_.setCurrentFont();
340 buffer_.updatePreviews();
344 BufferView::~BufferView()
346 // current buffer is going to be switched-off, save cursor pos
347 // Ideally, the whole cursor stack should be saved, but session
348 // currently can only handle bottom (whole document) level pit and pos.
349 // That is to say, if a cursor is in a nested inset, it will be
350 // restore to the left of the top level inset.
351 LastFilePosSection::FilePos fp;
352 fp.pit = d->cursor_.bottom().pit();
353 fp.pos = d->cursor_.bottom().pos();
354 theSession().lastFilePos().save(buffer_.fileName(), fp);
357 d->last_inset_->setMouseHover(this, false);
363 int BufferView::rightMargin() const
365 // The value used to be hardcoded to 10
366 int const default_margin = zoomedPixels(10);
367 // The additional test for the case the outliner is opened.
368 if (!full_screen_ || !lyxrc.full_screen_limit
369 || width_ < lyxrc.full_screen_width + 2 * default_margin)
370 return default_margin;
372 return (width_ - lyxrc.full_screen_width) / 2;
376 int BufferView::leftMargin() const
378 return rightMargin();
382 int BufferView::inPixels(Length const & len) const
384 Font const font = buffer().params().getFont();
385 return len.inPixels(workWidth(), theFontMetrics(font).em());
389 int BufferView::zoomedPixels(int pix) const
391 // FIXME: the dpi setting should really depend on the BufferView
392 // (think different monitors).
394 // Zoom factor specified by user in percent
395 double const zoom = lyxrc.currentZoom / 100.0; // [percent]
397 // DPI setting for monitor relative to 100dpi
398 double const dpizoom = lyxrc.dpi / 100.0; // [per 100dpi]
400 return support::iround(pix * zoom * dpizoom);
404 bool BufferView::isTopScreen() const
406 return 0 == d->scrollbarParameters_.min;
410 bool BufferView::isBottomScreen() const
412 return 0 == d->scrollbarParameters_.max;
416 Intl & BufferView::getIntl()
422 Intl const & BufferView::getIntl() const
428 CoordCache & BufferView::coordCache()
430 return d->coord_cache_;
434 CoordCache const & BufferView::coordCache() const
436 return d->coord_cache_;
440 Buffer & BufferView::buffer()
446 Buffer const & BufferView::buffer() const
452 bool BufferView::needsFitCursor() const
454 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
455 frontend::FontMetrics const & fm =
456 theFontMetrics(d->cursor_.getFont().fontInfo());
457 int const asc = fm.maxAscent();
458 int const des = fm.maxDescent();
459 Point const p = getPos(d->cursor_);
460 if (p.y_ - asc >= 0 && p.y_ + des < height_)
469 // this is for debugging only.
470 string flagsAsString(Update::flags flags)
472 if (flags == Update::None)
474 return string((flags & Update::FitCursor) ? "FitCursor " : "")
475 + ((flags & Update::Force) ? "Force " : "")
476 + ((flags & Update::ForceDraw) ? "ForceDraw " : "")
477 + ((flags & Update::SinglePar) ? "SinglePar " : "");
482 void BufferView::processUpdateFlags(Update::flags flags)
484 LYXERR(Debug::PAINTING, "BufferView::processUpdateFlags( "
485 << flagsAsString(flags) << ") buffer: " << &buffer_);
487 // Case when no explicit update is requested.
488 if (flags == Update::None)
491 // SinglePar is ignored for now (this should probably change). We
492 // set it ourselves below, at the price of always rebreaking the
493 // paragraph at cursor. This can be expensive for large tables.
494 flags = flags & ~Update::SinglePar;
496 // First check whether the metrics and inset positions should be updated
497 if (flags & Update::Force) {
498 // This will update the CoordCache items and replace Force
499 // with ForceDraw in flags.
500 updateMetrics(flags);
503 // Then make sure that the screen contains the cursor if needed
504 if (flags & Update::FitCursor) {
505 if (needsFitCursor()) {
506 scrollToCursor(d->cursor_, false);
507 // Metrics have to be recomputed (maybe again)
508 updateMetrics(flags);
510 flags = flags & ~Update::FitCursor;
513 // Finally detect whether we can only repaint a single paragraph
514 if (!(flags & Update::ForceDraw)) {
515 if (singleParUpdate())
516 flags = flags | Update::SinglePar;
518 updateMetrics(flags);
521 // Add flags to the the update flags. These will be reset to None
522 // after the redraw is actually done
523 d->update_flags_ = d->update_flags_ | flags;
524 LYXERR(Debug::PAINTING, "Cumulative flags: " << flagsAsString(flags));
526 // Now compute the update strategy
527 // Possibly values in flag are None, Decoration, ForceDraw
528 LATTEST((d->update_flags_ & ~(Update::None | Update::SinglePar
529 | Update::Decoration | Update::ForceDraw)) == 0);
531 if (d->update_flags_ & Update::ForceDraw)
532 d->update_strategy_ = FullScreenUpdate;
533 else if (d->update_flags_ & Update::Decoration)
534 d->update_strategy_ = DecorationUpdate;
535 else if (d->update_flags_ & Update::SinglePar)
536 d->update_strategy_ = SingleParUpdate;
538 // no need to redraw anything.
539 d->update_strategy_ = NoScreenUpdate;
542 updateHoveredInset();
545 buffer_.changed(false);
549 void BufferView::updateScrollbar()
551 if (height_ == 0 && width_ == 0)
554 // We prefer fixed size line scrolling.
555 d->scrollbarParameters_.single_step = defaultRowHeight();
556 // We prefer full screen page scrolling.
557 d->scrollbarParameters_.page_step = height_;
559 Text & t = buffer_.text();
560 TextMetrics & tm = d->text_metrics_[&t];
562 LYXERR(Debug::GUI, " Updating scrollbar: height: "
563 << t.paragraphs().size()
564 << " curr par: " << d->cursor_.bottom().pit()
565 << " default height " << defaultRowHeight());
567 size_t const parsize = t.paragraphs().size();
568 if (d->par_height_.size() != parsize) {
569 d->par_height_.clear();
570 // FIXME: We assume a default paragraph height of 2 rows. This
571 // should probably be pondered with the screen width.
572 d->par_height_.resize(parsize, defaultRowHeight() * 2);
575 // Look at paragraph heights on-screen
576 pair<pit_type, ParagraphMetrics const *> first = tm.first();
577 pair<pit_type, ParagraphMetrics const *> last = tm.last();
578 for (pit_type pit = first.first; pit <= last.first; ++pit) {
579 d->par_height_[pit] = tm.parMetrics(pit).height();
580 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
581 << d->par_height_[pit]);
584 int top_pos = first.second->position() - first.second->ascent();
585 int bottom_pos = last.second->position() + last.second->descent();
586 bool first_visible = first.first == 0 && top_pos >= 0;
587 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
588 if (first_visible && last_visible) {
589 d->scrollbarParameters_.min = 0;
590 d->scrollbarParameters_.max = 0;
594 d->scrollbarParameters_.min = top_pos;
595 for (size_t i = 0; i != size_t(first.first); ++i)
596 d->scrollbarParameters_.min -= d->par_height_[i];
597 d->scrollbarParameters_.max = bottom_pos;
598 for (size_t i = last.first + 1; i != parsize; ++i)
599 d->scrollbarParameters_.max += d->par_height_[i];
601 // The reference is the top position so we remove one page.
602 if (lyxrc.scroll_below_document)
603 d->scrollbarParameters_.max -= minVisiblePart();
605 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
607 // 0 must be inside the range as it denotes the current position
608 if (d->scrollbarParameters_.max < 0)
609 d->scrollbarParameters_.max = 0;
610 if (d->scrollbarParameters_.min > 0)
611 d->scrollbarParameters_.min = 0;
615 ScrollbarParameters const & BufferView::scrollbarParameters() const
617 return d->scrollbarParameters_;
621 docstring BufferView::toolTip(int x, int y) const
623 // Get inset under mouse, if there is one.
624 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
626 // No inset, no tooltip...
628 return covering_inset->toolTip(*this, x, y);
632 string BufferView::contextMenu(int x, int y) const
634 //If there is a selection, return the containing inset menu
635 if (d->cursor_.selection())
636 return d->cursor_.inset().contextMenu(*this, x, y);
638 // Get inset under mouse, if there is one.
639 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
641 return covering_inset->contextMenu(*this, x, y);
643 return buffer_.inset().contextMenu(*this, x, y);
648 void BufferView::scrollDocView(int const value, bool update)
650 // The scrollbar values are relative to the top of the screen, therefore the
651 // offset is equal to the target value.
653 // No scrolling at all? No need to redraw anything
657 // If the offset is less than 2 screen height, prefer to scroll instead.
658 if (abs(value) <= 2 * height_) {
659 d->anchor_ypos_ -= value;
660 processUpdateFlags(Update::Force);
664 // cut off at the top
665 if (value <= d->scrollbarParameters_.min) {
666 DocIterator dit = doc_iterator_begin(&buffer_);
667 showCursor(dit, false, update);
668 LYXERR(Debug::SCROLLING, "scroll to top");
672 // cut off at the bottom
673 if (value >= d->scrollbarParameters_.max) {
674 DocIterator dit = doc_iterator_end(&buffer_);
676 showCursor(dit, false, update);
677 LYXERR(Debug::SCROLLING, "scroll to bottom");
681 // find paragraph at target position
682 int par_pos = d->scrollbarParameters_.min;
684 for (; i != int(d->par_height_.size()); ++i) {
685 par_pos += d->par_height_[i];
686 if (par_pos >= value)
690 if (par_pos < value) {
691 // It seems we didn't find the correct pit so stay on the safe side and
693 LYXERR0("scrolling position not found!");
694 scrollDocView(d->scrollbarParameters_.max, update);
698 DocIterator dit = doc_iterator_begin(&buffer_);
700 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
701 showCursor(dit, false, update);
705 // FIXME: this method is not working well.
706 void BufferView::setCursorFromScrollbar()
708 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
710 int const height = 2 * defaultRowHeight();
711 int const first = height;
712 int const last = height_ - height;
714 Cursor const & oldcur = d->cursor_;
716 switch (cursorStatus(oldcur)) {
724 int const y = getPos(oldcur).y_;
725 newy = min(last, max(y, first));
729 // We reset the cursor because cursorStatus() does not
730 // work when the cursor is within mathed.
733 tm.setCursorFromCoordinates(cur, 0, newy);
735 // update the bufferview cursor and notify insets
736 // FIXME: Care about the d->cursor_ flags to redraw if needed
737 Cursor old = d->cursor_;
739 // the DEPM call in mouseSetCursor() might have destroyed the
740 // paragraph the cursor is in.
741 bool badcursor = old.fixIfBroken();
742 badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
744 d->cursor_.fixIfBroken();
748 Change const BufferView::getCurrentChange() const
750 if (!d->cursor_.selection())
751 return Change(Change::UNCHANGED);
753 DocIterator dit = d->cursor_.selectionBegin();
754 // The selected content might have been changed (see #7685)
755 dit = dit.getInnerText();
756 return dit.paragraph().lookupChange(dit.pos());
760 // this could be used elsewhere as well?
761 // FIXME: This does not work within mathed!
762 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
764 Point const p = getPos(dit);
767 if (p.y_ > workHeight())
773 void BufferView::bookmarkEditPosition()
775 // Don't eat cpu time for each keystroke
776 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
779 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
783 void BufferView::saveBookmark(unsigned int idx)
785 // tentatively save bookmark, id and pos will be used to
786 // acturately locate a bookmark in a 'live' lyx session.
787 // pit and pos will be updated with bottom level pit/pos
789 if (!buffer_.isInternal()) {
790 theSession().bookmarks().save(
792 d->cursor_.bottom().pit(),
793 d->cursor_.bottom().pos(),
794 d->cursor_.paragraph().id(),
799 // emit message signal.
800 message(_("Save bookmark"));
805 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
806 int top_id, pos_type top_pos)
808 bool success = false;
811 d->cursor_.clearSelection();
813 // if a valid par_id is given, try it first
814 // This is the case for a 'live' bookmark when unique paragraph ID
815 // is used to track bookmarks.
817 dit = buffer_.getParFromID(top_id);
819 dit.pos() = min(dit.paragraph().size(), top_pos);
820 // Some slices of the iterator may not be
821 // reachable (e.g. closed collapsible inset)
822 // so the dociterator may need to be
823 // shortened. Otherwise, setCursor may crash
824 // lyx when the cursor can not be set to these
826 size_t const n = dit.depth();
827 for (size_t i = 0; i < n; ++i)
828 if (!dit[i].inset().editable()) {
836 // if top_id == 0, or searching through top_id failed
837 // This is the case for a 'restored' bookmark when only bottom
838 // (document level) pit was saved. Because of this, bookmark
839 // restoration is inaccurate. If a bookmark was within an inset,
840 // it will be restored to the left of the outmost inset that contains
842 if (bottom_pit < int(buffer_.paragraphs().size())) {
843 dit = doc_iterator_begin(&buffer_);
845 dit.pit() = bottom_pit;
846 dit.pos() = min(bottom_pos, dit.paragraph().size());
851 // Note: only bottom (document) level pit is set.
853 // set the current font.
854 d->cursor_.setCurrentFont();
855 // Do not forget to reset the anchor (see #9912)
856 d->cursor_.resetAnchor();
857 processUpdateFlags(Update::FitCursor);
864 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
866 if (d->cursor_.real_current_font.isRightToLeft()) {
867 if (d->intl_.keymap == Intl::PRIMARY)
868 d->intl_.keyMapSec();
870 if (d->intl_.keymap == Intl::SECONDARY)
871 d->intl_.keyMapPrim();
874 d->intl_.getTransManager().translateAndInsert(c, t, cur);
878 int BufferView::workWidth() const
884 void BufferView::recenter()
886 showCursor(d->cursor_, true, true);
890 void BufferView::showCursor()
892 showCursor(d->cursor_, false, true);
896 void BufferView::showCursor(DocIterator const & dit,
897 bool recenter, bool update)
899 if (scrollToCursor(dit, recenter) && update)
900 processUpdateFlags(Update::Force);
904 void BufferView::scrollToCursor()
906 if (scrollToCursor(d->cursor_, false))
907 processUpdateFlags(Update::Force);
911 bool BufferView::scrollToCursor(DocIterator const & dit, bool const recenter)
913 // We are not properly started yet, delay until resizing is
918 LYXERR(Debug::SCROLLING, "recentering!");
920 CursorSlice const & bot = dit.bottom();
921 TextMetrics & tm = d->text_metrics_[bot.text()];
923 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
924 int bot_pit = bot.pit();
925 if (bot_pit > max_pit) {
926 // FIXME: Why does this happen?
927 LYXERR0("bottom pit is greater that max pit: "
928 << bot_pit << " > " << max_pit);
932 if (bot_pit == tm.first().first - 1)
933 tm.newParMetricsUp();
934 else if (bot_pit == tm.last().first + 1)
935 tm.newParMetricsDown();
937 if (tm.contains(bot_pit)) {
938 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
939 LBUFERR(!pm.rows().empty());
940 // FIXME: smooth scrolling doesn't work in mathed.
941 CursorSlice const & cs = dit.innerTextSlice();
942 int offset = coordOffset(dit).y_;
943 int ypos = pm.position() + offset;
944 Dimension const & row_dim =
945 pm.getRow(cs.pos(), dit.boundary()).dimension();
948 scrolled = scroll(ypos - height_/2);
950 // We try to visualize the whole row, if the row height is larger than
951 // the screen height, we scroll to a heuristic value of height_ / 4.
952 // FIXME: This heuristic value should be replaced by a recursive search
953 // for a row in the inset that can be visualized completely.
954 else if (row_dim.height() > height_) {
955 if (ypos < defaultRowHeight())
956 scrolled = scroll(ypos - height_ / 4);
957 else if (ypos > height_ - defaultRowHeight())
958 scrolled = scroll(ypos - 3 * height_ / 4);
961 // If the top part of the row falls of the screen, we scroll
962 // up to align the top of the row with the top of the screen.
963 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
964 int ynew = row_dim.ascent();
965 scrolled = scrollUp(ynew - ypos);
968 // If the bottom of the row falls of the screen, we scroll down.
969 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
970 int ynew = height_ - row_dim.descent();
971 scrolled = scrollDown(ypos - ynew);
974 // else, nothing to do, the cursor is already visible so we just return.
975 return scrolled != 0;
978 // fix inline completion position
979 if (d->inlineCompletionPos_.fixIfBroken())
980 d->inlineCompletionPos_ = DocIterator();
982 tm.redoParagraph(bot_pit);
983 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
984 int offset = coordOffset(dit).y_;
986 d->anchor_pit_ = bot_pit;
987 CursorSlice const & cs = dit.innerTextSlice();
988 Dimension const & row_dim =
989 pm.getRow(cs.pos(), dit.boundary()).dimension();
992 d->anchor_ypos_ = height_/2;
993 else if (d->anchor_pit_ == 0)
994 d->anchor_ypos_ = offset + pm.ascent();
995 else if (d->anchor_pit_ == max_pit)
996 d->anchor_ypos_ = height_ - offset - row_dim.descent();
997 else if (offset > height_)
998 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
1000 d->anchor_ypos_ = defaultRowHeight() * 2;
1006 void BufferView::makeDocumentClass()
1008 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1009 buffer_.params().makeDocumentClass();
1010 updateDocumentClass(olddc);
1014 void BufferView::updateDocumentClass(DocumentClassConstPtr olddc)
1016 message(_("Converting document to new document class..."));
1018 StableDocIterator backcur(d->cursor_);
1019 ErrorList & el = buffer_.errorList("Class Switch");
1020 cap::switchBetweenClasses(
1021 olddc, buffer_.params().documentClassPtr(),
1022 static_cast<InsetText &>(buffer_.inset()), el);
1024 setCursor(backcur.asDocIterator(&buffer_));
1026 buffer_.errors("Class Switch");
1030 /** Return the change status at cursor position, taking into account the
1031 * status at each level of the document iterator (a table in a deleted
1032 * footnote is deleted).
1033 * When \param outer is true, the top slice is not looked at.
1035 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
1037 size_t const depth = dit.depth() - (outer ? 1 : 0);
1039 for (size_t i = 0 ; i < depth ; ++i) {
1040 CursorSlice const & slice = dit[i];
1041 if (!slice.inset().inMathed()
1042 && slice.pos() < slice.paragraph().size()) {
1043 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
1044 if (ch != Change::UNCHANGED)
1048 return Change::UNCHANGED;
1052 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1054 FuncCode const act = cmd.action();
1056 // Can we use a readonly buffer?
1057 if (buffer_.isReadonly()
1058 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1059 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1060 if (buffer_.hasReadonlyFlag())
1061 flag.message(from_utf8(N_("Document is read-only")));
1063 flag.message(from_utf8(N_("Document has been modified externally")));
1064 flag.setEnabled(false);
1068 // Are we in a DELETED change-tracking region?
1069 if (lookupChangeType(d->cursor_, true) == Change::DELETED
1070 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1071 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1072 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1073 flag.setEnabled(false);
1077 Cursor & cur = d->cursor_;
1079 if (cur.getStatus(cmd, flag))
1084 // FIXME: This is a bit problematic because we don't check if this is
1085 // a document BufferView or not for these LFUNs. We probably have to
1086 // dispatch both to currentBufferView() and, if that fails,
1087 // to documentBufferView(); same as we do now for current Buffer and
1088 // document Buffer. Ideally those LFUN should go to Buffer as they
1089 // operate on the full Buffer and the cursor is only needed either for
1090 // an Undo record or to restore a cursor position. But we don't know
1091 // how to do that inside Buffer of course.
1092 case LFUN_BUFFER_PARAMS_APPLY:
1093 case LFUN_LAYOUT_MODULES_CLEAR:
1094 case LFUN_LAYOUT_MODULE_ADD:
1095 case LFUN_LAYOUT_RELOAD:
1096 case LFUN_TEXTCLASS_APPLY:
1097 case LFUN_TEXTCLASS_LOAD:
1098 flag.setEnabled(!buffer_.isReadonly());
1102 // We do not use the LyXAction flag for readonly because Undo sets the
1103 // buffer clean/dirty status by itself.
1104 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1107 // We do not use the LyXAction flag for readonly because Redo sets the
1108 // buffer clean/dirty status by itself.
1109 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1111 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1112 case LFUN_FILE_INSERT_PLAINTEXT: {
1113 docstring const fname = cmd.argument();
1114 if (!FileName::isAbsolute(to_utf8(fname))) {
1115 flag.message(_("Absolute filename expected."));
1118 flag.setEnabled(cur.inTexted());
1121 case LFUN_FILE_INSERT:
1122 case LFUN_BOOKMARK_SAVE:
1123 // FIXME: Actually, these LFUNS should be moved to Text
1124 flag.setEnabled(cur.inTexted());
1127 case LFUN_FONT_STATE:
1128 case LFUN_LABEL_INSERT:
1129 case LFUN_INFO_INSERT:
1130 case LFUN_PARAGRAPH_GOTO:
1131 case LFUN_NOTE_NEXT:
1132 case LFUN_REFERENCE_NEXT:
1133 case LFUN_WORD_FIND:
1134 case LFUN_WORD_FIND_FORWARD:
1135 case LFUN_WORD_FIND_BACKWARD:
1136 case LFUN_WORD_REPLACE:
1139 case LFUN_MARK_TOGGLE:
1140 case LFUN_SCREEN_RECENTER:
1141 case LFUN_SCREEN_SHOW_CURSOR:
1142 case LFUN_BIBTEX_DATABASE_ADD:
1143 case LFUN_BIBTEX_DATABASE_DEL:
1144 case LFUN_STATISTICS:
1145 case LFUN_KEYMAP_OFF:
1146 case LFUN_KEYMAP_PRIMARY:
1147 case LFUN_KEYMAP_SECONDARY:
1148 case LFUN_KEYMAP_TOGGLE:
1149 case LFUN_INSET_SELECT_ALL:
1150 flag.setEnabled(true);
1153 case LFUN_WORD_FINDADV: {
1154 FindAndReplaceOptions opt;
1155 istringstream iss(to_utf8(cmd.argument()));
1157 flag.setEnabled(opt.repl_buf_name.empty()
1158 || !buffer_.isReadonly());
1162 case LFUN_LABEL_GOTO:
1163 flag.setEnabled(!cmd.argument().empty()
1164 || getInsetByCode<InsetRef>(cur, REF_CODE));
1167 case LFUN_CHANGES_MERGE:
1168 case LFUN_CHANGE_NEXT:
1169 case LFUN_CHANGE_PREVIOUS:
1170 case LFUN_ALL_CHANGES_ACCEPT:
1171 case LFUN_ALL_CHANGES_REJECT:
1172 flag.setEnabled(buffer_.areChangesPresent());
1175 case LFUN_SCREEN_UP:
1176 case LFUN_SCREEN_DOWN:
1178 case LFUN_SCREEN_UP_SELECT:
1179 case LFUN_SCREEN_DOWN_SELECT:
1180 case LFUN_INSET_FORALL:
1181 flag.setEnabled(true);
1184 case LFUN_LAYOUT_TABULAR:
1185 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1189 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1192 case LFUN_LAYOUT_PARAGRAPH:
1193 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1196 case LFUN_BRANCH_ADD_INSERT:
1197 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1200 case LFUN_DIALOG_SHOW_NEW_INSET:
1201 // FIXME: this is wrong, but I do not understand the
1203 if (cur.inset().lyxCode() == CAPTION_CODE)
1204 return cur.inset().getStatus(cur, cmd, flag);
1205 // FIXME we should consider passthru paragraphs too.
1206 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1209 case LFUN_CITATION_INSERT: {
1210 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1211 // FIXME: This could turn in a recursive hell.
1212 // Shouldn't we use Buffer::getStatus() instead?
1213 flag.setEnabled(lyx::getStatus(fr).enabled());
1216 case LFUN_INSET_APPLY: {
1217 string const name = cmd.getArg(0);
1218 Inset * inset = editedInset(name);
1220 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1221 if (!inset->getStatus(cur, fr, flag)) {
1222 // Every inset is supposed to handle this
1223 LASSERT(false, break);
1226 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1227 flag = lyx::getStatus(fr);
1240 Inset * BufferView::editedInset(string const & name) const
1242 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1243 return it == d->edited_insets_.end() ? 0 : it->second;
1247 void BufferView::editInset(string const & name, Inset * inset)
1249 d->edited_insets_[name] = inset;
1253 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1255 LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1257 string const argument = to_utf8(cmd.argument());
1258 Cursor & cur = d->cursor_;
1261 // Don't dispatch function that does not apply to internal buffers.
1262 if (buffer_.isInternal()
1263 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1266 // We'll set this back to false if need be.
1267 bool dispatched = true;
1268 buffer_.undo().beginUndoGroup();
1270 FuncCode const act = cmd.action();
1273 case LFUN_BUFFER_PARAMS_APPLY: {
1274 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1275 cur.recordUndoBufferParams();
1276 istringstream ss(to_utf8(cmd.argument()));
1279 int const unknown_tokens = buffer_.readHeader(lex);
1280 if (unknown_tokens != 0) {
1281 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1282 << unknown_tokens << " unknown token"
1283 << (unknown_tokens == 1 ? "" : "s"));
1285 updateDocumentClass(olddc);
1287 // We are most certainly here because of a change in the document
1288 // It is then better to make sure that all dialogs are in sync with
1289 // current document settings.
1290 dr.screenUpdate(Update::Force | Update::FitCursor);
1291 dr.forceBufferUpdate();
1295 case LFUN_LAYOUT_MODULES_CLEAR: {
1296 // FIXME: this modifies the document in cap::switchBetweenClasses
1297 // without calling recordUndo. Fix this before using
1298 // recordUndoBufferParams().
1299 cur.recordUndoFullBuffer();
1300 buffer_.params().clearLayoutModules();
1301 makeDocumentClass();
1302 dr.screenUpdate(Update::Force);
1303 dr.forceBufferUpdate();
1307 case LFUN_LAYOUT_MODULE_ADD: {
1308 BufferParams const & params = buffer_.params();
1309 if (!params.layoutModuleCanBeAdded(argument)) {
1310 LYXERR0("Module `" << argument <<
1311 "' cannot be added due to failed requirements or "
1312 "conflicts with installed modules.");
1315 // FIXME: this modifies the document in cap::switchBetweenClasses
1316 // without calling recordUndo. Fix this before using
1317 // recordUndoBufferParams().
1318 cur.recordUndoFullBuffer();
1319 buffer_.params().addLayoutModule(argument);
1320 makeDocumentClass();
1321 dr.screenUpdate(Update::Force);
1322 dr.forceBufferUpdate();
1326 case LFUN_TEXTCLASS_APPLY: {
1327 // since this shortcircuits, the second call is made only if
1329 bool const success =
1330 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1331 LayoutFileList::get().load(argument, buffer_.filePath());
1333 docstring s = bformat(_("The document class `%1$s' "
1334 "could not be loaded."), from_utf8(argument));
1335 frontend::Alert::error(_("Could not load class"), s);
1339 LayoutFile const * old_layout = buffer_.params().baseClass();
1340 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1342 if (old_layout == new_layout)
1346 // Save the old, possibly modular, layout for use in conversion.
1347 // FIXME: this modifies the document in cap::switchBetweenClasses
1348 // without calling recordUndo. Fix this before using
1349 // recordUndoBufferParams().
1350 cur.recordUndoFullBuffer();
1351 buffer_.params().setBaseClass(argument);
1352 makeDocumentClass();
1353 dr.screenUpdate(Update::Force);
1354 dr.forceBufferUpdate();
1358 case LFUN_TEXTCLASS_LOAD: {
1359 // since this shortcircuits, the second call is made only if
1361 bool const success =
1362 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1363 LayoutFileList::get().load(argument, buffer_.filePath());
1365 docstring s = bformat(_("The document class `%1$s' "
1366 "could not be loaded."), from_utf8(argument));
1367 frontend::Alert::error(_("Could not load class"), s);
1372 case LFUN_LAYOUT_RELOAD: {
1373 LayoutFileIndex bc = buffer_.params().baseClassID();
1374 LayoutFileList::get().reset(bc);
1375 buffer_.params().setBaseClass(bc);
1376 makeDocumentClass();
1377 dr.screenUpdate(Update::Force);
1378 dr.forceBufferUpdate();
1383 dr.setMessage(_("Undo"));
1384 cur.clearSelection();
1385 // We need to find out if the bibliography information
1386 // has changed. See bug #11055.
1387 // So these should not be references...
1388 LayoutModuleList const engines = buffer().params().citeEngine();
1389 CiteEngineType const enginetype = buffer().params().citeEngineType();
1390 if (!cur.textUndo())
1391 dr.setMessage(_("No further undo information"));
1393 dr.screenUpdate(Update::Force | Update::FitCursor);
1394 dr.forceBufferUpdate();
1395 if (buffer().params().citeEngine() != engines ||
1396 buffer().params().citeEngineType() != enginetype)
1397 buffer().invalidateCiteLabels();
1403 dr.setMessage(_("Redo"));
1404 cur.clearSelection();
1405 // We need to find out if the bibliography information
1406 // has changed. See bug #11055.
1407 // So these should not be references...
1408 LayoutModuleList const engines = buffer().params().citeEngine();
1409 CiteEngineType const enginetype = buffer().params().citeEngineType();
1410 if (!cur.textRedo())
1411 dr.setMessage(_("No further redo information"));
1413 dr.screenUpdate(Update::Force | Update::FitCursor);
1414 dr.forceBufferUpdate();
1415 if (buffer().params().citeEngine() != engines ||
1416 buffer().params().citeEngineType() != enginetype)
1417 buffer().invalidateCiteLabels();
1422 case LFUN_FONT_STATE:
1423 dr.setMessage(cur.currentState(false));
1426 case LFUN_BOOKMARK_SAVE:
1427 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1430 case LFUN_LABEL_GOTO: {
1431 docstring label = cmd.argument();
1432 if (label.empty()) {
1434 getInsetByCode<InsetRef>(cur, REF_CODE);
1436 label = inset->getParam("reference");
1437 // persistent=false: use temp_bookmark
1441 if (!label.empty()) {
1443 // at the moment, this is redundant, since gotoLabel will
1444 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1446 dr.screenUpdate(Update::Force | Update::FitCursor);
1451 case LFUN_PARAGRAPH_GOTO: {
1452 int const id = convert<int>(cmd.getArg(0));
1453 pos_type const pos = convert<int>(cmd.getArg(1));
1456 string const str_id_end = cmd.getArg(2);
1457 string const str_pos_end = cmd.getArg(3);
1459 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1460 b = theBufferList().next(b)) {
1463 cur.setCursor(b->getParFromID(id));
1465 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1469 LYXERR(Debug::INFO, "Paragraph " << cur.paragraph().id()
1470 << " found in buffer `"
1471 << b->absFileName() << "'.");
1473 if (b == &buffer_) {
1475 if (str_id_end.empty() || str_pos_end.empty()) {
1478 mouseSetCursor(cur);
1481 int const id_end = convert<int>(str_id_end);
1482 pos_type const pos_end = convert<int>(str_pos_end);
1483 success = setCursorFromEntries({id, pos},
1487 dr.screenUpdate(Update::Force | Update::FitCursor);
1489 // Switch to other buffer view and resend cmd
1490 lyx::dispatch(FuncRequest(
1491 LFUN_BUFFER_SWITCH, b->absFileName()));
1499 case LFUN_NOTE_NEXT:
1500 gotoInset(this, NOTE_CODE, false);
1503 case LFUN_REFERENCE_NEXT: {
1504 vector<InsetCode> tmp;
1505 tmp.push_back(LABEL_CODE);
1506 tmp.push_back(REF_CODE);
1507 gotoInset(this, tmp, true);
1511 case LFUN_CHANGE_NEXT:
1512 findNextChange(this);
1513 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1514 dr.screenUpdate(Update::Force | Update::FitCursor);
1517 case LFUN_CHANGE_PREVIOUS:
1518 findPreviousChange(this);
1519 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1520 dr.screenUpdate(Update::Force | Update::FitCursor);
1523 case LFUN_CHANGES_MERGE:
1524 if (findNextChange(this) || findPreviousChange(this)) {
1525 dr.screenUpdate(Update::Force | Update::FitCursor);
1526 dr.forceBufferUpdate();
1527 showDialog("changes");
1531 case LFUN_ALL_CHANGES_ACCEPT:
1532 // select complete document
1534 cur.selHandle(true);
1535 buffer_.text().cursorBottom(cur);
1536 // accept everything in a single step to support atomic undo
1537 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1539 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1540 dr.screenUpdate(Update::Force | Update::FitCursor);
1541 dr.forceBufferUpdate();
1544 case LFUN_ALL_CHANGES_REJECT:
1545 // select complete document
1547 cur.selHandle(true);
1548 buffer_.text().cursorBottom(cur);
1549 // reject everything in a single step to support atomic undo
1550 // Note: reject does not work recursively; the user may have to repeat the operation
1551 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1553 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1554 dr.screenUpdate(Update::Force | Update::FitCursor);
1555 dr.forceBufferUpdate();
1558 case LFUN_WORD_FIND_FORWARD:
1559 case LFUN_WORD_FIND_BACKWARD: {
1561 // Would it maybe be better if this variable were view specific anyway?
1562 static docstring last_search;
1563 docstring searched_string;
1565 if (!cmd.argument().empty()) {
1566 last_search = cmd.argument();
1567 searched_string = cmd.argument();
1569 searched_string = last_search;
1572 if (searched_string.empty())
1575 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1576 docstring const data =
1577 find2string(searched_string, true, false, fw);
1578 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1580 dr.screenUpdate(Update::Force | Update::FitCursor);
1584 case LFUN_WORD_FIND: {
1585 FuncRequest req = cmd;
1586 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1587 req = d->search_request_cache_;
1588 if (req.argument().empty()) {
1589 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1592 if (lyxfind(this, req))
1593 dr.screenUpdate(Update::Force | Update::FitCursor);
1595 d->search_request_cache_ = req;
1599 case LFUN_WORD_REPLACE: {
1600 bool has_deleted = false;
1601 if (cur.selection()) {
1602 DocIterator beg = cur.selectionBegin();
1603 DocIterator end = cur.selectionEnd();
1604 if (beg.pit() == end.pit()) {
1605 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1606 if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1613 if (lyxreplace(this, cmd, has_deleted)) {
1614 dr.forceBufferUpdate();
1615 dr.screenUpdate(Update::Force | Update::FitCursor);
1620 case LFUN_WORD_FINDADV: {
1621 FindAndReplaceOptions opt;
1622 istringstream iss(to_utf8(cmd.argument()));
1624 if (findAdv(this, opt)) {
1625 dr.screenUpdate(Update::Force | Update::FitCursor);
1636 cur.clearSelection();
1637 dr.setMessage(from_utf8(N_("Mark off")));
1641 cur.clearSelection();
1643 dr.setMessage(from_utf8(N_("Mark on")));
1646 case LFUN_MARK_TOGGLE:
1647 cur.selection(false);
1650 dr.setMessage(from_utf8(N_("Mark removed")));
1653 dr.setMessage(from_utf8(N_("Mark set")));
1658 case LFUN_SCREEN_SHOW_CURSOR:
1662 case LFUN_SCREEN_RECENTER:
1666 case LFUN_BIBTEX_DATABASE_ADD: {
1667 Cursor tmpcur = cur;
1668 findInset(tmpcur, BIBTEX_CODE, false);
1669 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1672 if (inset->addDatabase(cmd.argument()))
1673 dr.forceBufferUpdate();
1678 case LFUN_BIBTEX_DATABASE_DEL: {
1679 Cursor tmpcur = cur;
1680 findInset(tmpcur, BIBTEX_CODE, false);
1681 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1684 if (inset->delDatabase(cmd.argument()))
1685 dr.forceBufferUpdate();
1690 case LFUN_STATISTICS: {
1691 DocIterator from, to;
1692 if (cur.selection()) {
1693 from = cur.selectionBegin();
1694 to = cur.selectionEnd();
1696 from = doc_iterator_begin(&buffer_);
1697 to = doc_iterator_end(&buffer_);
1699 buffer_.updateStatistics(from, to);
1700 int const words = buffer_.wordCount();
1701 int const chars = buffer_.charCount(false);
1702 int const chars_blanks = buffer_.charCount(true);
1704 if (cur.selection())
1705 message = _("Statistics for the selection:");
1707 message = _("Statistics for the document:");
1710 message += bformat(_("%1$d words"), words);
1712 message += _("One word");
1714 if (chars_blanks != 1)
1715 message += bformat(_("%1$d characters (including blanks)"),
1718 message += _("One character (including blanks)");
1721 message += bformat(_("%1$d characters (excluding blanks)"),
1724 message += _("One character (excluding blanks)");
1726 Alert::information(_("Statistics"), message);
1730 case LFUN_SCREEN_UP:
1731 case LFUN_SCREEN_DOWN: {
1732 Point p = getPos(cur);
1733 // This code has been commented out to enable to scroll down a
1734 // document, even if there are large insets in it (see bug #5465).
1735 /*if (p.y_ < 0 || p.y_ > height_) {
1736 // The cursor is off-screen so recenter before proceeding.
1740 int const scrolled = scroll(act == LFUN_SCREEN_UP
1741 ? -height_ : height_);
1742 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1744 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1745 p = Point(width_, height_);
1746 bool const in_texted = cur.inTexted();
1747 cur.setCursor(doc_iterator_begin(cur.buffer()));
1748 cur.selHandle(false);
1749 // Force an immediate computation of metrics because we need it below
1750 processUpdateFlags(Update::Force);
1752 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1753 true, act == LFUN_SCREEN_UP);
1754 //FIXME: what to do with cur.x_target()?
1755 bool update = in_texted && cur.bv().checkDepm(cur, old);
1758 if (update || cur.mark())
1759 dr.screenUpdate(Update::Force | Update::FitCursor);
1761 dr.forceBufferUpdate();
1766 string const scroll_type = cmd.getArg(0);
1767 int scroll_step = 0;
1768 if (scroll_type == "line")
1769 scroll_step = d->scrollbarParameters_.single_step;
1770 else if (scroll_type == "page")
1771 scroll_step = d->scrollbarParameters_.page_step;
1774 string const scroll_quantity = cmd.getArg(1);
1775 if (scroll_quantity == "up")
1776 scrollUp(scroll_step);
1777 else if (scroll_quantity == "down")
1778 scrollDown(scroll_step);
1780 int const scroll_value = convert<int>(scroll_quantity);
1782 scroll(scroll_step * scroll_value);
1784 dr.screenUpdate(Update::ForceDraw);
1785 dr.forceBufferUpdate();
1789 case LFUN_SCREEN_UP_SELECT: {
1790 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
1791 cur.selHandle(true);
1792 if (isTopScreen()) {
1793 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1797 int y = getPos(cur).y_;
1798 int const ymin = y - height_ + defaultRowHeight();
1799 while (y > ymin && cur.up())
1803 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1807 case LFUN_SCREEN_DOWN_SELECT: {
1808 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
1809 cur.selHandle(true);
1810 if (isBottomScreen()) {
1811 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1815 int y = getPos(cur).y_;
1816 int const ymax = y + height_ - defaultRowHeight();
1817 while (y < ymax && cur.down())
1821 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1826 case LFUN_INSET_SELECT_ALL: {
1827 // true if all cells are selected
1828 bool const all_selected = cur.depth() > 1
1829 && cur.selBegin().at_begin()
1830 && cur.selEnd().at_end();
1831 // true if some cells are selected
1832 bool const cells_selected = cur.depth() > 1
1833 && cur.selBegin().at_cell_begin()
1834 && cur.selEnd().at_cell_end();
1835 if (all_selected || (cells_selected && !cur.inset().isTable())) {
1836 // All the contents of the inset if selected, or only at
1837 // least one cell but inset is not a table.
1838 // Select the inset from outside.
1841 cur.selection(true);
1843 } else if (cells_selected) {
1844 // At least one complete cell is selected and inset is a table.
1849 cur.selection(true);
1850 cur.idx() = cur.lastidx();
1851 cur.pos() = cur.lastpos();
1853 // select current cell
1857 cur.selection(true);
1858 cur.pit() = cur.lastpit();
1859 cur.pos() = cur.lastpos();
1861 cur.setCurrentFont();
1862 dr.screenUpdate(Update::Force);
1867 // This would be in Buffer class if only Cursor did not
1868 // require a bufferview
1869 case LFUN_INSET_FORALL: {
1870 docstring const name = from_utf8(cmd.getArg(0));
1871 string const commandstr = cmd.getLongArg(1);
1872 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1874 // an arbitrary number to limit number of iterations
1875 const int max_iter = 100000;
1877 Cursor & cur = d->cursor_;
1878 Cursor const savecur = cur;
1880 if (!cur.nextInset())
1882 cur.beginUndoGroup();
1883 while(cur && iterations < max_iter) {
1884 Inset * const ins = cur.nextInset();
1887 docstring insname = ins->layoutName();
1888 while (!insname.empty()) {
1889 if (insname == name || name == from_utf8("*")) {
1891 lyx::dispatch(fr, dr);
1895 size_t const i = insname.rfind(':');
1896 if (i == string::npos)
1898 insname = insname.substr(0, i);
1900 // if we did not delete the inset, skip it
1901 if (!cur.nextInset() || cur.nextInset() == ins)
1906 /** This is a dummy undo record only to remember the cursor
1907 * that has just been set; this will be used on a redo action
1908 * (see ticket #10097)
1910 * FIXME: a better fix would be to have a way to set the
1911 * cursor value directly, but I am not sure it is worth it.
1915 dr.screenUpdate(Update::Force);
1916 dr.forceBufferUpdate();
1918 if (iterations >= max_iter) {
1920 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1922 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1927 case LFUN_BRANCH_ADD_INSERT: {
1928 docstring branch_name = from_utf8(cmd.getArg(0));
1929 if (branch_name.empty())
1930 if (!Alert::askForText(branch_name, _("Branch name")) ||
1931 branch_name.empty())
1934 DispatchResult drtmp;
1935 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1936 if (drtmp.error()) {
1937 Alert::warning(_("Branch already exists"), drtmp.message());
1940 docstring const sep = buffer_.params().branchlist().separator();
1941 for (docstring const & branch : getVectorFromString(branch_name, sep))
1942 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch));
1946 case LFUN_KEYMAP_OFF:
1947 getIntl().keyMapOn(false);
1950 case LFUN_KEYMAP_PRIMARY:
1951 getIntl().keyMapPrim();
1954 case LFUN_KEYMAP_SECONDARY:
1955 getIntl().keyMapSec();
1958 case LFUN_KEYMAP_TOGGLE:
1959 getIntl().toggleKeyMap();
1962 case LFUN_DIALOG_SHOW_NEW_INSET: {
1963 string const name = cmd.getArg(0);
1964 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1965 if (decodeInsetParam(name, data, buffer_))
1966 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1968 lyxerr << "Inset type '" << name <<
1969 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1973 case LFUN_CITATION_INSERT: {
1974 if (argument.empty()) {
1975 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1978 // we can have one optional argument, delimited by '|'
1979 // citation-insert <key>|<text_before>
1980 // this should be enhanced to also support text_after
1981 // and citation style
1982 string arg = argument;
1984 if (contains(argument, "|")) {
1985 arg = token(argument, '|', 0);
1986 opt1 = token(argument, '|', 1);
1989 // if our cursor is directly in front of or behind a citation inset,
1990 // we will instead add the new key to it.
1991 Inset * inset = cur.nextInset();
1992 if (!inset || inset->lyxCode() != CITE_CODE)
1993 inset = cur.prevInset();
1994 if (inset && inset->lyxCode() == CITE_CODE) {
1995 InsetCitation * icite = static_cast<InsetCitation *>(inset);
1996 if (icite->addKey(arg)) {
1997 dr.forceBufferUpdate();
1998 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
2000 LYXERR0("Discarding optional argument to citation-insert.");
2005 InsetCommandParams icp(CITE_CODE);
2006 icp["key"] = from_utf8(arg);
2008 icp["before"] = from_utf8(opt1);
2009 string icstr = InsetCommand::params2string(icp);
2010 FuncRequest fr(LFUN_INSET_INSERT, icstr);
2015 case LFUN_INSET_APPLY: {
2016 string const name = cmd.getArg(0);
2017 Inset * inset = editedInset(name);
2019 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2023 // put cursor in front of inset.
2024 if (!setCursorFromInset(inset)) {
2025 LASSERT(false, break);
2028 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2029 inset->dispatch(cur, fr);
2030 dr.screenUpdate(cur.result().screenUpdate());
2031 if (cur.result().needBufferUpdate())
2032 dr.forceBufferUpdate();
2037 // The change of language of buffer belongs to the Buffer class.
2038 // We have to do it here because we need a cursor for Undo.
2039 // When Undo::recordUndoBufferParams() is implemented someday
2040 // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
2041 case LFUN_BUFFER_LANGUAGE: {
2042 Language const * oldL = buffer_.params().language;
2043 Language const * newL = languages.getLanguage(argument);
2044 if (!newL || oldL == newL)
2046 if (oldL->rightToLeft() == newL->rightToLeft()) {
2047 cur.recordUndoFullBuffer();
2048 buffer_.changeLanguage(oldL, newL);
2049 cur.setCurrentFont();
2050 dr.forceBufferUpdate();
2055 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2056 case LFUN_FILE_INSERT_PLAINTEXT: {
2057 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
2058 string const fname = to_utf8(cmd.argument());
2059 if (!FileName::isAbsolute(fname))
2060 dr.setMessage(_("Absolute filename expected."));
2062 insertPlaintextFile(FileName(fname), as_paragraph);
2067 // OK, so try the Buffer itself...
2068 buffer_.dispatch(cmd, dr);
2069 dispatched = dr.dispatched();
2073 buffer_.undo().endUndoGroup();
2074 dr.dispatched(dispatched);
2076 // NOTE: The code below is copied from Cursor::dispatch. If you
2077 // need to modify this, please update the other one too.
2079 // notify insets we just entered/left
2080 if (cursor() != old) {
2081 old.beginUndoGroup();
2083 bool badcursor = notifyCursorLeavesOrEnters(old, cursor());
2085 cursor().fixIfBroken();
2086 resetInlineCompletionPos();
2093 docstring const BufferView::requestSelection()
2095 Cursor & cur = d->cursor_;
2097 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2098 if (!cur.selection()) {
2099 d->xsel_cache_.set = false;
2103 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2104 if (!d->xsel_cache_.set ||
2105 cur.top() != d->xsel_cache_.cursor ||
2106 cur.realAnchor().top() != d->xsel_cache_.anchor)
2108 d->xsel_cache_.cursor = cur.top();
2109 d->xsel_cache_.anchor = cur.realAnchor().top();
2110 d->xsel_cache_.set = cur.selection();
2111 return cur.selectionAsString(false);
2117 void BufferView::clearSelection()
2119 d->cursor_.clearSelection();
2120 // Clear the selection buffer. Otherwise a subsequent
2121 // middle-mouse-button paste would use the selection buffer,
2122 // not the more current external selection.
2123 cap::clearSelection();
2124 d->xsel_cache_.set = false;
2125 // The buffer did not really change, but this causes the
2126 // redraw we need because we cleared the selection above.
2127 buffer_.changed(false);
2131 void BufferView::resize(int width, int height)
2133 // Update from work area
2137 // Clear the paragraph height cache.
2138 d->par_height_.clear();
2139 // Redo the metrics.
2144 Inset const * BufferView::getCoveringInset(Text const & text,
2147 TextMetrics & tm = d->text_metrics_[&text];
2148 Inset * inset = tm.checkInsetHit(x, y);
2152 if (!inset->descendable(*this))
2153 // No need to go further down if the inset is not
2157 size_t cell_number = inset->nargs();
2158 // Check all the inner cell.
2159 for (size_t i = 0; i != cell_number; ++i) {
2160 Text const * inner_text = inset->getText(i);
2163 Inset const * inset_deeper =
2164 getCoveringInset(*inner_text, x, y);
2166 return inset_deeper;
2174 void BufferView::updateHoveredInset() const
2176 // Get inset under mouse, if there is one.
2177 int const x = d->mouse_position_cache_.x_;
2178 int const y = d->mouse_position_cache_.y_;
2179 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2181 d->clickable_inset_ = covering_inset && covering_inset->clickable(*this, x, y);
2183 if (covering_inset == d->last_inset_)
2184 // Same inset, no need to do anything...
2187 bool need_redraw = false;
2188 if (d->last_inset_) {
2189 // Remove the hint on the last hovered inset (if any).
2190 need_redraw |= d->last_inset_->setMouseHover(this, false);
2194 if (covering_inset && covering_inset->setMouseHover(this, true)) {
2196 // Only the insets that accept the hover state, do
2197 // clear the last_inset_, so only set the last_inset_
2198 // member if the hovered setting is accepted.
2199 d->last_inset_ = covering_inset;
2203 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2204 << d->mouse_position_cache_.x_ << ", "
2205 << d->mouse_position_cache_.y_ << ")");
2207 d->update_strategy_ = DecorationUpdate;
2209 // This event (moving without mouse click) is not passed further.
2210 // This should be changed if it is further utilized.
2211 buffer_.changed(false);
2216 void BufferView::clearLastInset(Inset * inset) const
2218 if (d->last_inset_ != inset) {
2219 LYXERR0("Wrong last_inset!");
2226 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2228 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2230 // This is only called for mouse related events including
2231 // LFUN_FILE_OPEN generated by drag-and-drop.
2232 FuncRequest cmd = cmd0;
2234 Cursor old = cursor();
2236 cur.push(buffer_.inset());
2237 cur.selection(d->cursor_.selection());
2239 // Either the inset under the cursor or the
2240 // surrounding Text will handle this event.
2242 // make sure we stay within the screen...
2243 cmd.set_y(min(max(cmd.y(), -1), height_));
2245 d->mouse_position_cache_.x_ = cmd.x();
2246 d->mouse_position_cache_.y_ = cmd.y();
2248 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2249 updateHoveredInset();
2253 // Build temporary cursor.
2254 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2256 // If inset is not editable, cur.pos() might point behind the
2257 // inset (depending on cmd.x(), cmd.y()). This is needed for
2258 // editing to fix bug 9628, but e.g. the context menu needs a
2259 // cursor in front of the inset.
2260 if ((inset->hasSettings() || !inset->contextMenuName().empty()
2261 || inset->lyxCode() == SEPARATOR_CODE) &&
2262 cur.nextInset() != inset && cur.prevInset() == inset)
2264 } else if (cur.inTexted() && cur.pos()
2265 && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
2266 // Always place cursor in front of a separator inset.
2270 // Put anchor at the same position.
2273 cur.beginUndoGroup();
2275 // Try to dispatch to an non-editable inset near this position
2276 // via the temp cursor. If the inset wishes to change the real
2277 // cursor it has to do so explicitly by using
2278 // cur.bv().cursor() = cur; (or similar)
2280 inset->dispatch(cur, cmd);
2282 // Now dispatch to the temporary cursor. If the real cursor should
2283 // be modified, the inset's dispatch has to do so explicitly.
2284 if (!inset || !cur.result().dispatched())
2287 // Notify left insets
2289 bool badcursor = old.fixIfBroken() | cur.fixIfBroken();
2290 badcursor |= notifyCursorLeavesOrEnters(old, cur);
2292 cursor().fixIfBroken();
2297 // Do we have a selection?
2298 theSelection().haveSelection(cursor().selection());
2300 if (cur.needBufferUpdate()) {
2301 cur.clearBufferUpdate();
2302 buffer().updateBuffer();
2305 // If the command has been dispatched,
2306 if (cur.result().dispatched() || cur.result().screenUpdate())
2307 processUpdateFlags(cur.result().screenUpdate());
2311 int BufferView::minVisiblePart()
2313 return 2 * defaultRowHeight();
2317 int BufferView::scroll(int y)
2320 return scrollDown(y);
2322 return scrollUp(-y);
2327 int BufferView::scrollDown(int offset)
2329 Text * text = &buffer_.text();
2330 TextMetrics & tm = d->text_metrics_[text];
2331 int const ymax = height_ + offset;
2333 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2334 int bottom_pos = last.second->position() + last.second->descent();
2335 if (lyxrc.scroll_below_document)
2336 bottom_pos += height_ - minVisiblePart();
2337 if (last.first + 1 == int(text->paragraphs().size())) {
2338 if (bottom_pos <= height_)
2340 offset = min(offset, bottom_pos - height_);
2343 if (bottom_pos > ymax)
2345 tm.newParMetricsDown();
2347 d->anchor_ypos_ -= offset;
2352 int BufferView::scrollUp(int offset)
2354 Text * text = &buffer_.text();
2355 TextMetrics & tm = d->text_metrics_[text];
2356 int ymin = - offset;
2358 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2359 int top_pos = first.second->position() - first.second->ascent();
2360 if (first.first == 0) {
2363 offset = min(offset, - top_pos);
2368 tm.newParMetricsUp();
2370 d->anchor_ypos_ += offset;
2375 bool BufferView::setCursorFromRow(int row)
2377 TexRow::TextEntry start, end;
2378 tie(start,end) = buffer_.texrow().getEntriesFromRow(row);
2379 LYXERR(Debug::LATEX,
2380 "setCursorFromRow: for row " << row << ", TexRow has found "
2381 "start (id=" << start.id << ",pos=" << start.pos << "), "
2382 "end (id=" << end.id << ",pos=" << end.pos << ")");
2383 return setCursorFromEntries(start, end);
2387 bool BufferView::setCursorFromEntries(TexRow::TextEntry start,
2388 TexRow::TextEntry end)
2390 DocIterator dit_start, dit_end;
2391 tie(dit_start,dit_end) =
2392 TexRow::getDocIteratorsFromEntries(start, end, buffer_);
2395 // Setting selection start
2396 d->cursor_.clearSelection();
2397 setCursor(dit_start);
2398 // Setting selection end
2400 d->cursor_.resetAnchor();
2401 setCursorSelectionTo(dit_end);
2407 bool BufferView::setCursorFromInset(Inset const * inset)
2409 // are we already there?
2410 if (cursor().nextInset() == inset)
2413 // Inset is not at cursor position. Find it in the document.
2416 while (cur && cur.nextInset() != inset)
2427 void BufferView::gotoLabel(docstring const & label)
2429 for (Buffer const * buf : buffer().allRelatives()) {
2431 for (TocItem const & item : *buf->tocBackend().toc("label")) {
2432 if (label == item.str()) {
2433 lyx::dispatch(item.action());
2441 TextMetrics const & BufferView::textMetrics(Text const * t) const
2443 return const_cast<BufferView *>(this)->textMetrics(t);
2447 TextMetrics & BufferView::textMetrics(Text const * t)
2450 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2451 if (tmc_it == d->text_metrics_.end()) {
2452 tmc_it = d->text_metrics_.insert(
2453 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2455 return tmc_it->second;
2459 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2462 return textMetrics(t).parMetrics(pit);
2466 int BufferView::workHeight() const
2472 void BufferView::setCursor(DocIterator const & dit)
2475 size_t const n = dit.depth();
2476 for (size_t i = 0; i < n; ++i)
2477 dit[i].inset().edit(d->cursor_, true);
2479 d->cursor_.setCursor(dit);
2480 d->cursor_.selection(false);
2481 d->cursor_.setCurrentFont();
2483 // It seems on general grounds as if this is probably needed, but
2484 // it is not yet clear.
2485 // See bug #7394 and r38388.
2486 // d->cursor.resetAnchor();
2490 void BufferView::setCursorSelectionTo(DocIterator const & dit)
2492 size_t const n = dit.depth();
2493 for (size_t i = 0; i < n; ++i)
2494 dit[i].inset().edit(d->cursor_, true);
2496 d->cursor_.selection(true);
2497 d->cursor_.setCursorSelectionTo(dit);
2498 d->cursor_.setCurrentFont();
2502 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2504 // Would be wrong to delete anything if we have a selection.
2505 if (cur.selection())
2508 bool need_anchor_change = false;
2509 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2510 need_anchor_change);
2512 if (need_anchor_change)
2520 // we would rather not do this here, but it needs to be done before
2521 // the changed() signal is sent.
2522 buffer_.updateBuffer();
2524 buffer_.changed(true);
2529 bool BufferView::mouseSetCursor(Cursor & cur, bool const select)
2531 LASSERT(&cur.bv() == this, return false);
2534 // this event will clear selection so we save selection for
2535 // persistent selection
2536 cap::saveSelection(cursor());
2538 d->cursor_.macroModeClose();
2539 // If a macro has been finalized, the cursor might have been broken
2542 // Has the cursor just left the inset?
2543 bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2545 d->cursor_.fixIfBroken();
2547 // do the dEPM magic if needed
2548 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2549 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2550 // the leftinset bool would not be necessary (badcursor instead).
2551 bool update = leftinset;
2554 d->cursor_.setSelection();
2555 d->cursor_.setCursorSelectionTo(cur);
2557 if (d->cursor_.inTexted())
2558 update |= checkDepm(cur, d->cursor_);
2559 d->cursor_.resetAnchor();
2560 d->cursor_.setCursor(cur);
2561 d->cursor_.clearSelection();
2563 d->cursor_.boundary(cur.boundary());
2564 d->cursor_.finishUndo();
2565 d->cursor_.setCurrentFont();
2567 cur.forceBufferUpdate();
2572 void BufferView::putSelectionAt(DocIterator const & cur,
2573 int length, bool backwards)
2575 d->cursor_.clearSelection();
2581 d->cursor_.pos() += length;
2582 d->cursor_.setSelection(d->cursor_, -length);
2584 d->cursor_.setSelection(d->cursor_, length);
2589 bool BufferView::selectIfEmpty(DocIterator & cur)
2591 if ((cur.inTexted() && !cur.paragraph().empty())
2592 || (cur.inMathed() && !cur.cell().empty()))
2595 pit_type const beg_pit = cur.pit();
2597 // The paragraph associated to this item isn't
2598 // the first one, so it can be selected
2601 // We have to resort to select the space between the
2602 // end of this item and the begin of the next one
2606 // If it is the only item in the document,
2607 // nothing can be selected
2610 pit_type const end_pit = cur.pit();
2611 pos_type const end_pos = cur.pos();
2612 d->cursor_.clearSelection();
2614 d->cursor_.setCursor(cur);
2615 d->cursor_.pit() = beg_pit;
2616 d->cursor_.pos() = 0;
2617 d->cursor_.selection(false);
2618 d->cursor_.resetAnchor();
2619 d->cursor_.pit() = end_pit;
2620 d->cursor_.pos() = end_pos;
2621 d->cursor_.setSelection();
2626 Cursor & BufferView::cursor()
2632 Cursor const & BufferView::cursor() const
2638 bool BufferView::singleParUpdate()
2640 Text & buftext = buffer_.text();
2641 pit_type const bottom_pit = d->cursor_.bottom().pit();
2642 TextMetrics & tm = textMetrics(&buftext);
2643 int old_height = tm.parMetrics(bottom_pit).height();
2645 // make sure inline completion pointer is ok
2646 if (d->inlineCompletionPos_.fixIfBroken())
2647 d->inlineCompletionPos_ = DocIterator();
2649 // In Single Paragraph mode, rebreak only
2650 // the (main text, not inset!) paragraph containing the cursor.
2651 // (if this paragraph contains insets etc., rebreaking will
2652 // recursively descend)
2653 tm.redoParagraph(bottom_pit);
2654 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2655 if (pm.height() != old_height)
2656 // Paragraph height has changed so we cannot proceed to
2657 // the singlePar optimisation.
2660 tm.updatePosCache(bottom_pit);
2662 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2663 << " y2: " << pm.position() + pm.descent()
2664 << " pit: " << bottom_pit
2665 << " singlepar: 1");
2670 void BufferView::updateMetrics()
2672 updateMetrics(d->update_flags_);
2673 d->update_strategy_ = FullScreenUpdate;
2677 void BufferView::updateMetrics(Update::flags & update_flags)
2679 if (height_ == 0 || width_ == 0)
2682 Text & buftext = buffer_.text();
2683 pit_type const npit = int(buftext.paragraphs().size());
2685 // Clear out the position cache in case of full screen redraw,
2686 d->coord_cache_.clear();
2688 // Clear out paragraph metrics to avoid having invalid metrics
2689 // in the cache from paragraphs not relayouted below
2690 // The complete text metrics will be redone.
2691 d->text_metrics_.clear();
2693 TextMetrics & tm = textMetrics(&buftext);
2695 // make sure inline completion pointer is ok
2696 if (d->inlineCompletionPos_.fixIfBroken())
2697 d->inlineCompletionPos_ = DocIterator();
2699 if (d->anchor_pit_ >= npit)
2700 // The anchor pit must have been deleted...
2701 d->anchor_pit_ = npit - 1;
2703 // Rebreak anchor paragraph.
2704 tm.redoParagraph(d->anchor_pit_);
2705 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2708 if (d->anchor_pit_ == 0) {
2709 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2711 // Complete buffer visible? Then it's easy.
2712 if (scrollRange == 0)
2713 d->anchor_ypos_ = anchor_pm.ascent();
2715 // avoid empty space above the first row
2716 d->anchor_ypos_ = min(d->anchor_ypos_, anchor_pm.ascent());
2719 anchor_pm.setPosition(d->anchor_ypos_);
2720 tm.updatePosCache(d->anchor_pit_);
2722 LYXERR(Debug::PAINTING, "metrics: "
2723 << " anchor pit = " << d->anchor_pit_
2724 << " anchor ypos = " << d->anchor_ypos_);
2726 // Redo paragraphs above anchor if necessary.
2727 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2728 // We are now just above the anchor paragraph.
2729 pit_type pit1 = d->anchor_pit_ - 1;
2730 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2731 tm.redoParagraph(pit1);
2732 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2734 // Save the paragraph position in the cache.
2736 tm.updatePosCache(pit1);
2740 // Redo paragraphs below the anchor if necessary.
2741 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2742 // We are now just below the anchor paragraph.
2743 pit_type pit2 = d->anchor_pit_ + 1;
2744 for (; pit2 < npit && y2 <= height_; ++pit2) {
2745 tm.redoParagraph(pit2);
2746 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2748 // Save the paragraph position in the cache.
2750 tm.updatePosCache(pit2);
2754 LYXERR(Debug::PAINTING, "Metrics: "
2755 << " anchor pit = " << d->anchor_pit_
2756 << " anchor ypos = " << d->anchor_ypos_
2759 << " pit1 = " << pit1
2760 << " pit2 = " << pit2);
2762 // metrics is done, full drawing is necessary now
2763 update_flags = (update_flags & ~Update::Force) | Update::ForceDraw;
2765 // Now update the positions of insets in the cache.
2768 if (lyxerr.debugging(Debug::WORKAREA)) {
2769 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2770 d->coord_cache_.dump();
2775 void BufferView::updatePosCache()
2777 // this is the "nodraw" drawing stage: only set the positions of the
2778 // insets in metrics cache.
2779 frontend::NullPainter np;
2784 void BufferView::insertLyXFile(FileName const & fname)
2786 LASSERT(d->cursor_.inTexted(), return);
2788 // Get absolute path of file and add ".lyx"
2789 // to the filename if necessary
2790 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2792 docstring const disp_fn = makeDisplayPath(filename.absFileName());
2793 // emit message signal.
2794 message(bformat(_("Inserting document %1$s..."), disp_fn));
2797 Buffer buf(filename.absFileName(), false);
2798 if (buf.loadLyXFile() == Buffer::ReadSuccess) {
2799 ErrorList & el = buffer_.errorList("Parse");
2800 // Copy the inserted document error list into the current buffer one.
2801 el = buf.errorList("Parse");
2802 buffer_.undo().recordUndo(d->cursor_);
2803 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2804 buf.params().documentClassPtr(), el);
2805 res = _("Document %1$s inserted.");
2807 res = _("Could not insert document %1$s");
2810 buffer_.changed(true);
2811 // emit message signal.
2812 message(bformat(res, disp_fn));
2816 Point BufferView::coordOffset(DocIterator const & dit) const
2822 // Addup contribution of nested insets, from inside to outside,
2823 // keeping the outer paragraph for a special handling below
2824 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2825 CursorSlice const & sl = dit[i];
2829 // get relative position inside sl.inset()
2830 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2832 // Make relative position inside of the edited inset relative to sl.inset()
2836 // In case of an RTL inset, the edited inset will be positioned to the left
2839 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2840 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2845 // remember width for the case that sl.inset() is positioned in an RTL inset
2846 lastw = sl.inset().dimension(*this).wid;
2848 //lyxerr << "Cursor::getPos, i: "
2849 // << i << " x: " << xx << " y: " << y << endl;
2852 // Add contribution of initial rows of outermost paragraph
2853 CursorSlice const & sl = dit[0];
2854 TextMetrics const & tm = textMetrics(sl.text());
2855 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2857 LBUFERR(!pm.rows().empty());
2858 y -= pm.rows()[0].ascent();
2860 // FIXME: document this mess
2862 if (sl.pos() > 0 && dit.depth() == 1) {
2864 if (pos && dit.boundary())
2866 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2867 rend = pm.pos2row(pos);
2869 rend = pm.pos2row(sl.pos());
2871 size_t rend = pm.pos2row(sl.pos());
2873 for (size_t rit = 0; rit != rend; ++rit)
2874 y += pm.rows()[rit].height();
2875 y += pm.rows()[rend].ascent();
2877 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2879 // Make relative position from the nested inset now bufferview absolute.
2880 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2883 // In the RTL case place the nested inset at the left of the cursor in
2884 // the outer paragraph
2885 bool boundary_1 = dit.boundary() && 1 == dit.depth();
2886 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2894 Point BufferView::getPos(DocIterator const & dit) const
2896 if (!paragraphVisible(dit))
2897 return Point(-1, -1);
2899 CursorSlice const & bot = dit.bottom();
2900 TextMetrics const & tm = textMetrics(bot.text());
2902 // offset from outer paragraph
2903 Point p = coordOffset(dit);
2904 p.y_ += tm.parMetrics(bot.pit()).position();
2909 bool BufferView::paragraphVisible(DocIterator const & dit) const
2911 CursorSlice const & bot = dit.bottom();
2912 TextMetrics const & tm = textMetrics(bot.text());
2914 return tm.contains(bot.pit());
2918 void BufferView::caretPosAndHeight(Point & p, int & h) const
2920 Cursor const & cur = cursor();
2921 Font const font = cur.real_current_font;
2922 frontend::FontMetrics const & fm = theFontMetrics(font);
2923 int const asc = fm.maxAscent();
2924 int const des = fm.maxDescent();
2931 bool BufferView::cursorInView(Point const & p, int h) const
2933 Cursor const & cur = cursor();
2934 // does the cursor touch the screen ?
2935 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2941 int BufferView::horizScrollOffset() const
2943 return d->horiz_scroll_offset_;
2947 int BufferView::horizScrollOffset(Text const * text,
2948 pit_type pit, pos_type pos) const
2950 // Is this a row that is currently scrolled?
2951 if (!d->current_row_slice_.empty()
2952 && &text->inset() == d->current_row_slice_.inset().asInsetText()
2953 && pit == d->current_row_slice_.pit()
2954 && pos == d->current_row_slice_.pos())
2955 return d->horiz_scroll_offset_;
2960 bool BufferView::hadHorizScrollOffset(Text const * text,
2961 pit_type pit, pos_type pos) const
2963 return !d->last_row_slice_.empty()
2964 && &text->inset() == d->last_row_slice_.inset().asInsetText()
2965 && pit == d->last_row_slice_.pit()
2966 && pos == d->last_row_slice_.pos();
2970 void BufferView::setCurrentRowSlice(CursorSlice const & rowSlice)
2972 // nothing to do if the cursor was already on this row
2973 if (d->current_row_slice_ == rowSlice) {
2974 d->last_row_slice_ = CursorSlice();
2978 // if the (previous) current row was scrolled, we have to
2979 // remember it in order to repaint it next time.
2980 if (d->horiz_scroll_offset_ != 0)
2981 d->last_row_slice_ = d->current_row_slice_;
2983 d->last_row_slice_ = CursorSlice();
2985 // Since we changed row, the scroll offset is not valid anymore
2986 d->horiz_scroll_offset_ = 0;
2987 d->current_row_slice_ = rowSlice;
2993 bool sliceInRow(CursorSlice const & cs, Text const * text, Row const & row)
2995 /* The normal case is the last line. The previous line takes care
2996 * of empty rows (e.g. empty paragraphs). Cursor boundary issues
2997 * are taken care of when setting caret_slice_ in
3000 return !cs.empty() && cs.text() == text && cs.pit() == row.pit()
3001 && ((row.pos() == row.endpos() && row.pos() == cs.pos())
3002 || (row.pos() <= cs.pos() && cs.pos() < row.endpos()));
3008 bool BufferView::needRepaint(Text const * text, Row const & row) const
3010 return d->repaint_caret_row_ && sliceInRow(d->caret_slice_, text, row);
3014 void BufferView::checkCursorScrollOffset()
3016 CursorSlice rowSlice = d->cursor_.bottom();
3017 TextMetrics const & tm = textMetrics(rowSlice.text());
3019 // Stop if metrics have not been computed yet, since it means
3020 // that there is nothing to do.
3021 if (!tm.contains(rowSlice.pit()))
3023 ParagraphMetrics const & pm = tm.parMetrics(rowSlice.pit());
3024 Row const & row = pm.getRow(rowSlice.pos(),
3025 d->cursor_.boundary() && rowSlice == d->cursor_.top());
3026 rowSlice.pos() = row.pos();
3028 // Set the row on which the cursor lives.
3029 setCurrentRowSlice(rowSlice);
3031 // Current x position of the cursor in pixels
3032 int cur_x = getPos(d->cursor_).x_;
3034 // Horizontal scroll offset of the cursor row in pixels
3035 int offset = d->horiz_scroll_offset_;
3036 int const MARGIN = 2 * theFontMetrics(d->cursor_.real_current_font).em()
3038 if (row.right_x() <= workWidth() - row.right_margin) {
3039 // Row is narrower than the work area, no offset needed.
3042 if (cur_x - offset < MARGIN) {
3043 // cursor would be too far right
3044 offset = cur_x - MARGIN;
3045 } else if (cur_x - offset > workWidth() - MARGIN) {
3046 // cursor would be too far left
3047 offset = cur_x - workWidth() + MARGIN;
3049 // Correct the offset to make sure that we do not scroll too much
3052 if (row.right_x() - offset < workWidth() - row.right_margin)
3053 offset = row.right_x() - workWidth() + row.right_margin;
3056 //lyxerr << "cur_x=" << cur_x << ", offset=" << offset << ", row.wid=" << row.width() << ", margin=" << MARGIN << endl;
3058 if (offset != d->horiz_scroll_offset_)
3059 LYXERR(Debug::PAINTING, "Horiz. scroll offset changed from "
3060 << d->horiz_scroll_offset_ << " to " << offset);
3062 if (d->update_strategy_ == NoScreenUpdate
3063 && (offset != d->horiz_scroll_offset_
3064 || !d->last_row_slice_.empty())) {
3065 // FIXME: if one uses SingleParUpdate, then home/end
3066 // will not work on long rows. Why?
3067 d->update_strategy_ = FullScreenUpdate;
3070 d->horiz_scroll_offset_ = offset;
3074 void BufferView::draw(frontend::Painter & pain, bool paint_caret)
3076 if (height_ == 0 || width_ == 0)
3078 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t--- START NODRAW ---"
3079 : "\t\t*** START DRAWING ***"));
3080 Text & text = buffer_.text();
3081 TextMetrics const & tm = d->text_metrics_[&text];
3082 int const y = tm.first().second->position();
3083 PainterInfo pi(this, pain);
3085 /** A repaint of the previous caret row is needed if there is
3086 * caret painted on screen and either
3087 * 1/ a new caret has to be painted at a place different from
3089 * 2/ there is no need for a caret anymore.
3091 d->repaint_caret_row_ = !d->caret_slice_.empty() &&
3092 ((paint_caret && d->cursor_.top() != d->caret_slice_)
3095 // Check whether the row where the cursor lives needs to be scrolled.
3096 // Update the drawing strategy if needed.
3097 checkCursorScrollOffset();
3099 switch (d->update_strategy_) {
3101 case NoScreenUpdate:
3102 // no screen painting is actually needed. In nodraw stage
3103 // however, the different coordinates of insets and paragraphs
3104 // needs to be updated.
3105 LYXERR(Debug::PAINTING, "Strategy: NoScreenUpdate");
3106 pi.full_repaint = false;
3107 if (pain.isNull()) {
3108 pi.full_repaint = true;
3110 } else if (d->repaint_caret_row_) {
3111 pi.full_repaint = false;
3116 case SingleParUpdate:
3117 pi.full_repaint = false;
3118 LYXERR(Debug::PAINTING, "Strategy: SingleParUpdate");
3119 // In general, only the current row of the outermost paragraph
3120 // will be redrawn. Particular cases where selection spans
3121 // multiple paragraph are correctly detected in TextMetrics.
3125 case DecorationUpdate:
3126 // FIXME: We should also distinguish DecorationUpdate to avoid text
3127 // drawing if possible. This is not possible to do easily right now
3128 // because of the single backing pixmap.
3130 case FullScreenUpdate:
3132 LYXERR(Debug::PAINTING,
3133 ((d->update_strategy_ == FullScreenUpdate)
3134 ? "Strategy: FullScreenUpdate"
3135 : "Strategy: DecorationUpdate"));
3137 // The whole screen, including insets, will be refreshed.
3138 pi.full_repaint = true;
3140 // Clear background.
3141 pain.fillRectangle(0, 0, width_, height_,
3142 pi.backgroundColor(&buffer_.inset()));
3147 // and possibly grey out below
3148 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3149 int const y2 = lastpm.second->position() + lastpm.second->descent();
3152 Color color = buffer().isInternal()
3153 ? Color_background : Color_bottomarea;
3154 pain.fillRectangle(0, y2, width_, height_ - y2, color);
3158 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t --- END NODRAW ---"
3159 : "\t\t *** END DRAWING ***"));
3161 // The scrollbar needs an update.
3164 // Normalize anchor for next time
3165 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
3166 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3167 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
3168 ParagraphMetrics const & pm = tm.parMetrics(pit);
3169 if (pm.position() + pm.descent() > 0) {
3170 if (d->anchor_pit_ != pit
3171 || d->anchor_ypos_ != pm.position())
3172 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
3173 << " anchor ypos = " << d->anchor_ypos_);
3174 d->anchor_pit_ = pit;
3175 d->anchor_ypos_ = pm.position();
3179 if (!pain.isNull()) {
3180 // reset the update flags, everything has been done
3181 d->update_flags_ = Update::None;
3184 // Remember what has just been done for the next draw() step
3186 d->caret_slice_ = d->cursor_.top();
3187 if (d->caret_slice_.pos() > 0
3188 && (d->cursor_.boundary()
3189 || d->caret_slice_.pos() == d->caret_slice_.lastpos()))
3190 --d->caret_slice_.pos();
3192 d->caret_slice_ = CursorSlice();
3196 void BufferView::message(docstring const & msg)
3199 d->gui_->message(msg);
3203 void BufferView::showDialog(string const & name)
3206 d->gui_->showDialog(name, string());
3210 void BufferView::showDialog(string const & name,
3211 string const & data, Inset * inset)
3214 d->gui_->showDialog(name, data, inset);
3218 void BufferView::updateDialog(string const & name, string const & data)
3221 d->gui_->updateDialog(name, data);
3225 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
3231 // FIXME: Move this out of BufferView again
3232 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
3234 if (!fname.isReadableFile()) {
3235 docstring const error = from_ascii(strerror(errno));
3236 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3237 docstring const text =
3238 bformat(_("Could not read the specified document\n"
3239 "%1$s\ndue to the error: %2$s"), file, error);
3240 Alert::error(_("Could not read file"), text);
3244 if (!fname.isReadableFile()) {
3245 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3246 docstring const text =
3247 bformat(_("%1$s\n is not readable."), file);
3248 Alert::error(_("Could not open file"), text);
3252 // FIXME UNICODE: We don't know the encoding of the file
3253 docstring file_content = fname.fileContents("UTF-8");
3254 if (file_content.empty()) {
3255 Alert::error(_("Reading not UTF-8 encoded file"),
3256 _("The file is not UTF-8 encoded.\n"
3257 "It will be read as local 8Bit-encoded.\n"
3258 "If this does not give the correct result\n"
3259 "then please change the encoding of the file\n"
3260 "to UTF-8 with a program other than LyX.\n"));
3261 file_content = fname.fileContents("local8bit");
3264 return normalize_c(file_content);
3268 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
3270 docstring const tmpstr = contentsOfPlaintextFile(f);
3275 Cursor & cur = cursor();
3276 cap::replaceSelection(cur);
3277 buffer_.undo().recordUndo(cur);
3279 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3281 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3283 buffer_.changed(true);
3287 docstring const & BufferView::inlineCompletion() const
3289 return d->inlineCompletion_;
3293 size_t const & BufferView::inlineCompletionUniqueChars() const
3295 return d->inlineCompletionUniqueChars_;
3299 DocIterator const & BufferView::inlineCompletionPos() const
3301 return d->inlineCompletionPos_;
3305 void BufferView::resetInlineCompletionPos()
3307 d->inlineCompletionPos_ = DocIterator();
3311 bool samePar(DocIterator const & a, DocIterator const & b)
3313 if (a.empty() && b.empty())
3315 if (a.empty() || b.empty())
3317 if (a.depth() != b.depth())
3319 return &a.innerParagraph() == &b.innerParagraph();
3323 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3324 docstring const & completion, size_t uniqueChars)
3326 uniqueChars = min(completion.size(), uniqueChars);
3327 bool changed = d->inlineCompletion_ != completion
3328 || d->inlineCompletionUniqueChars_ != uniqueChars;
3329 bool singlePar = true;
3330 d->inlineCompletion_ = completion;
3331 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3333 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3336 DocIterator const & old = d->inlineCompletionPos_;
3338 //lyxerr << "inlineCompletionPos changed" << std::endl;
3339 // old or pos are in another paragraph?
3340 if ((!samePar(cur, pos) && !pos.empty())
3341 || (!samePar(cur, old) && !old.empty())) {
3343 //lyxerr << "different paragraph" << std::endl;
3345 d->inlineCompletionPos_ = pos;
3350 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3351 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3353 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3358 bool BufferView::clickableInset() const
3360 return d->clickable_inset_;