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/Package.h"
85 #include "support/types.h"
95 using namespace lyx::support;
99 namespace Alert = frontend::Alert;
103 /// Return an inset of this class if it exists at the current cursor position
105 T * getInsetByCode(Cursor const & cur, InsetCode code)
107 DocIterator it = cur;
108 Inset * inset = it.nextInset();
109 if (inset && inset->lyxCode() == code)
110 return static_cast<T*>(inset);
115 /// Note that comparing contents can only be used for InsetCommand
116 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
117 docstring const & contents)
119 DocIterator tmpdit = dit;
122 Inset const * inset = tmpdit.nextInset();
124 bool const valid_code = std::find(codes.begin(), codes.end(),
125 inset->lyxCode()) != codes.end();
126 InsetCommand const * ic = inset->asInsetCommand();
127 bool const same_or_no_contents = contents.empty()
128 || (ic && (ic->getFirstNonOptParam() == contents));
130 if (valid_code && same_or_no_contents) {
135 tmpdit.forwardInset();
142 /// Looks for next inset with one of the given codes.
143 /// Note that same_content can only be used for InsetCommand
144 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
148 DocIterator tmpdit = dit;
149 tmpdit.forwardInset();
153 Inset const * inset = tmpdit.nextInset();
154 if (same_content && inset) {
155 InsetCommand const * ic = inset->asInsetCommand();
157 bool const valid_code = std::find(codes.begin(), codes.end(),
158 ic->lyxCode()) != codes.end();
160 contents = ic->getFirstNonOptParam();
164 if (!findNextInset(tmpdit, codes, contents)) {
165 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
166 Inset * inset = &tmpdit.bottom().inset();
167 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
168 if (!findNextInset(tmpdit, codes, contents))
180 /// Looks for next inset with the given code
181 void findInset(DocIterator & dit, InsetCode code, bool same_content)
183 findInset(dit, vector<InsetCode>(1, code), same_content);
187 /// Moves cursor to the next inset with one of the given codes.
188 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
191 Cursor tmpcur = bv->cursor();
192 if (!findInset(tmpcur, codes, same_content)) {
193 bv->cursor().message(_("No more insets"));
197 tmpcur.clearSelection();
198 bv->setCursor(tmpcur);
203 /// Moves cursor to the next inset with given code.
204 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
206 gotoInset(bv, vector<InsetCode>(1, code), same_content);
210 /// A map from a Text to the associated text metrics
211 typedef map<Text const *, TextMetrics> TextMetricsCache;
213 enum ScreenUpdateStrategy {
223 /////////////////////////////////////////////////////////////////////
227 /////////////////////////////////////////////////////////////////////
229 struct BufferView::Private
231 Private(BufferView & bv) : update_strategy_(FullScreenUpdate),
232 update_flags_(Update::Force),
234 anchor_pit_(0), anchor_ypos_(0),
235 inlineCompletionUniqueChars_(0),
236 last_inset_(0), clickable_inset_(false),
237 mouse_position_cache_(),
238 bookmark_edit_position_(-1), gui_(0),
239 horiz_scroll_offset_(0), repaint_caret_row_(false)
241 xsel_cache_.set = false;
245 ScrollbarParameters scrollbarParameters_;
247 ScreenUpdateStrategy update_strategy_;
249 Update::flags update_flags_;
251 CoordCache coord_cache_;
253 /// Estimated average par height for scrollbar.
255 /// this is used to handle XSelection events in the right manner.
264 pit_type anchor_pit_;
268 vector<int> par_height_;
271 DocIterator inlineCompletionPos_;
273 docstring inlineCompletion_;
275 size_t inlineCompletionUniqueChars_;
277 /// keyboard mapping object.
280 /// last visited inset.
281 /** kept to send setMouseHover(false).
282 * Not owned, so don't delete.
284 Inset const * last_inset_;
285 /// are we hovering something that we can click
286 bool clickable_inset_;
288 /// position of the mouse at the time of the last mouse move
289 /// This is used to update the hovering status of inset in
290 /// cases where the buffer is scrolled, but the mouse didn't move.
291 Point mouse_position_cache_;
293 // cache for id of the paragraph which was edited the last time
294 int bookmark_edit_position_;
296 mutable TextMetricsCache text_metrics_;
299 /** Not owned, so don't delete.
301 frontend::GuiBufferViewDelegate * gui_;
303 /// Cache for Find Next
304 FuncRequest search_request_cache_;
307 map<string, Inset *> edited_insets_;
309 /// When the row where the cursor lies is scrolled, this
310 /// contains the scroll offset
311 int horiz_scroll_offset_;
312 /// a slice pointing to the start of the row where the cursor
313 /// is (at last draw time)
314 CursorSlice current_row_slice_;
315 /// a slice pointing to the start of the row where cursor was
316 /// at previous draw event
317 CursorSlice last_row_slice_;
319 /// a slice pointing to where the cursor has been drawn after the current
321 CursorSlice caret_slice_;
322 /// indicates whether the caret slice needs to be repainted in this draw() run.
323 bool repaint_caret_row_;
327 BufferView::BufferView(Buffer & buf)
328 : width_(0), height_(0), full_screen_(false), buffer_(buf),
329 d(new Private(*this))
331 d->xsel_cache_.set = false;
332 d->intl_.initKeyMapper(lyxrc.use_kbmap);
334 d->cursor_.setBuffer(&buf);
335 d->cursor_.push(buffer_.inset());
336 d->cursor_.resetAnchor();
337 d->cursor_.setCurrentFont();
339 buffer_.updatePreviews();
343 BufferView::~BufferView()
345 // current buffer is going to be switched-off, save cursor pos
346 // Ideally, the whole cursor stack should be saved, but session
347 // currently can only handle bottom (whole document) level pit and pos.
348 // That is to say, if a cursor is in a nested inset, it will be
349 // restore to the left of the top level inset.
350 LastFilePosSection::FilePos fp;
351 fp.pit = d->cursor_.bottom().pit();
352 fp.pos = d->cursor_.bottom().pos();
353 theSession().lastFilePos().save(buffer_.fileName(), fp);
356 d->last_inset_->setMouseHover(this, false);
362 int BufferView::rightMargin() const
364 // The value used to be hardcoded to 10, which is 0.1in at 100dpi
365 int const default_margin = Length(0.1, Length::IN).inPixels(0);
366 // The additional test for the case the outliner is opened.
367 if (!full_screen_ || !lyxrc.full_screen_limit
368 || width_ < lyxrc.full_screen_width + 2 * default_margin)
369 return default_margin;
371 return (width_ - lyxrc.full_screen_width) / 2;
375 int BufferView::leftMargin() const
377 return rightMargin();
381 int BufferView::inPixels(Length const & len) const
383 Font const font = buffer().params().getFont();
384 return len.inPixels(workWidth(), theFontMetrics(font).em());
388 bool BufferView::isTopScreen() const
390 return 0 == d->scrollbarParameters_.min;
394 bool BufferView::isBottomScreen() const
396 return 0 == d->scrollbarParameters_.max;
400 Intl & BufferView::getIntl()
406 Intl const & BufferView::getIntl() const
412 CoordCache & BufferView::coordCache()
414 return d->coord_cache_;
418 CoordCache const & BufferView::coordCache() const
420 return d->coord_cache_;
424 Buffer & BufferView::buffer()
430 Buffer const & BufferView::buffer() const
436 bool BufferView::needsFitCursor() const
438 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
439 frontend::FontMetrics const & fm =
440 theFontMetrics(d->cursor_.getFont().fontInfo());
441 int const asc = fm.maxAscent();
442 int const des = fm.maxDescent();
443 Point const p = getPos(d->cursor_);
444 if (p.y_ - asc >= 0 && p.y_ + des < height_)
453 // this is for debugging only.
454 string flagsAsString(Update::flags flags)
456 if (flags == Update::None)
458 return string((flags & Update::FitCursor) ? "FitCursor " : "")
459 + ((flags & Update::Force) ? "Force " : "")
460 + ((flags & Update::ForceDraw) ? "ForceDraw " : "")
461 + ((flags & Update::SinglePar) ? "SinglePar " : "");
466 void BufferView::processUpdateFlags(Update::flags flags)
468 LYXERR(Debug::PAINTING, "BufferView::processUpdateFlags( "
469 << flagsAsString(flags) << ") buffer: " << &buffer_);
471 // Case when no explicit update is requested.
472 if (flags == Update::None)
475 // SinglePar is ignored for now (this should probably change). We
476 // set it ourselves below, at the price of always rebreaking the
477 // paragraph at cursor. This can be expensive for large tables.
478 flags = flags & ~Update::SinglePar;
480 // First check whether the metrics and inset positions should be updated
481 if (flags & Update::Force) {
482 // This will update the CoordCache items and replace Force
483 // with ForceDraw in flags.
484 updateMetrics(flags);
487 // Then make sure that the screen contains the cursor if needed
488 if (flags & Update::FitCursor) {
489 if (needsFitCursor()) {
490 scrollToCursor(d->cursor_, false);
491 // Metrics have to be recomputed (maybe again)
492 updateMetrics(flags);
494 flags = flags & ~Update::FitCursor;
497 // Finally detect whether we can only repaint a single paragraph
498 if (!(flags & Update::ForceDraw)) {
499 if (singleParUpdate())
500 flags = flags | Update::SinglePar;
502 updateMetrics(flags);
505 // Add flags to the the update flags. These will be reset to None
506 // after the redraw is actually done
507 d->update_flags_ = d->update_flags_ | flags;
508 LYXERR(Debug::PAINTING, "Cumulative flags: " << flagsAsString(flags));
510 // Now compute the update strategy
511 // Possibly values in flag are None, Decoration, ForceDraw
512 LATTEST((d->update_flags_ & ~(Update::None | Update::SinglePar
513 | Update::Decoration | Update::ForceDraw)) == 0);
515 if (d->update_flags_ & Update::ForceDraw)
516 d->update_strategy_ = FullScreenUpdate;
517 else if (d->update_flags_ & Update::Decoration)
518 d->update_strategy_ = DecorationUpdate;
519 else if (d->update_flags_ & Update::SinglePar)
520 d->update_strategy_ = SingleParUpdate;
522 // no need to redraw anything.
523 d->update_strategy_ = NoScreenUpdate;
526 updateHoveredInset();
529 buffer_.changed(false);
533 void BufferView::updateScrollbar()
535 if (height_ == 0 && width_ == 0)
538 // We prefer fixed size line scrolling.
539 d->scrollbarParameters_.single_step = defaultRowHeight();
540 // We prefer full screen page scrolling.
541 d->scrollbarParameters_.page_step = height_;
543 Text & t = buffer_.text();
544 TextMetrics & tm = d->text_metrics_[&t];
546 LYXERR(Debug::GUI, " Updating scrollbar: height: "
547 << t.paragraphs().size()
548 << " curr par: " << d->cursor_.bottom().pit()
549 << " default height " << defaultRowHeight());
551 size_t const parsize = t.paragraphs().size();
552 if (d->par_height_.size() != parsize) {
553 d->par_height_.clear();
554 // FIXME: We assume a default paragraph height of 2 rows. This
555 // should probably be pondered with the screen width.
556 d->par_height_.resize(parsize, defaultRowHeight() * 2);
559 // Look at paragraph heights on-screen
560 pair<pit_type, ParagraphMetrics const *> first = tm.first();
561 pair<pit_type, ParagraphMetrics const *> last = tm.last();
562 for (pit_type pit = first.first; pit <= last.first; ++pit) {
563 d->par_height_[pit] = tm.parMetrics(pit).height();
564 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
565 << d->par_height_[pit]);
568 int top_pos = first.second->position() - first.second->ascent();
569 int bottom_pos = last.second->position() + last.second->descent();
570 bool first_visible = first.first == 0 && top_pos >= 0;
571 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
572 if (first_visible && last_visible) {
573 d->scrollbarParameters_.min = 0;
574 d->scrollbarParameters_.max = 0;
578 d->scrollbarParameters_.min = top_pos;
579 for (size_t i = 0; i != size_t(first.first); ++i)
580 d->scrollbarParameters_.min -= d->par_height_[i];
581 d->scrollbarParameters_.max = bottom_pos;
582 for (size_t i = last.first + 1; i != parsize; ++i)
583 d->scrollbarParameters_.max += d->par_height_[i];
585 // The reference is the top position so we remove one page.
586 if (lyxrc.scroll_below_document)
587 d->scrollbarParameters_.max -= minVisiblePart();
589 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
591 // 0 must be inside the range as it denotes the current position
592 if (d->scrollbarParameters_.max < 0)
593 d->scrollbarParameters_.max = 0;
594 if (d->scrollbarParameters_.min > 0)
595 d->scrollbarParameters_.min = 0;
599 ScrollbarParameters const & BufferView::scrollbarParameters() const
601 return d->scrollbarParameters_;
605 docstring BufferView::toolTip(int x, int y) const
607 // Get inset under mouse, if there is one.
608 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
610 // No inset, no tooltip...
612 return covering_inset->toolTip(*this, x, y);
616 string BufferView::contextMenu(int x, int y) const
618 //If there is a selection, return the containing inset menu
619 if (d->cursor_.selection())
620 return d->cursor_.inset().contextMenu(*this, x, y);
622 // Get inset under mouse, if there is one.
623 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
625 return covering_inset->contextMenu(*this, x, y);
627 return buffer_.inset().contextMenu(*this, x, y);
632 void BufferView::scrollDocView(int const value, bool update)
634 // The scrollbar values are relative to the top of the screen, therefore the
635 // offset is equal to the target value.
637 // No scrolling at all? No need to redraw anything
641 // If the offset is less than 2 screen height, prefer to scroll instead.
642 if (abs(value) <= 2 * height_) {
643 d->anchor_ypos_ -= value;
644 processUpdateFlags(Update::Force);
648 // cut off at the top
649 if (value <= d->scrollbarParameters_.min) {
650 DocIterator dit = doc_iterator_begin(&buffer_);
651 showCursor(dit, false, update);
652 LYXERR(Debug::SCROLLING, "scroll to top");
656 // cut off at the bottom
657 if (value >= d->scrollbarParameters_.max) {
658 DocIterator dit = doc_iterator_end(&buffer_);
660 showCursor(dit, false, update);
661 LYXERR(Debug::SCROLLING, "scroll to bottom");
665 // find paragraph at target position
666 int par_pos = d->scrollbarParameters_.min;
668 for (; i != int(d->par_height_.size()); ++i) {
669 par_pos += d->par_height_[i];
670 if (par_pos >= value)
674 if (par_pos < value) {
675 // It seems we didn't find the correct pit so stay on the safe side and
677 LYXERR0("scrolling position not found!");
678 scrollDocView(d->scrollbarParameters_.max, update);
682 DocIterator dit = doc_iterator_begin(&buffer_);
684 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
685 showCursor(dit, false, update);
689 // FIXME: this method is not working well.
690 void BufferView::setCursorFromScrollbar()
692 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
694 int const height = 2 * defaultRowHeight();
695 int const first = height;
696 int const last = height_ - height;
698 Cursor const & oldcur = d->cursor_;
700 switch (cursorStatus(oldcur)) {
708 int const y = getPos(oldcur).y_;
709 newy = min(last, max(y, first));
713 // We reset the cursor because cursorStatus() does not
714 // work when the cursor is within mathed.
717 tm.setCursorFromCoordinates(cur, 0, newy);
719 // update the bufferview cursor and notify insets
720 // FIXME: Care about the d->cursor_ flags to redraw if needed
721 Cursor old = d->cursor_;
723 // the DEPM call in mouseSetCursor() might have destroyed the
724 // paragraph the cursor is in.
725 bool badcursor = old.fixIfBroken();
726 badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
728 d->cursor_.fixIfBroken();
732 Change const BufferView::getCurrentChange() const
734 if (!d->cursor_.selection())
735 return Change(Change::UNCHANGED);
737 DocIterator dit = d->cursor_.selectionBegin();
738 // The selected content might have been changed (see #7685)
739 dit = dit.getInnerText();
740 return dit.paragraph().lookupChange(dit.pos());
744 // this could be used elsewhere as well?
745 // FIXME: This does not work within mathed!
746 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
748 Point const p = getPos(dit);
751 if (p.y_ > workHeight())
757 void BufferView::bookmarkEditPosition()
759 // Don't eat cpu time for each keystroke
760 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
763 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
767 void BufferView::saveBookmark(unsigned int idx)
769 // tentatively save bookmark, id and pos will be used to
770 // acturately locate a bookmark in a 'live' lyx session.
771 // pit and pos will be updated with bottom level pit/pos
773 if (!buffer_.isInternal()) {
774 theSession().bookmarks().save(
776 d->cursor_.bottom().pit(),
777 d->cursor_.bottom().pos(),
778 d->cursor_.paragraph().id(),
783 // emit message signal.
784 message(_("Save bookmark"));
789 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
790 int top_id, pos_type top_pos)
792 bool success = false;
795 d->cursor_.clearSelection();
797 // if a valid par_id is given, try it first
798 // This is the case for a 'live' bookmark when unique paragraph ID
799 // is used to track bookmarks.
801 dit = buffer_.getParFromID(top_id);
803 dit.pos() = min(dit.paragraph().size(), top_pos);
804 // Some slices of the iterator may not be
805 // reachable (e.g. closed collapsible inset)
806 // so the dociterator may need to be
807 // shortened. Otherwise, setCursor may crash
808 // lyx when the cursor can not be set to these
810 size_t const n = dit.depth();
811 for (size_t i = 0; i < n; ++i)
812 if (!dit[i].inset().editable()) {
820 // if top_id == 0, or searching through top_id failed
821 // This is the case for a 'restored' bookmark when only bottom
822 // (document level) pit was saved. Because of this, bookmark
823 // restoration is inaccurate. If a bookmark was within an inset,
824 // it will be restored to the left of the outmost inset that contains
826 if (bottom_pit < int(buffer_.paragraphs().size())) {
827 dit = doc_iterator_begin(&buffer_);
829 dit.pit() = bottom_pit;
830 dit.pos() = min(bottom_pos, dit.paragraph().size());
835 // Note: only bottom (document) level pit is set.
837 // set the current font.
838 d->cursor_.setCurrentFont();
839 // Do not forget to reset the anchor (see #9912)
840 d->cursor_.resetAnchor();
841 processUpdateFlags(Update::FitCursor);
848 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
850 if (d->cursor_.real_current_font.isRightToLeft()) {
851 if (d->intl_.keymap == Intl::PRIMARY)
852 d->intl_.keyMapSec();
854 if (d->intl_.keymap == Intl::SECONDARY)
855 d->intl_.keyMapPrim();
858 d->intl_.getTransManager().translateAndInsert(c, t, cur);
862 int BufferView::workWidth() const
868 void BufferView::recenter()
870 showCursor(d->cursor_, true, true);
874 void BufferView::showCursor()
876 showCursor(d->cursor_, false, true);
880 void BufferView::showCursor(DocIterator const & dit,
881 bool recenter, bool update)
883 if (scrollToCursor(dit, recenter) && update)
884 processUpdateFlags(Update::Force);
888 void BufferView::scrollToCursor()
890 if (scrollToCursor(d->cursor_, false))
891 processUpdateFlags(Update::Force);
895 bool BufferView::scrollToCursor(DocIterator const & dit, bool const recenter)
897 // We are not properly started yet, delay until resizing is
902 LYXERR(Debug::SCROLLING, "recentering!");
904 CursorSlice const & bot = dit.bottom();
905 TextMetrics & tm = d->text_metrics_[bot.text()];
907 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
908 int bot_pit = bot.pit();
909 if (bot_pit > max_pit) {
910 // FIXME: Why does this happen?
911 LYXERR0("bottom pit is greater that max pit: "
912 << bot_pit << " > " << max_pit);
916 if (bot_pit == tm.first().first - 1)
917 tm.newParMetricsUp();
918 else if (bot_pit == tm.last().first + 1)
919 tm.newParMetricsDown();
921 if (tm.contains(bot_pit)) {
922 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
923 LBUFERR(!pm.rows().empty());
924 // FIXME: smooth scrolling doesn't work in mathed.
925 CursorSlice const & cs = dit.innerTextSlice();
926 int offset = coordOffset(dit).y_;
927 int ypos = pm.position() + offset;
928 Dimension const & row_dim =
929 pm.getRow(cs.pos(), dit.boundary()).dimension();
932 scrolled = scroll(ypos - height_/2);
934 // We try to visualize the whole row, if the row height is larger than
935 // the screen height, we scroll to a heuristic value of height_ / 4.
936 // FIXME: This heuristic value should be replaced by a recursive search
937 // for a row in the inset that can be visualized completely.
938 else if (row_dim.height() > height_) {
939 if (ypos < defaultRowHeight())
940 scrolled = scroll(ypos - height_ / 4);
941 else if (ypos > height_ - defaultRowHeight())
942 scrolled = scroll(ypos - 3 * height_ / 4);
945 // If the top part of the row falls of the screen, we scroll
946 // up to align the top of the row with the top of the screen.
947 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
948 int ynew = row_dim.ascent();
949 scrolled = scrollUp(ynew - ypos);
952 // If the bottom of the row falls of the screen, we scroll down.
953 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
954 int ynew = height_ - row_dim.descent();
955 scrolled = scrollDown(ypos - ynew);
958 // else, nothing to do, the cursor is already visible so we just return.
959 return scrolled != 0;
962 // fix inline completion position
963 if (d->inlineCompletionPos_.fixIfBroken())
964 d->inlineCompletionPos_ = DocIterator();
966 tm.redoParagraph(bot_pit);
967 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
968 int offset = coordOffset(dit).y_;
970 d->anchor_pit_ = bot_pit;
971 CursorSlice const & cs = dit.innerTextSlice();
972 Dimension const & row_dim =
973 pm.getRow(cs.pos(), dit.boundary()).dimension();
976 d->anchor_ypos_ = height_/2;
977 else if (d->anchor_pit_ == 0)
978 d->anchor_ypos_ = offset + pm.ascent();
979 else if (d->anchor_pit_ == max_pit)
980 d->anchor_ypos_ = height_ - offset - row_dim.descent();
981 else if (offset > height_)
982 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
984 d->anchor_ypos_ = defaultRowHeight() * 2;
990 void BufferView::makeDocumentClass()
992 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
993 buffer_.params().makeDocumentClass();
994 updateDocumentClass(olddc);
998 void BufferView::updateDocumentClass(DocumentClassConstPtr olddc)
1000 message(_("Converting document to new document class..."));
1002 StableDocIterator backcur(d->cursor_);
1003 ErrorList & el = buffer_.errorList("Class Switch");
1004 cap::switchBetweenClasses(
1005 olddc, buffer_.params().documentClassPtr(),
1006 static_cast<InsetText &>(buffer_.inset()), el);
1008 setCursor(backcur.asDocIterator(&buffer_));
1010 buffer_.errors("Class Switch");
1014 /** Return the change status at cursor position, taking into account the
1015 * status at each level of the document iterator (a table in a deleted
1016 * footnote is deleted).
1017 * When \param outer is true, the top slice is not looked at.
1019 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
1021 size_t const depth = dit.depth() - (outer ? 1 : 0);
1023 for (size_t i = 0 ; i < depth ; ++i) {
1024 CursorSlice const & slice = dit[i];
1025 if (!slice.inset().inMathed()
1026 && slice.pos() < slice.paragraph().size()) {
1027 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
1028 if (ch != Change::UNCHANGED)
1032 return Change::UNCHANGED;
1036 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1038 FuncCode const act = cmd.action();
1040 // Can we use a readonly buffer?
1041 if (buffer_.isReadonly()
1042 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1043 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1044 if (buffer_.hasReadonlyFlag())
1045 flag.message(from_utf8(N_("Document is read-only")));
1047 flag.message(from_utf8(N_("Document has been modified externally")));
1048 flag.setEnabled(false);
1052 // Are we in a DELETED change-tracking region?
1053 if (lookupChangeType(d->cursor_, true) == Change::DELETED
1054 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1055 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1056 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1057 flag.setEnabled(false);
1061 Cursor & cur = d->cursor_;
1063 if (cur.getStatus(cmd, flag))
1068 // FIXME: This is a bit problematic because we don't check if this is
1069 // a document BufferView or not for these LFUNs. We probably have to
1070 // dispatch both to currentBufferView() and, if that fails,
1071 // to documentBufferView(); same as we do now for current Buffer and
1072 // document Buffer. Ideally those LFUN should go to Buffer as they
1073 // operate on the full Buffer and the cursor is only needed either for
1074 // an Undo record or to restore a cursor position. But we don't know
1075 // how to do that inside Buffer of course.
1076 case LFUN_BUFFER_PARAMS_APPLY:
1077 case LFUN_LAYOUT_MODULES_CLEAR:
1078 case LFUN_LAYOUT_MODULE_ADD:
1079 case LFUN_LAYOUT_RELOAD:
1080 case LFUN_TEXTCLASS_APPLY:
1081 case LFUN_TEXTCLASS_LOAD:
1082 flag.setEnabled(!buffer_.isReadonly());
1086 // We do not use the LyXAction flag for readonly because Undo sets the
1087 // buffer clean/dirty status by itself.
1088 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1091 // We do not use the LyXAction flag for readonly because Redo sets the
1092 // buffer clean/dirty status by itself.
1093 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1095 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1096 case LFUN_FILE_INSERT_PLAINTEXT: {
1097 docstring const fname = cmd.argument();
1098 if (!FileName::isAbsolute(to_utf8(fname))) {
1099 flag.message(_("Absolute filename expected."));
1102 flag.setEnabled(cur.inTexted());
1105 case LFUN_FILE_INSERT:
1106 case LFUN_BOOKMARK_SAVE:
1107 // FIXME: Actually, these LFUNS should be moved to Text
1108 flag.setEnabled(cur.inTexted());
1111 case LFUN_FONT_STATE:
1112 case LFUN_LABEL_INSERT:
1113 case LFUN_INFO_INSERT:
1114 case LFUN_PARAGRAPH_GOTO:
1115 case LFUN_NOTE_NEXT:
1116 case LFUN_REFERENCE_NEXT:
1117 case LFUN_WORD_FIND:
1118 case LFUN_WORD_FIND_FORWARD:
1119 case LFUN_WORD_FIND_BACKWARD:
1120 case LFUN_WORD_REPLACE:
1123 case LFUN_MARK_TOGGLE:
1124 case LFUN_SCREEN_RECENTER:
1125 case LFUN_SCREEN_SHOW_CURSOR:
1126 case LFUN_BIBTEX_DATABASE_ADD:
1127 case LFUN_BIBTEX_DATABASE_DEL:
1128 case LFUN_STATISTICS:
1129 case LFUN_KEYMAP_OFF:
1130 case LFUN_KEYMAP_PRIMARY:
1131 case LFUN_KEYMAP_SECONDARY:
1132 case LFUN_KEYMAP_TOGGLE:
1133 case LFUN_INSET_SELECT_ALL:
1134 flag.setEnabled(true);
1137 case LFUN_WORD_FINDADV: {
1138 FindAndReplaceOptions opt;
1139 istringstream iss(to_utf8(cmd.argument()));
1141 flag.setEnabled(opt.repl_buf_name.empty()
1142 || !buffer_.isReadonly());
1146 case LFUN_LABEL_GOTO:
1147 flag.setEnabled(!cmd.argument().empty()
1148 || getInsetByCode<InsetRef>(cur, REF_CODE));
1151 case LFUN_CHANGES_MERGE:
1152 case LFUN_CHANGE_NEXT:
1153 case LFUN_CHANGE_PREVIOUS:
1154 case LFUN_ALL_CHANGES_ACCEPT:
1155 case LFUN_ALL_CHANGES_REJECT:
1156 flag.setEnabled(buffer_.areChangesPresent());
1159 case LFUN_SCREEN_UP:
1160 case LFUN_SCREEN_DOWN:
1162 case LFUN_SCREEN_UP_SELECT:
1163 case LFUN_SCREEN_DOWN_SELECT:
1164 case LFUN_INSET_FORALL:
1165 flag.setEnabled(true);
1168 case LFUN_LAYOUT_TABULAR:
1169 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1173 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1176 case LFUN_LAYOUT_PARAGRAPH:
1177 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1180 case LFUN_BRANCH_ADD_INSERT:
1181 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1184 case LFUN_DIALOG_SHOW_NEW_INSET:
1185 // FIXME: this is wrong, but I do not understand the
1187 if (cur.inset().lyxCode() == CAPTION_CODE)
1188 return cur.inset().getStatus(cur, cmd, flag);
1189 // FIXME we should consider passthru paragraphs too.
1190 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1193 case LFUN_CITATION_INSERT: {
1194 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1195 // FIXME: This could turn in a recursive hell.
1196 // Shouldn't we use Buffer::getStatus() instead?
1197 flag.setEnabled(lyx::getStatus(fr).enabled());
1200 case LFUN_INSET_APPLY: {
1201 string const name = cmd.getArg(0);
1202 Inset * inset = editedInset(name);
1204 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1205 if (!inset->getStatus(cur, fr, flag)) {
1206 // Every inset is supposed to handle this
1207 LASSERT(false, break);
1210 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1211 flag = lyx::getStatus(fr);
1224 Inset * BufferView::editedInset(string const & name) const
1226 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1227 return it == d->edited_insets_.end() ? 0 : it->second;
1231 void BufferView::editInset(string const & name, Inset * inset)
1233 d->edited_insets_[name] = inset;
1237 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1239 LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1241 string const argument = to_utf8(cmd.argument());
1242 Cursor & cur = d->cursor_;
1245 // Don't dispatch function that does not apply to internal buffers.
1246 if (buffer_.isInternal()
1247 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1250 // We'll set this back to false if need be.
1251 bool dispatched = true;
1252 buffer_.undo().beginUndoGroup();
1254 FuncCode const act = cmd.action();
1257 case LFUN_BUFFER_PARAMS_APPLY: {
1258 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1259 cur.recordUndoBufferParams();
1260 istringstream ss(to_utf8(cmd.argument()));
1263 int const unknown_tokens = buffer_.readHeader(lex);
1264 if (unknown_tokens != 0) {
1265 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1266 << unknown_tokens << " unknown token"
1267 << (unknown_tokens == 1 ? "" : "s"));
1269 updateDocumentClass(olddc);
1271 // We are most certainly here because of a change in the document
1272 // It is then better to make sure that all dialogs are in sync with
1273 // current document settings.
1274 dr.screenUpdate(Update::Force | Update::FitCursor);
1275 dr.forceBufferUpdate();
1279 case LFUN_LAYOUT_MODULES_CLEAR: {
1280 // FIXME: this modifies the document in cap::switchBetweenClasses
1281 // without calling recordUndo. Fix this before using
1282 // recordUndoBufferParams().
1283 cur.recordUndoFullBuffer();
1284 buffer_.params().clearLayoutModules();
1285 makeDocumentClass();
1286 dr.screenUpdate(Update::Force);
1287 dr.forceBufferUpdate();
1291 case LFUN_LAYOUT_MODULE_ADD: {
1292 BufferParams const & params = buffer_.params();
1293 if (!params.layoutModuleCanBeAdded(argument)) {
1294 LYXERR0("Module `" << argument <<
1295 "' cannot be added due to failed requirements or "
1296 "conflicts with installed modules.");
1299 // FIXME: this modifies the document in cap::switchBetweenClasses
1300 // without calling recordUndo. Fix this before using
1301 // recordUndoBufferParams().
1302 cur.recordUndoFullBuffer();
1303 buffer_.params().addLayoutModule(argument);
1304 makeDocumentClass();
1305 dr.screenUpdate(Update::Force);
1306 dr.forceBufferUpdate();
1310 case LFUN_TEXTCLASS_APPLY: {
1311 // since this shortcircuits, the second call is made only if
1313 bool const success =
1314 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1315 LayoutFileList::get().load(argument, buffer_.filePath());
1317 docstring s = bformat(_("The document class `%1$s' "
1318 "could not be loaded."), from_utf8(argument));
1319 frontend::Alert::error(_("Could not load class"), s);
1323 LayoutFile const * old_layout = buffer_.params().baseClass();
1324 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1326 if (old_layout == new_layout)
1330 // Save the old, possibly modular, layout for use in conversion.
1331 // FIXME: this modifies the document in cap::switchBetweenClasses
1332 // without calling recordUndo. Fix this before using
1333 // recordUndoBufferParams().
1334 cur.recordUndoFullBuffer();
1335 buffer_.params().setBaseClass(argument);
1336 makeDocumentClass();
1337 dr.screenUpdate(Update::Force);
1338 dr.forceBufferUpdate();
1342 case LFUN_TEXTCLASS_LOAD: {
1343 // since this shortcircuits, the second call is made only if
1345 bool const success =
1346 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1347 LayoutFileList::get().load(argument, buffer_.filePath());
1349 docstring s = bformat(_("The document class `%1$s' "
1350 "could not be loaded."), from_utf8(argument));
1351 frontend::Alert::error(_("Could not load class"), s);
1356 case LFUN_LAYOUT_RELOAD: {
1357 LayoutFileIndex bc = buffer_.params().baseClassID();
1358 LayoutFileList::get().reset(bc);
1359 buffer_.params().setBaseClass(bc);
1360 makeDocumentClass();
1361 dr.screenUpdate(Update::Force);
1362 dr.forceBufferUpdate();
1367 dr.setMessage(_("Undo"));
1368 cur.clearSelection();
1369 if (!cur.textUndo())
1370 dr.setMessage(_("No further undo information"));
1372 dr.screenUpdate(Update::Force | Update::FitCursor);
1373 dr.forceBufferUpdate();
1377 dr.setMessage(_("Redo"));
1378 cur.clearSelection();
1379 if (!cur.textRedo())
1380 dr.setMessage(_("No further redo information"));
1382 dr.screenUpdate(Update::Force | Update::FitCursor);
1383 dr.forceBufferUpdate();
1386 case LFUN_FONT_STATE:
1387 dr.setMessage(cur.currentState(false));
1390 case LFUN_BOOKMARK_SAVE:
1391 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1394 case LFUN_LABEL_GOTO: {
1395 docstring label = cmd.argument();
1396 if (label.empty()) {
1398 getInsetByCode<InsetRef>(cur, REF_CODE);
1400 label = inset->getParam("reference");
1401 // persistent=false: use temp_bookmark
1405 if (!label.empty()) {
1407 // at the moment, this is redundant, since gotoLabel will
1408 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1410 dr.screenUpdate(Update::Force | Update::FitCursor);
1415 case LFUN_PARAGRAPH_GOTO: {
1416 int const id = convert<int>(cmd.getArg(0));
1417 pos_type const pos = convert<int>(cmd.getArg(1));
1420 string const str_id_end = cmd.getArg(2);
1421 string const str_pos_end = cmd.getArg(3);
1423 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1424 b = theBufferList().next(b)) {
1427 cur.setCursor(b->getParFromID(id));
1429 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1433 LYXERR(Debug::INFO, "Paragraph " << cur.paragraph().id()
1434 << " found in buffer `"
1435 << b->absFileName() << "'.");
1437 if (b == &buffer_) {
1439 if (str_id_end.empty() || str_pos_end.empty()) {
1442 mouseSetCursor(cur);
1445 int const id_end = convert<int>(str_id_end);
1446 pos_type const pos_end = convert<int>(str_pos_end);
1447 success = setCursorFromEntries({id, pos},
1451 dr.screenUpdate(Update::Force | Update::FitCursor);
1453 // Switch to other buffer view and resend cmd
1454 lyx::dispatch(FuncRequest(
1455 LFUN_BUFFER_SWITCH, b->absFileName()));
1463 case LFUN_NOTE_NEXT:
1464 gotoInset(this, NOTE_CODE, false);
1467 case LFUN_REFERENCE_NEXT: {
1468 vector<InsetCode> tmp;
1469 tmp.push_back(LABEL_CODE);
1470 tmp.push_back(REF_CODE);
1471 gotoInset(this, tmp, true);
1475 case LFUN_CHANGE_NEXT:
1476 findNextChange(this);
1477 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1478 dr.screenUpdate(Update::Force | Update::FitCursor);
1481 case LFUN_CHANGE_PREVIOUS:
1482 findPreviousChange(this);
1483 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1484 dr.screenUpdate(Update::Force | Update::FitCursor);
1487 case LFUN_CHANGES_MERGE:
1488 if (findNextChange(this) || findPreviousChange(this)) {
1489 dr.screenUpdate(Update::Force | Update::FitCursor);
1490 dr.forceBufferUpdate();
1491 showDialog("changes");
1495 case LFUN_ALL_CHANGES_ACCEPT:
1496 // select complete document
1498 cur.selHandle(true);
1499 buffer_.text().cursorBottom(cur);
1500 // accept everything in a single step to support atomic undo
1501 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1503 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1504 dr.screenUpdate(Update::Force | Update::FitCursor);
1505 dr.forceBufferUpdate();
1508 case LFUN_ALL_CHANGES_REJECT:
1509 // select complete document
1511 cur.selHandle(true);
1512 buffer_.text().cursorBottom(cur);
1513 // reject everything in a single step to support atomic undo
1514 // Note: reject does not work recursively; the user may have to repeat the operation
1515 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1517 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1518 dr.screenUpdate(Update::Force | Update::FitCursor);
1519 dr.forceBufferUpdate();
1522 case LFUN_WORD_FIND_FORWARD:
1523 case LFUN_WORD_FIND_BACKWARD: {
1525 // Would it maybe be better if this variable were view specific anyway?
1526 static docstring last_search;
1527 docstring searched_string;
1529 if (!cmd.argument().empty()) {
1530 last_search = cmd.argument();
1531 searched_string = cmd.argument();
1533 searched_string = last_search;
1536 if (searched_string.empty())
1539 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1540 docstring const data =
1541 find2string(searched_string, true, false, fw);
1542 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1544 dr.screenUpdate(Update::Force | Update::FitCursor);
1548 case LFUN_WORD_FIND: {
1549 FuncRequest req = cmd;
1550 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1551 req = d->search_request_cache_;
1552 if (req.argument().empty()) {
1553 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1556 if (lyxfind(this, req))
1557 dr.screenUpdate(Update::Force | Update::FitCursor);
1559 d->search_request_cache_ = req;
1563 case LFUN_WORD_REPLACE: {
1564 bool has_deleted = false;
1565 if (cur.selection()) {
1566 DocIterator beg = cur.selectionBegin();
1567 DocIterator end = cur.selectionEnd();
1568 if (beg.pit() == end.pit()) {
1569 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1570 if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1577 if (lyxreplace(this, cmd, has_deleted)) {
1578 dr.forceBufferUpdate();
1579 dr.screenUpdate(Update::Force | Update::FitCursor);
1584 case LFUN_WORD_FINDADV: {
1585 FindAndReplaceOptions opt;
1586 istringstream iss(to_utf8(cmd.argument()));
1588 if (findAdv(this, opt)) {
1589 dr.screenUpdate(Update::Force | Update::FitCursor);
1600 cur.clearSelection();
1601 dr.setMessage(from_utf8(N_("Mark off")));
1605 cur.clearSelection();
1607 dr.setMessage(from_utf8(N_("Mark on")));
1610 case LFUN_MARK_TOGGLE:
1611 cur.selection(false);
1614 dr.setMessage(from_utf8(N_("Mark removed")));
1617 dr.setMessage(from_utf8(N_("Mark set")));
1622 case LFUN_SCREEN_SHOW_CURSOR:
1626 case LFUN_SCREEN_RECENTER:
1630 case LFUN_BIBTEX_DATABASE_ADD: {
1631 Cursor tmpcur = cur;
1632 findInset(tmpcur, BIBTEX_CODE, false);
1633 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1636 if (inset->addDatabase(cmd.argument()))
1637 dr.forceBufferUpdate();
1642 case LFUN_BIBTEX_DATABASE_DEL: {
1643 Cursor tmpcur = cur;
1644 findInset(tmpcur, BIBTEX_CODE, false);
1645 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1648 if (inset->delDatabase(cmd.argument()))
1649 dr.forceBufferUpdate();
1654 case LFUN_STATISTICS: {
1655 DocIterator from, to;
1656 if (cur.selection()) {
1657 from = cur.selectionBegin();
1658 to = cur.selectionEnd();
1660 from = doc_iterator_begin(&buffer_);
1661 to = doc_iterator_end(&buffer_);
1663 buffer_.updateStatistics(from, to);
1664 int const words = buffer_.wordCount();
1665 int const chars = buffer_.charCount(false);
1666 int const chars_blanks = buffer_.charCount(true);
1668 if (cur.selection())
1669 message = _("Statistics for the selection:");
1671 message = _("Statistics for the document:");
1674 message += bformat(_("%1$d words"), words);
1676 message += _("One word");
1678 if (chars_blanks != 1)
1679 message += bformat(_("%1$d characters (including blanks)"),
1682 message += _("One character (including blanks)");
1685 message += bformat(_("%1$d characters (excluding blanks)"),
1688 message += _("One character (excluding blanks)");
1690 Alert::information(_("Statistics"), message);
1694 case LFUN_SCREEN_UP:
1695 case LFUN_SCREEN_DOWN: {
1696 Point p = getPos(cur);
1697 // This code has been commented out to enable to scroll down a
1698 // document, even if there are large insets in it (see bug #5465).
1699 /*if (p.y_ < 0 || p.y_ > height_) {
1700 // The cursor is off-screen so recenter before proceeding.
1704 int const scrolled = scroll(act == LFUN_SCREEN_UP
1705 ? -height_ : height_);
1706 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1708 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1709 p = Point(width_, height_);
1710 bool const in_texted = cur.inTexted();
1711 cur.setCursor(doc_iterator_begin(cur.buffer()));
1712 cur.selHandle(false);
1713 // Force an immediate computation of metrics because we need it below
1714 processUpdateFlags(Update::Force);
1716 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1717 true, act == LFUN_SCREEN_UP);
1718 //FIXME: what to do with cur.x_target()?
1719 bool update = in_texted && cur.bv().checkDepm(cur, old);
1722 if (update || cur.mark())
1723 dr.screenUpdate(Update::Force | Update::FitCursor);
1725 dr.forceBufferUpdate();
1730 string const scroll_type = cmd.getArg(0);
1731 int scroll_step = 0;
1732 if (scroll_type == "line")
1733 scroll_step = d->scrollbarParameters_.single_step;
1734 else if (scroll_type == "page")
1735 scroll_step = d->scrollbarParameters_.page_step;
1738 string const scroll_quantity = cmd.getArg(1);
1739 if (scroll_quantity == "up")
1740 scrollUp(scroll_step);
1741 else if (scroll_quantity == "down")
1742 scrollDown(scroll_step);
1744 int const scroll_value = convert<int>(scroll_quantity);
1746 scroll(scroll_step * scroll_value);
1748 dr.screenUpdate(Update::ForceDraw);
1749 dr.forceBufferUpdate();
1753 case LFUN_SCREEN_UP_SELECT: {
1754 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
1755 cur.selHandle(true);
1756 if (isTopScreen()) {
1757 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1761 int y = getPos(cur).y_;
1762 int const ymin = y - height_ + defaultRowHeight();
1763 while (y > ymin && cur.up())
1767 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1771 case LFUN_SCREEN_DOWN_SELECT: {
1772 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
1773 cur.selHandle(true);
1774 if (isBottomScreen()) {
1775 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1779 int y = getPos(cur).y_;
1780 int const ymax = y + height_ - defaultRowHeight();
1781 while (y < ymax && cur.down())
1785 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1790 case LFUN_INSET_SELECT_ALL: {
1791 // true if all cells are selected
1792 bool const all_selected = cur.depth() > 1
1793 && cur.selBegin().at_begin()
1794 && cur.selEnd().at_end();
1795 // true if some cells are selected
1796 bool const cells_selected = cur.depth() > 1
1797 && cur.selBegin().at_cell_begin()
1798 && cur.selEnd().at_cell_end();
1799 if (all_selected || (cells_selected && !cur.inset().isTable())) {
1800 // All the contents of the inset if selected, or only at
1801 // least one cell but inset is not a table.
1802 // Select the inset from outside.
1805 cur.selection(true);
1807 } else if (cells_selected) {
1808 // At least one complete cell is selected and inset is a table.
1813 cur.selection(true);
1814 cur.idx() = cur.lastidx();
1815 cur.pos() = cur.lastpos();
1817 // select current cell
1821 cur.selection(true);
1822 cur.pit() = cur.lastpit();
1823 cur.pos() = cur.lastpos();
1825 cur.setCurrentFont();
1826 dr.screenUpdate(Update::Force);
1831 // This would be in Buffer class if only Cursor did not
1832 // require a bufferview
1833 case LFUN_INSET_FORALL: {
1834 docstring const name = from_utf8(cmd.getArg(0));
1835 string const commandstr = cmd.getLongArg(1);
1836 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1838 // an arbitrary number to limit number of iterations
1839 const int max_iter = 100000;
1841 Cursor & cur = d->cursor_;
1842 Cursor const savecur = cur;
1844 if (!cur.nextInset())
1846 cur.beginUndoGroup();
1847 while(cur && iterations < max_iter) {
1848 Inset * const ins = cur.nextInset();
1851 docstring insname = ins->layoutName();
1852 while (!insname.empty()) {
1853 if (insname == name || name == from_utf8("*")) {
1855 lyx::dispatch(fr, dr);
1859 size_t const i = insname.rfind(':');
1860 if (i == string::npos)
1862 insname = insname.substr(0, i);
1864 // if we did not delete the inset, skip it
1865 if (!cur.nextInset() || cur.nextInset() == ins)
1870 /** This is a dummy undo record only to remember the cursor
1871 * that has just been set; this will be used on a redo action
1872 * (see ticket #10097)
1874 * FIXME: a better fix would be to have a way to set the
1875 * cursor value directly, but I am not sure it is worth it.
1879 dr.screenUpdate(Update::Force);
1880 dr.forceBufferUpdate();
1882 if (iterations >= max_iter) {
1884 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1886 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1891 case LFUN_BRANCH_ADD_INSERT: {
1892 docstring branch_name = from_utf8(cmd.getArg(0));
1893 if (branch_name.empty())
1894 if (!Alert::askForText(branch_name, _("Branch name")) ||
1895 branch_name.empty())
1898 DispatchResult drtmp;
1899 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1900 if (drtmp.error()) {
1901 Alert::warning(_("Branch already exists"), drtmp.message());
1904 docstring const sep = buffer_.params().branchlist().separator();
1905 for (docstring const & branch : getVectorFromString(branch_name, sep))
1906 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch));
1910 case LFUN_KEYMAP_OFF:
1911 getIntl().keyMapOn(false);
1914 case LFUN_KEYMAP_PRIMARY:
1915 getIntl().keyMapPrim();
1918 case LFUN_KEYMAP_SECONDARY:
1919 getIntl().keyMapSec();
1922 case LFUN_KEYMAP_TOGGLE:
1923 getIntl().toggleKeyMap();
1926 case LFUN_DIALOG_SHOW_NEW_INSET: {
1927 string const name = cmd.getArg(0);
1928 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1929 if (decodeInsetParam(name, data, buffer_))
1930 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1932 lyxerr << "Inset type '" << name <<
1933 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1937 case LFUN_CITATION_INSERT: {
1938 if (argument.empty()) {
1939 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1942 // we can have one optional argument, delimited by '|'
1943 // citation-insert <key>|<text_before>
1944 // this should be enhanced to also support text_after
1945 // and citation style
1946 string arg = argument;
1948 if (contains(argument, "|")) {
1949 arg = token(argument, '|', 0);
1950 opt1 = token(argument, '|', 1);
1953 // if our cursor is directly in front of or behind a citation inset,
1954 // we will instead add the new key to it.
1955 Inset * inset = cur.nextInset();
1956 if (!inset || inset->lyxCode() != CITE_CODE)
1957 inset = cur.prevInset();
1958 if (inset && inset->lyxCode() == CITE_CODE) {
1959 InsetCitation * icite = static_cast<InsetCitation *>(inset);
1960 if (icite->addKey(arg)) {
1961 dr.forceBufferUpdate();
1962 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
1964 LYXERR0("Discarding optional argument to citation-insert.");
1969 InsetCommandParams icp(CITE_CODE);
1970 icp["key"] = from_utf8(arg);
1972 icp["before"] = from_utf8(opt1);
1973 string icstr = InsetCommand::params2string(icp);
1974 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1979 case LFUN_INSET_APPLY: {
1980 string const name = cmd.getArg(0);
1981 Inset * inset = editedInset(name);
1983 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1987 // put cursor in front of inset.
1988 if (!setCursorFromInset(inset)) {
1989 LASSERT(false, break);
1992 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1993 inset->dispatch(cur, fr);
1994 dr.screenUpdate(cur.result().screenUpdate());
1995 if (cur.result().needBufferUpdate())
1996 dr.forceBufferUpdate();
2001 // The change of language of buffer belongs to the Buffer class.
2002 // We have to do it here because we need a cursor for Undo.
2003 // When Undo::recordUndoBufferParams() is implemented someday
2004 // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
2005 case LFUN_BUFFER_LANGUAGE: {
2006 Language const * oldL = buffer_.params().language;
2007 Language const * newL = languages.getLanguage(argument);
2008 if (!newL || oldL == newL)
2010 if (oldL->rightToLeft() == newL->rightToLeft()) {
2011 cur.recordUndoFullBuffer();
2012 buffer_.changeLanguage(oldL, newL);
2013 cur.setCurrentFont();
2014 dr.forceBufferUpdate();
2019 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2020 case LFUN_FILE_INSERT_PLAINTEXT: {
2021 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
2022 string const fname = to_utf8(cmd.argument());
2023 if (!FileName::isAbsolute(fname))
2024 dr.setMessage(_("Absolute filename expected."));
2026 insertPlaintextFile(FileName(fname), as_paragraph);
2031 // OK, so try the Buffer itself...
2032 buffer_.dispatch(cmd, dr);
2033 dispatched = dr.dispatched();
2037 buffer_.undo().endUndoGroup();
2038 dr.dispatched(dispatched);
2040 // NOTE: The code below is copied from Cursor::dispatch. If you
2041 // need to modify this, please update the other one too.
2043 // notify insets we just entered/left
2044 if (cursor() != old) {
2045 old.beginUndoGroup();
2047 bool badcursor = notifyCursorLeavesOrEnters(old, cursor());
2049 cursor().fixIfBroken();
2050 resetInlineCompletionPos();
2057 docstring const BufferView::requestSelection()
2059 Cursor & cur = d->cursor_;
2061 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2062 if (!cur.selection()) {
2063 d->xsel_cache_.set = false;
2067 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2068 if (!d->xsel_cache_.set ||
2069 cur.top() != d->xsel_cache_.cursor ||
2070 cur.realAnchor().top() != d->xsel_cache_.anchor)
2072 d->xsel_cache_.cursor = cur.top();
2073 d->xsel_cache_.anchor = cur.realAnchor().top();
2074 d->xsel_cache_.set = cur.selection();
2075 return cur.selectionAsString(false);
2081 void BufferView::clearSelection()
2083 d->cursor_.clearSelection();
2084 // Clear the selection buffer. Otherwise a subsequent
2085 // middle-mouse-button paste would use the selection buffer,
2086 // not the more current external selection.
2087 cap::clearSelection();
2088 d->xsel_cache_.set = false;
2089 // The buffer did not really change, but this causes the
2090 // redraw we need because we cleared the selection above.
2091 buffer_.changed(false);
2095 void BufferView::resize(int width, int height)
2097 // Update from work area
2101 // Clear the paragraph height cache.
2102 d->par_height_.clear();
2103 // Redo the metrics.
2108 Inset const * BufferView::getCoveringInset(Text const & text,
2111 TextMetrics & tm = d->text_metrics_[&text];
2112 Inset * inset = tm.checkInsetHit(x, y);
2116 if (!inset->descendable(*this))
2117 // No need to go further down if the inset is not
2121 size_t cell_number = inset->nargs();
2122 // Check all the inner cell.
2123 for (size_t i = 0; i != cell_number; ++i) {
2124 Text const * inner_text = inset->getText(i);
2127 Inset const * inset_deeper =
2128 getCoveringInset(*inner_text, x, y);
2130 return inset_deeper;
2138 void BufferView::updateHoveredInset() const
2140 // Get inset under mouse, if there is one.
2141 int const x = d->mouse_position_cache_.x_;
2142 int const y = d->mouse_position_cache_.y_;
2143 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2145 d->clickable_inset_ = covering_inset && covering_inset->clickable(*this, x, y);
2147 if (covering_inset == d->last_inset_)
2148 // Same inset, no need to do anything...
2151 bool need_redraw = false;
2152 if (d->last_inset_) {
2153 // Remove the hint on the last hovered inset (if any).
2154 need_redraw |= d->last_inset_->setMouseHover(this, false);
2158 if (covering_inset && covering_inset->setMouseHover(this, true)) {
2160 // Only the insets that accept the hover state, do
2161 // clear the last_inset_, so only set the last_inset_
2162 // member if the hovered setting is accepted.
2163 d->last_inset_ = covering_inset;
2167 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2168 << d->mouse_position_cache_.x_ << ", "
2169 << d->mouse_position_cache_.y_ << ")");
2171 d->update_strategy_ = DecorationUpdate;
2173 // This event (moving without mouse click) is not passed further.
2174 // This should be changed if it is further utilized.
2175 buffer_.changed(false);
2180 void BufferView::clearLastInset(Inset * inset) const
2182 if (d->last_inset_ != inset) {
2183 LYXERR0("Wrong last_inset!");
2190 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2192 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2194 // This is only called for mouse related events including
2195 // LFUN_FILE_OPEN generated by drag-and-drop.
2196 FuncRequest cmd = cmd0;
2198 Cursor old = cursor();
2200 cur.push(buffer_.inset());
2201 cur.selection(d->cursor_.selection());
2203 // Either the inset under the cursor or the
2204 // surrounding Text will handle this event.
2206 // make sure we stay within the screen...
2207 cmd.set_y(min(max(cmd.y(), -1), height_));
2209 d->mouse_position_cache_.x_ = cmd.x();
2210 d->mouse_position_cache_.y_ = cmd.y();
2212 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2213 updateHoveredInset();
2217 // Build temporary cursor.
2218 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2220 // If inset is not editable, cur.pos() might point behind the
2221 // inset (depending on cmd.x(), cmd.y()). This is needed for
2222 // editing to fix bug 9628, but e.g. the context menu needs a
2223 // cursor in front of the inset.
2224 if ((inset->hasSettings() || !inset->contextMenuName().empty()
2225 || inset->lyxCode() == SEPARATOR_CODE) &&
2226 cur.nextInset() != inset && cur.prevInset() == inset)
2228 } else if (cur.inTexted() && cur.pos()
2229 && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
2230 // Always place cursor in front of a separator inset.
2234 // Put anchor at the same position.
2237 cur.beginUndoGroup();
2239 // Try to dispatch to an non-editable inset near this position
2240 // via the temp cursor. If the inset wishes to change the real
2241 // cursor it has to do so explicitly by using
2242 // cur.bv().cursor() = cur; (or similar)
2244 inset->dispatch(cur, cmd);
2246 // Now dispatch to the temporary cursor. If the real cursor should
2247 // be modified, the inset's dispatch has to do so explicitly.
2248 if (!inset || !cur.result().dispatched())
2251 // Notify left insets
2253 bool badcursor = old.fixIfBroken() | cur.fixIfBroken();
2254 badcursor |= notifyCursorLeavesOrEnters(old, cur);
2256 cursor().fixIfBroken();
2261 // Do we have a selection?
2262 theSelection().haveSelection(cursor().selection());
2264 if (cur.needBufferUpdate()) {
2265 cur.clearBufferUpdate();
2266 buffer().updateBuffer();
2269 // If the command has been dispatched,
2270 if (cur.result().dispatched() || cur.result().screenUpdate())
2271 processUpdateFlags(cur.result().screenUpdate());
2275 int BufferView::minVisiblePart()
2277 return 2 * defaultRowHeight();
2281 int BufferView::scroll(int y)
2284 return scrollDown(y);
2286 return scrollUp(-y);
2291 int BufferView::scrollDown(int offset)
2293 Text * text = &buffer_.text();
2294 TextMetrics & tm = d->text_metrics_[text];
2295 int const ymax = height_ + offset;
2297 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2298 int bottom_pos = last.second->position() + last.second->descent();
2299 if (lyxrc.scroll_below_document)
2300 bottom_pos += height_ - minVisiblePart();
2301 if (last.first + 1 == int(text->paragraphs().size())) {
2302 if (bottom_pos <= height_)
2304 offset = min(offset, bottom_pos - height_);
2307 if (bottom_pos > ymax)
2309 tm.newParMetricsDown();
2311 d->anchor_ypos_ -= offset;
2316 int BufferView::scrollUp(int offset)
2318 Text * text = &buffer_.text();
2319 TextMetrics & tm = d->text_metrics_[text];
2320 int ymin = - offset;
2322 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2323 int top_pos = first.second->position() - first.second->ascent();
2324 if (first.first == 0) {
2327 offset = min(offset, - top_pos);
2332 tm.newParMetricsUp();
2334 d->anchor_ypos_ += offset;
2339 bool BufferView::setCursorFromRow(int row)
2341 TexRow::TextEntry start, end;
2342 tie(start,end) = buffer_.texrow().getEntriesFromRow(row);
2343 LYXERR(Debug::LATEX,
2344 "setCursorFromRow: for row " << row << ", TexRow has found "
2345 "start (id=" << start.id << ",pos=" << start.pos << "), "
2346 "end (id=" << end.id << ",pos=" << end.pos << ")");
2347 return setCursorFromEntries(start, end);
2351 bool BufferView::setCursorFromEntries(TexRow::TextEntry start,
2352 TexRow::TextEntry end)
2354 DocIterator dit_start, dit_end;
2355 tie(dit_start,dit_end) =
2356 TexRow::getDocIteratorsFromEntries(start, end, buffer_);
2359 // Setting selection start
2360 d->cursor_.clearSelection();
2361 setCursor(dit_start);
2362 // Setting selection end
2364 d->cursor_.resetAnchor();
2365 setCursorSelectionTo(dit_end);
2371 bool BufferView::setCursorFromInset(Inset const * inset)
2373 // are we already there?
2374 if (cursor().nextInset() == inset)
2377 // Inset is not at cursor position. Find it in the document.
2380 while (cur && cur.nextInset() != inset)
2391 void BufferView::gotoLabel(docstring const & label)
2393 for (Buffer const * buf : buffer().allRelatives()) {
2395 for (TocItem const & item : *buf->tocBackend().toc("label")) {
2396 if (label == item.str()) {
2397 lyx::dispatch(item.action());
2405 TextMetrics const & BufferView::textMetrics(Text const * t) const
2407 return const_cast<BufferView *>(this)->textMetrics(t);
2411 TextMetrics & BufferView::textMetrics(Text const * t)
2414 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2415 if (tmc_it == d->text_metrics_.end()) {
2416 tmc_it = d->text_metrics_.insert(
2417 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2419 return tmc_it->second;
2423 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2426 return textMetrics(t).parMetrics(pit);
2430 int BufferView::workHeight() const
2436 void BufferView::setCursor(DocIterator const & dit)
2439 size_t const n = dit.depth();
2440 for (size_t i = 0; i < n; ++i)
2441 dit[i].inset().edit(d->cursor_, true);
2443 d->cursor_.setCursor(dit);
2444 d->cursor_.selection(false);
2445 d->cursor_.setCurrentFont();
2447 // It seems on general grounds as if this is probably needed, but
2448 // it is not yet clear.
2449 // See bug #7394 and r38388.
2450 // d->cursor.resetAnchor();
2454 void BufferView::setCursorSelectionTo(DocIterator const & dit)
2456 size_t const n = dit.depth();
2457 for (size_t i = 0; i < n; ++i)
2458 dit[i].inset().edit(d->cursor_, true);
2460 d->cursor_.selection(true);
2461 d->cursor_.setCursorSelectionTo(dit);
2462 d->cursor_.setCurrentFont();
2466 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2468 // Would be wrong to delete anything if we have a selection.
2469 if (cur.selection())
2472 bool need_anchor_change = false;
2473 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2474 need_anchor_change);
2476 if (need_anchor_change)
2484 // we would rather not do this here, but it needs to be done before
2485 // the changed() signal is sent.
2486 buffer_.updateBuffer();
2488 buffer_.changed(true);
2493 bool BufferView::mouseSetCursor(Cursor & cur, bool const select)
2495 LASSERT(&cur.bv() == this, return false);
2498 // this event will clear selection so we save selection for
2499 // persistent selection
2500 cap::saveSelection(cursor());
2502 d->cursor_.macroModeClose();
2503 // If a macro has been finalized, the cursor might have been broken
2506 // Has the cursor just left the inset?
2507 bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2509 d->cursor_.fixIfBroken();
2511 // do the dEPM magic if needed
2512 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2513 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2514 // the leftinset bool would not be necessary (badcursor instead).
2515 bool update = leftinset;
2518 d->cursor_.setSelection();
2519 d->cursor_.setCursorSelectionTo(cur);
2521 if (d->cursor_.inTexted())
2522 update |= checkDepm(cur, d->cursor_);
2523 d->cursor_.resetAnchor();
2524 d->cursor_.setCursor(cur);
2525 d->cursor_.clearSelection();
2527 d->cursor_.boundary(cur.boundary());
2528 d->cursor_.finishUndo();
2529 d->cursor_.setCurrentFont();
2531 cur.forceBufferUpdate();
2536 void BufferView::putSelectionAt(DocIterator const & cur,
2537 int length, bool backwards)
2539 d->cursor_.clearSelection();
2545 d->cursor_.pos() += length;
2546 d->cursor_.setSelection(d->cursor_, -length);
2548 d->cursor_.setSelection(d->cursor_, length);
2553 bool BufferView::selectIfEmpty(DocIterator & cur)
2555 if ((cur.inTexted() && !cur.paragraph().empty())
2556 || (cur.inMathed() && !cur.cell().empty()))
2559 pit_type const beg_pit = cur.pit();
2561 // The paragraph associated to this item isn't
2562 // the first one, so it can be selected
2565 // We have to resort to select the space between the
2566 // end of this item and the begin of the next one
2570 // If it is the only item in the document,
2571 // nothing can be selected
2574 pit_type const end_pit = cur.pit();
2575 pos_type const end_pos = cur.pos();
2576 d->cursor_.clearSelection();
2578 d->cursor_.setCursor(cur);
2579 d->cursor_.pit() = beg_pit;
2580 d->cursor_.pos() = 0;
2581 d->cursor_.selection(false);
2582 d->cursor_.resetAnchor();
2583 d->cursor_.pit() = end_pit;
2584 d->cursor_.pos() = end_pos;
2585 d->cursor_.setSelection();
2590 Cursor & BufferView::cursor()
2596 Cursor const & BufferView::cursor() const
2602 bool BufferView::singleParUpdate()
2604 Text & buftext = buffer_.text();
2605 pit_type const bottom_pit = d->cursor_.bottom().pit();
2606 TextMetrics & tm = textMetrics(&buftext);
2607 int old_height = tm.parMetrics(bottom_pit).height();
2609 // make sure inline completion pointer is ok
2610 if (d->inlineCompletionPos_.fixIfBroken())
2611 d->inlineCompletionPos_ = DocIterator();
2613 // In Single Paragraph mode, rebreak only
2614 // the (main text, not inset!) paragraph containing the cursor.
2615 // (if this paragraph contains insets etc., rebreaking will
2616 // recursively descend)
2617 tm.redoParagraph(bottom_pit);
2618 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2619 if (pm.height() != old_height)
2620 // Paragraph height has changed so we cannot proceed to
2621 // the singlePar optimisation.
2624 tm.updatePosCache(bottom_pit);
2626 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2627 << " y2: " << pm.position() + pm.descent()
2628 << " pit: " << bottom_pit
2629 << " singlepar: 1");
2634 void BufferView::updateMetrics()
2636 updateMetrics(d->update_flags_);
2637 d->update_strategy_ = FullScreenUpdate;
2641 void BufferView::updateMetrics(Update::flags & update_flags)
2643 if (height_ == 0 || width_ == 0)
2646 Text & buftext = buffer_.text();
2647 pit_type const npit = int(buftext.paragraphs().size());
2649 // Clear out the position cache in case of full screen redraw,
2650 d->coord_cache_.clear();
2652 // Clear out paragraph metrics to avoid having invalid metrics
2653 // in the cache from paragraphs not relayouted below
2654 // The complete text metrics will be redone.
2655 d->text_metrics_.clear();
2657 TextMetrics & tm = textMetrics(&buftext);
2659 // make sure inline completion pointer is ok
2660 if (d->inlineCompletionPos_.fixIfBroken())
2661 d->inlineCompletionPos_ = DocIterator();
2663 if (d->anchor_pit_ >= npit)
2664 // The anchor pit must have been deleted...
2665 d->anchor_pit_ = npit - 1;
2667 // Rebreak anchor paragraph.
2668 tm.redoParagraph(d->anchor_pit_);
2669 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2672 if (d->anchor_pit_ == 0) {
2673 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2675 // Complete buffer visible? Then it's easy.
2676 if (scrollRange == 0)
2677 d->anchor_ypos_ = anchor_pm.ascent();
2679 // avoid empty space above the first row
2680 d->anchor_ypos_ = min(d->anchor_ypos_, anchor_pm.ascent());
2683 anchor_pm.setPosition(d->anchor_ypos_);
2684 tm.updatePosCache(d->anchor_pit_);
2686 LYXERR(Debug::PAINTING, "metrics: "
2687 << " anchor pit = " << d->anchor_pit_
2688 << " anchor ypos = " << d->anchor_ypos_);
2690 // Redo paragraphs above anchor if necessary.
2691 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2692 // We are now just above the anchor paragraph.
2693 pit_type pit1 = d->anchor_pit_ - 1;
2694 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2695 tm.redoParagraph(pit1);
2696 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2698 // Save the paragraph position in the cache.
2700 tm.updatePosCache(pit1);
2704 // Redo paragraphs below the anchor if necessary.
2705 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2706 // We are now just below the anchor paragraph.
2707 pit_type pit2 = d->anchor_pit_ + 1;
2708 for (; pit2 < npit && y2 <= height_; ++pit2) {
2709 tm.redoParagraph(pit2);
2710 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2712 // Save the paragraph position in the cache.
2714 tm.updatePosCache(pit2);
2718 LYXERR(Debug::PAINTING, "Metrics: "
2719 << " anchor pit = " << d->anchor_pit_
2720 << " anchor ypos = " << d->anchor_ypos_
2723 << " pit1 = " << pit1
2724 << " pit2 = " << pit2);
2726 // metrics is done, full drawing is necessary now
2727 update_flags = (update_flags & ~Update::Force) | Update::ForceDraw;
2729 // Now update the positions of insets in the cache.
2732 if (lyxerr.debugging(Debug::WORKAREA)) {
2733 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2734 d->coord_cache_.dump();
2739 void BufferView::updatePosCache()
2741 // this is the "nodraw" drawing stage: only set the positions of the
2742 // insets in metrics cache.
2743 frontend::NullPainter np;
2748 void BufferView::insertLyXFile(FileName const & fname)
2750 LASSERT(d->cursor_.inTexted(), return);
2752 // Get absolute path of file and add ".lyx"
2753 // to the filename if necessary
2754 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2756 docstring const disp_fn = makeDisplayPath(filename.absFileName());
2757 // emit message signal.
2758 message(bformat(_("Inserting document %1$s..."), disp_fn));
2761 Buffer buf(filename.absFileName(), false);
2762 if (buf.loadLyXFile() == Buffer::ReadSuccess) {
2763 ErrorList & el = buffer_.errorList("Parse");
2764 // Copy the inserted document error list into the current buffer one.
2765 el = buf.errorList("Parse");
2766 buffer_.undo().recordUndo(d->cursor_);
2767 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2768 buf.params().documentClassPtr(), el);
2769 res = _("Document %1$s inserted.");
2771 res = _("Could not insert document %1$s");
2774 buffer_.changed(true);
2775 // emit message signal.
2776 message(bformat(res, disp_fn));
2780 Point BufferView::coordOffset(DocIterator const & dit) const
2786 // Addup contribution of nested insets, from inside to outside,
2787 // keeping the outer paragraph for a special handling below
2788 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2789 CursorSlice const & sl = dit[i];
2793 // get relative position inside sl.inset()
2794 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2796 // Make relative position inside of the edited inset relative to sl.inset()
2800 // In case of an RTL inset, the edited inset will be positioned to the left
2803 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2804 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2809 // remember width for the case that sl.inset() is positioned in an RTL inset
2810 lastw = sl.inset().dimension(*this).wid;
2812 //lyxerr << "Cursor::getPos, i: "
2813 // << i << " x: " << xx << " y: " << y << endl;
2816 // Add contribution of initial rows of outermost paragraph
2817 CursorSlice const & sl = dit[0];
2818 TextMetrics const & tm = textMetrics(sl.text());
2819 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2821 LBUFERR(!pm.rows().empty());
2822 y -= pm.rows()[0].ascent();
2824 // FIXME: document this mess
2826 if (sl.pos() > 0 && dit.depth() == 1) {
2828 if (pos && dit.boundary())
2830 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2831 rend = pm.pos2row(pos);
2833 rend = pm.pos2row(sl.pos());
2835 size_t rend = pm.pos2row(sl.pos());
2837 for (size_t rit = 0; rit != rend; ++rit)
2838 y += pm.rows()[rit].height();
2839 y += pm.rows()[rend].ascent();
2841 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2843 // Make relative position from the nested inset now bufferview absolute.
2844 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2847 // In the RTL case place the nested inset at the left of the cursor in
2848 // the outer paragraph
2849 bool boundary_1 = dit.boundary() && 1 == dit.depth();
2850 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2858 Point BufferView::getPos(DocIterator const & dit) const
2860 if (!paragraphVisible(dit))
2861 return Point(-1, -1);
2863 CursorSlice const & bot = dit.bottom();
2864 TextMetrics const & tm = textMetrics(bot.text());
2866 // offset from outer paragraph
2867 Point p = coordOffset(dit);
2868 p.y_ += tm.parMetrics(bot.pit()).position();
2873 bool BufferView::paragraphVisible(DocIterator const & dit) const
2875 CursorSlice const & bot = dit.bottom();
2876 TextMetrics const & tm = textMetrics(bot.text());
2878 return tm.contains(bot.pit());
2882 void BufferView::caretPosAndHeight(Point & p, int & h) const
2884 Cursor const & cur = cursor();
2885 Font const font = cur.real_current_font;
2886 frontend::FontMetrics const & fm = theFontMetrics(font);
2887 int const asc = fm.maxAscent();
2888 int const des = fm.maxDescent();
2895 bool BufferView::cursorInView(Point const & p, int h) const
2897 Cursor const & cur = cursor();
2898 // does the cursor touch the screen ?
2899 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2905 int BufferView::horizScrollOffset() const
2907 return d->horiz_scroll_offset_;
2911 int BufferView::horizScrollOffset(Text const * text,
2912 pit_type pit, pos_type pos) const
2914 // Is this a row that is currently scrolled?
2915 if (!d->current_row_slice_.empty()
2916 && &text->inset() == d->current_row_slice_.inset().asInsetText()
2917 && pit == d->current_row_slice_.pit()
2918 && pos == d->current_row_slice_.pos())
2919 return d->horiz_scroll_offset_;
2924 bool BufferView::hadHorizScrollOffset(Text const * text,
2925 pit_type pit, pos_type pos) const
2927 return !d->last_row_slice_.empty()
2928 && &text->inset() == d->last_row_slice_.inset().asInsetText()
2929 && pit == d->last_row_slice_.pit()
2930 && pos == d->last_row_slice_.pos();
2934 void BufferView::setCurrentRowSlice(CursorSlice const & rowSlice)
2936 // nothing to do if the cursor was already on this row
2937 if (d->current_row_slice_ == rowSlice) {
2938 d->last_row_slice_ = CursorSlice();
2942 // if the (previous) current row was scrolled, we have to
2943 // remember it in order to repaint it next time.
2944 if (d->horiz_scroll_offset_ != 0)
2945 d->last_row_slice_ = d->current_row_slice_;
2947 d->last_row_slice_ = CursorSlice();
2949 // Since we changed row, the scroll offset is not valid anymore
2950 d->horiz_scroll_offset_ = 0;
2951 d->current_row_slice_ = rowSlice;
2957 bool sliceInRow(CursorSlice const & cs, Text const * text, Row const & row)
2959 /* The normal case is the last line. The previous line takes care
2960 * of empty rows (e.g. empty paragraphs). Cursor boundary issues
2961 * are taken care of when setting caret_slice_ in
2964 return !cs.empty() && cs.text() == text && cs.pit() == row.pit()
2965 && ((row.pos() == row.endpos() && row.pos() == cs.pos())
2966 || (row.pos() <= cs.pos() && cs.pos() < row.endpos()));
2972 bool BufferView::needRepaint(Text const * text, Row const & row) const
2974 return d->repaint_caret_row_ && sliceInRow(d->caret_slice_, text, row);
2978 void BufferView::checkCursorScrollOffset()
2980 CursorSlice rowSlice = d->cursor_.bottom();
2981 TextMetrics const & tm = textMetrics(rowSlice.text());
2983 // Stop if metrics have not been computed yet, since it means
2984 // that there is nothing to do.
2985 if (!tm.contains(rowSlice.pit()))
2987 ParagraphMetrics const & pm = tm.parMetrics(rowSlice.pit());
2988 Row const & row = pm.getRow(rowSlice.pos(),
2989 d->cursor_.boundary() && rowSlice == d->cursor_.top());
2990 rowSlice.pos() = row.pos();
2992 // Set the row on which the cursor lives.
2993 setCurrentRowSlice(rowSlice);
2995 // Current x position of the cursor in pixels
2996 int cur_x = getPos(d->cursor_).x_;
2998 // Horizontal scroll offset of the cursor row in pixels
2999 int offset = d->horiz_scroll_offset_;
3000 int const MARGIN = 2 * theFontMetrics(d->cursor_.real_current_font).em()
3002 if (row.right_x() <= workWidth() - row.right_margin) {
3003 // Row is narrower than the work area, no offset needed.
3006 if (cur_x - offset < MARGIN) {
3007 // cursor would be too far right
3008 offset = cur_x - MARGIN;
3009 } else if (cur_x - offset > workWidth() - MARGIN) {
3010 // cursor would be too far left
3011 offset = cur_x - workWidth() + MARGIN;
3013 // Correct the offset to make sure that we do not scroll too much
3016 if (row.right_x() - offset < workWidth() - row.right_margin)
3017 offset = row.right_x() - workWidth() + row.right_margin;
3020 //lyxerr << "cur_x=" << cur_x << ", offset=" << offset << ", row.wid=" << row.width() << ", margin=" << MARGIN << endl;
3022 if (offset != d->horiz_scroll_offset_)
3023 LYXERR(Debug::PAINTING, "Horiz. scroll offset changed from "
3024 << d->horiz_scroll_offset_ << " to " << offset);
3026 if (d->update_strategy_ == NoScreenUpdate
3027 && (offset != d->horiz_scroll_offset_
3028 || !d->last_row_slice_.empty())) {
3029 // FIXME: if one uses SingleParUpdate, then home/end
3030 // will not work on long rows. Why?
3031 d->update_strategy_ = FullScreenUpdate;
3034 d->horiz_scroll_offset_ = offset;
3038 void BufferView::draw(frontend::Painter & pain, bool paint_caret)
3040 if (height_ == 0 || width_ == 0)
3042 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t--- START NODRAW ---"
3043 : "\t\t*** START DRAWING ***"));
3044 Text & text = buffer_.text();
3045 TextMetrics const & tm = d->text_metrics_[&text];
3046 int const y = tm.first().second->position();
3047 PainterInfo pi(this, pain);
3049 /** A repaint of the previous caret row is needed if there is
3050 * caret painted on screen and either
3051 * 1/ a new caret has to be painted at a place different from
3053 * 2/ there is no need for a caret anymore.
3055 d->repaint_caret_row_ = !d->caret_slice_.empty() &&
3056 ((paint_caret && d->cursor_.top() != d->caret_slice_)
3059 // Check whether the row where the cursor lives needs to be scrolled.
3060 // Update the drawing strategy if needed.
3061 checkCursorScrollOffset();
3063 switch (d->update_strategy_) {
3065 case NoScreenUpdate:
3066 // no screen painting is actually needed. In nodraw stage
3067 // however, the different coordinates of insets and paragraphs
3068 // needs to be updated.
3069 LYXERR(Debug::PAINTING, "Strategy: NoScreenUpdate");
3070 pi.full_repaint = false;
3071 if (pain.isNull()) {
3072 pi.full_repaint = true;
3074 } else if (d->repaint_caret_row_) {
3075 pi.full_repaint = false;
3080 case SingleParUpdate:
3081 pi.full_repaint = false;
3082 LYXERR(Debug::PAINTING, "Strategy: SingleParUpdate");
3083 // In general, only the current row of the outermost paragraph
3084 // will be redrawn. Particular cases where selection spans
3085 // multiple paragraph are correctly detected in TextMetrics.
3089 case DecorationUpdate:
3090 // FIXME: We should also distinguish DecorationUpdate to avoid text
3091 // drawing if possible. This is not possible to do easily right now
3092 // because of the single backing pixmap.
3094 case FullScreenUpdate:
3096 LYXERR(Debug::PAINTING,
3097 ((d->update_strategy_ == FullScreenUpdate)
3098 ? "Strategy: FullScreenUpdate"
3099 : "Strategy: DecorationUpdate"));
3101 // The whole screen, including insets, will be refreshed.
3102 pi.full_repaint = true;
3104 // Clear background.
3105 pain.fillRectangle(0, 0, width_, height_,
3106 pi.backgroundColor(&buffer_.inset()));
3111 // and possibly grey out below
3112 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3113 int const y2 = lastpm.second->position() + lastpm.second->descent();
3116 Color color = buffer().isInternal()
3117 ? Color_background : Color_bottomarea;
3118 pain.fillRectangle(0, y2, width_, height_ - y2, color);
3122 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t --- END NODRAW ---"
3123 : "\t\t *** END DRAWING ***"));
3125 // The scrollbar needs an update.
3128 // Normalize anchor for next time
3129 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
3130 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3131 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
3132 ParagraphMetrics const & pm = tm.parMetrics(pit);
3133 if (pm.position() + pm.descent() > 0) {
3134 if (d->anchor_pit_ != pit
3135 || d->anchor_ypos_ != pm.position())
3136 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
3137 << " anchor ypos = " << d->anchor_ypos_);
3138 d->anchor_pit_ = pit;
3139 d->anchor_ypos_ = pm.position();
3143 if (!pain.isNull()) {
3144 // reset the update flags, everything has been done
3145 d->update_flags_ = Update::None;
3148 // Remember what has just been done for the next draw() step
3150 d->caret_slice_ = d->cursor_.top();
3151 if (d->caret_slice_.pos() > 0
3152 && (d->cursor_.boundary()
3153 || d->caret_slice_.pos() == d->caret_slice_.lastpos()))
3154 --d->caret_slice_.pos();
3156 d->caret_slice_ = CursorSlice();
3160 void BufferView::message(docstring const & msg)
3163 d->gui_->message(msg);
3167 void BufferView::showDialog(string const & name)
3170 d->gui_->showDialog(name, string());
3174 void BufferView::showDialog(string const & name,
3175 string const & data, Inset * inset)
3178 d->gui_->showDialog(name, data, inset);
3182 void BufferView::updateDialog(string const & name, string const & data)
3185 d->gui_->updateDialog(name, data);
3189 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
3195 // FIXME: Move this out of BufferView again
3196 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
3198 if (!fname.isReadableFile()) {
3199 docstring const error = from_ascii(strerror(errno));
3200 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3201 docstring const text =
3202 bformat(_("Could not read the specified document\n"
3203 "%1$s\ndue to the error: %2$s"), file, error);
3204 Alert::error(_("Could not read file"), text);
3208 if (!fname.isReadableFile()) {
3209 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3210 docstring const text =
3211 bformat(_("%1$s\n is not readable."), file);
3212 Alert::error(_("Could not open file"), text);
3216 // FIXME UNICODE: We don't know the encoding of the file
3217 docstring file_content = fname.fileContents("UTF-8");
3218 if (file_content.empty()) {
3219 Alert::error(_("Reading not UTF-8 encoded file"),
3220 _("The file is not UTF-8 encoded.\n"
3221 "It will be read as local 8Bit-encoded.\n"
3222 "If this does not give the correct result\n"
3223 "then please change the encoding of the file\n"
3224 "to UTF-8 with a program other than LyX.\n"));
3225 file_content = fname.fileContents("local8bit");
3228 return normalize_c(file_content);
3232 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
3234 docstring const tmpstr = contentsOfPlaintextFile(f);
3239 Cursor & cur = cursor();
3240 cap::replaceSelection(cur);
3241 buffer_.undo().recordUndo(cur);
3243 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3245 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3247 buffer_.changed(true);
3251 docstring const & BufferView::inlineCompletion() const
3253 return d->inlineCompletion_;
3257 size_t const & BufferView::inlineCompletionUniqueChars() const
3259 return d->inlineCompletionUniqueChars_;
3263 DocIterator const & BufferView::inlineCompletionPos() const
3265 return d->inlineCompletionPos_;
3269 void BufferView::resetInlineCompletionPos()
3271 d->inlineCompletionPos_ = DocIterator();
3275 bool samePar(DocIterator const & a, DocIterator const & b)
3277 if (a.empty() && b.empty())
3279 if (a.empty() || b.empty())
3281 if (a.depth() != b.depth())
3283 return &a.innerParagraph() == &b.innerParagraph();
3287 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3288 docstring const & completion, size_t uniqueChars)
3290 uniqueChars = min(completion.size(), uniqueChars);
3291 bool changed = d->inlineCompletion_ != completion
3292 || d->inlineCompletionUniqueChars_ != uniqueChars;
3293 bool singlePar = true;
3294 d->inlineCompletion_ = completion;
3295 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3297 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3300 DocIterator const & old = d->inlineCompletionPos_;
3302 //lyxerr << "inlineCompletionPos changed" << std::endl;
3303 // old or pos are in another paragraph?
3304 if ((!samePar(cur, pos) && !pos.empty())
3305 || (!samePar(cur, old) && !old.empty())) {
3307 //lyxerr << "different paragraph" << std::endl;
3309 d->inlineCompletionPos_ = pos;
3314 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3315 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3317 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3322 bool BufferView::clickableInset() const
3324 return d->clickable_inset_;