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"
42 #include "MetricsInfo.h"
43 #include "Paragraph.h"
44 #include "ParagraphParameters.h"
45 #include "ParIterator.h"
48 #include "TextClass.h"
49 #include "TextMetrics.h"
51 #include "TocBackend.h"
53 #include "WordLangTuple.h"
55 #include "insets/InsetBibtex.h"
56 #include "insets/InsetCommand.h" // ChangeRefs
57 #include "insets/InsetExternal.h"
58 #include "insets/InsetGraphics.h"
59 #include "insets/InsetRef.h"
60 #include "insets/InsetText.h"
61 #include "insets/InsetNote.h"
63 #include "frontends/alert.h"
64 #include "frontends/Application.h"
65 #include "frontends/Delegates.h"
66 #include "frontends/FontMetrics.h"
67 #include "frontends/Painter.h"
68 #include "frontends/Selection.h"
70 #include "graphics/Previews.h"
72 #include "support/convert.h"
73 #include "support/debug.h"
74 #include "support/ExceptionMessage.h"
75 #include "support/filetools.h"
76 #include "support/gettext.h"
77 #include "support/lstrings.h"
78 #include "support/Package.h"
79 #include "support/types.h"
88 using namespace lyx::support;
92 namespace Alert = frontend::Alert;
96 /// Return an inset of this class if it exists at the current cursor position
98 T * getInsetByCode(Cursor const & cur, InsetCode code)
100 DocIterator it = cur;
101 Inset * inset = it.nextInset();
102 if (inset && inset->lyxCode() == code)
103 return static_cast<T*>(inset);
108 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
111 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
112 docstring const & contents)
114 DocIterator tmpdit = dit;
117 Inset const * inset = tmpdit.nextInset();
119 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
120 && (contents.empty() ||
121 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
125 tmpdit.forwardInset();
132 /// Looks for next inset with one of the given codes.
133 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
137 DocIterator tmpdit = dit;
138 tmpdit.forwardInset();
143 Inset const * inset = tmpdit.nextInset();
145 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
146 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
150 if (!findNextInset(tmpdit, codes, contents)) {
151 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
152 Inset * inset = &tmpdit.bottom().inset();
153 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
154 if (!findNextInset(tmpdit, codes, contents))
166 /// Looks for next inset with the given code
167 void findInset(DocIterator & dit, InsetCode code, bool same_content)
169 findInset(dit, vector<InsetCode>(1, code), same_content);
173 /// Moves cursor to the next inset with one of the given codes.
174 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
177 Cursor tmpcur = bv->cursor();
178 if (!findInset(tmpcur, codes, same_content)) {
179 bv->cursor().message(_("No more insets"));
183 tmpcur.clearSelection();
184 bv->setCursor(tmpcur);
189 /// Moves cursor to the next inset with given code.
190 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
192 gotoInset(bv, vector<InsetCode>(1, code), same_content);
196 /// A map from a Text to the associated text metrics
197 typedef map<Text const *, TextMetrics> TextMetricsCache;
199 enum ScreenUpdateStrategy {
209 /////////////////////////////////////////////////////////////////////
213 /////////////////////////////////////////////////////////////////////
215 struct BufferView::Private
217 Private(BufferView & bv): wh_(0), cursor_(bv),
218 anchor_pit_(0), anchor_ypos_(0),
219 inlineCompletionUniqueChars_(0),
220 last_inset_(0), bookmark_edit_position_(0), gui_(0)
224 ScrollbarParameters scrollbarParameters_;
226 ScreenUpdateStrategy update_strategy_;
228 CoordCache coord_cache_;
230 /// Estimated average par height for scrollbar.
232 /// this is used to handle XSelection events in the right manner.
241 pit_type anchor_pit_;
245 vector<int> par_height_;
248 DocIterator inlineCompletionPos_;
250 docstring inlineCompletion_;
252 size_t inlineCompletionUniqueChars_;
254 /// keyboard mapping object.
257 /// last visited inset.
258 /** kept to send setMouseHover(false).
259 * Not owned, so don't delete.
263 // cache for id of the paragraph which was edited the last time
264 int bookmark_edit_position_;
266 mutable TextMetricsCache text_metrics_;
269 /** Not owned, so don't delete.
271 frontend::GuiBufferViewDelegate * gui_;
273 /// Cache for Find Next
274 FuncRequest search_request_cache_;
278 BufferView::BufferView(Buffer & buf)
279 : width_(0), height_(0), full_screen_(false), buffer_(buf),
280 d(new Private(*this))
282 d->xsel_cache_.set = false;
283 d->intl_.initKeyMapper(lyxrc.use_kbmap);
285 d->cursor_.setBuffer(&buf);
286 d->cursor_.push(buffer_.inset());
287 d->cursor_.resetAnchor();
288 d->cursor_.setCurrentFont();
290 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
291 thePreviews().generateBufferPreviews(buffer_);
295 BufferView::~BufferView()
297 // current buffer is going to be switched-off, save cursor pos
298 // Ideally, the whole cursor stack should be saved, but session
299 // currently can only handle bottom (whole document) level pit and pos.
300 // That is to say, if a cursor is in a nested inset, it will be
301 // restore to the left of the top level inset.
302 LastFilePosSection::FilePos fp;
303 fp.pit = d->cursor_.bottom().pit();
304 fp.pos = d->cursor_.bottom().pos();
305 theSession().lastFilePos().save(buffer_.fileName(), fp);
311 int BufferView::rightMargin() const
313 // The additional test for the case the outliner is opened.
315 !lyxrc.full_screen_limit ||
316 width_ < lyxrc.full_screen_width + 20)
319 return (width_ - lyxrc.full_screen_width) / 2;
323 int BufferView::leftMargin() const
325 return rightMargin();
329 bool BufferView::isTopScreen() const
331 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
335 bool BufferView::isBottomScreen() const
337 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
341 Intl & BufferView::getIntl()
347 Intl const & BufferView::getIntl() const
353 CoordCache & BufferView::coordCache()
355 return d->coord_cache_;
359 CoordCache const & BufferView::coordCache() const
361 return d->coord_cache_;
365 Buffer & BufferView::buffer()
371 Buffer const & BufferView::buffer() const
377 bool BufferView::fitCursor()
379 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
380 frontend::FontMetrics const & fm =
381 theFontMetrics(d->cursor_.getFont().fontInfo());
382 int const asc = fm.maxAscent();
383 int const des = fm.maxDescent();
384 Point const p = getPos(d->cursor_, d->cursor_.boundary());
385 if (p.y_ - asc >= 0 && p.y_ + des < height_)
392 void BufferView::processUpdateFlags(Update::flags flags)
394 // last_inset_ points to the last visited inset. This pointer may become
395 // invalid because of keyboard editing. Since all such operations
396 // causes screen update(), I reset last_inset_ to avoid such a problem.
398 // This is close to a hot-path.
399 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
400 << "[fitcursor = " << (flags & Update::FitCursor)
401 << ", forceupdate = " << (flags & Update::Force)
402 << ", singlepar = " << (flags & Update::SinglePar)
403 << "] buffer: " << &buffer_);
405 buffer_.updateMacros();
407 // Now do the first drawing step if needed. This consists on updating
408 // the CoordCache in updateMetrics().
409 // The second drawing step is done in WorkArea::redraw() if needed.
411 // Case when no explicit update is requested.
413 // no need to redraw anything.
414 d->update_strategy_ = NoScreenUpdate;
418 if (flags == Update::Decoration) {
419 d->update_strategy_ = DecorationUpdate;
424 if (flags == Update::FitCursor
425 || flags == (Update::Decoration | Update::FitCursor)) {
426 // tell the frontend to update the screen if needed.
431 if (flags & Update::Decoration) {
432 d->update_strategy_ = DecorationUpdate;
436 // no screen update is needed.
437 d->update_strategy_ = NoScreenUpdate;
441 bool const full_metrics = flags & Update::Force || !singleParUpdate();
444 // We have to update the full screen metrics.
447 if (!(flags & Update::FitCursor)) {
448 // Nothing to do anymore. Trigger a redraw and return
453 // updateMetrics() does not update paragraph position
454 // This is done at draw() time. So we need a redraw!
458 // The cursor is off screen so ensure it is visible.
465 void BufferView::updateScrollbar()
467 if (height_ == 0 && width_ == 0)
470 // We prefer fixed size line scrolling.
471 d->scrollbarParameters_.single_step = defaultRowHeight();
472 // We prefer full screen page scrolling.
473 d->scrollbarParameters_.page_step = height_;
475 Text & t = buffer_.text();
476 TextMetrics & tm = d->text_metrics_[&t];
478 LYXERR(Debug::GUI, " Updating scrollbar: height: "
479 << t.paragraphs().size()
480 << " curr par: " << d->cursor_.bottom().pit()
481 << " default height " << defaultRowHeight());
483 size_t const parsize = t.paragraphs().size();
484 if (d->par_height_.size() != parsize) {
485 d->par_height_.clear();
486 // FIXME: We assume a default paragraph height of 2 rows. This
487 // should probably be pondered with the screen width.
488 d->par_height_.resize(parsize, defaultRowHeight() * 2);
491 // Look at paragraph heights on-screen
492 pair<pit_type, ParagraphMetrics const *> first = tm.first();
493 pair<pit_type, ParagraphMetrics const *> last = tm.last();
494 for (pit_type pit = first.first; pit <= last.first; ++pit) {
495 d->par_height_[pit] = tm.parMetrics(pit).height();
496 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
497 << d->par_height_[pit]);
500 int top_pos = first.second->position() - first.second->ascent();
501 int bottom_pos = last.second->position() + last.second->descent();
502 bool first_visible = first.first == 0 && top_pos >= 0;
503 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
504 if (first_visible && last_visible) {
505 d->scrollbarParameters_.min = 0;
506 d->scrollbarParameters_.max = 0;
510 d->scrollbarParameters_.min = top_pos;
511 for (size_t i = 0; i != size_t(first.first); ++i)
512 d->scrollbarParameters_.min -= d->par_height_[i];
513 d->scrollbarParameters_.max = bottom_pos;
514 for (size_t i = last.first + 1; i != parsize; ++i)
515 d->scrollbarParameters_.max += d->par_height_[i];
517 d->scrollbarParameters_.position = 0;
518 // The reference is the top position so we remove one page.
519 if (lyxrc.scroll_below_document)
520 d->scrollbarParameters_.max -= minVisiblePart();
522 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
526 ScrollbarParameters const & BufferView::scrollbarParameters() const
528 return d->scrollbarParameters_;
532 docstring BufferView::toolTip(int x, int y) const
534 // Get inset under mouse, if there is one.
535 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
537 // No inset, no tooltip...
539 return covering_inset->toolTip(*this, x, y);
543 docstring BufferView::contextMenu(int x, int y) const
545 //If there is a selection, return the containing inset menu
546 if (d->cursor_.selection())
547 return d->cursor_.inset().contextMenu(*this, x, y);
549 // Get inset under mouse, if there is one.
550 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
552 return covering_inset->contextMenu(*this, x, y);
554 return buffer_.inset().contextMenu(*this, x, y);
558 void BufferView::scrollDocView(int value)
560 int const offset = value - d->scrollbarParameters_.position;
562 // No scrolling at all? No need to redraw anything
566 // If the offset is less than 2 screen height, prefer to scroll instead.
567 if (abs(offset) <= 2 * height_) {
568 d->anchor_ypos_ -= offset;
574 // cut off at the top
575 if (value <= d->scrollbarParameters_.min) {
576 DocIterator dit = doc_iterator_begin(&buffer_);
578 LYXERR(Debug::SCROLLING, "scroll to top");
582 // cut off at the bottom
583 if (value >= d->scrollbarParameters_.max) {
584 DocIterator dit = doc_iterator_end(&buffer_);
587 LYXERR(Debug::SCROLLING, "scroll to bottom");
591 // find paragraph at target position
592 int par_pos = d->scrollbarParameters_.min;
594 for (; i != int(d->par_height_.size()); ++i) {
595 par_pos += d->par_height_[i];
596 if (par_pos >= value)
600 if (par_pos < value) {
601 // It seems we didn't find the correct pit so stay on the safe side and
603 LYXERR0("scrolling position not found!");
604 scrollDocView(d->scrollbarParameters_.max);
608 DocIterator dit = doc_iterator_begin(&buffer_);
610 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
615 // FIXME: this method is not working well.
616 void BufferView::setCursorFromScrollbar()
618 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
620 int const height = 2 * defaultRowHeight();
621 int const first = height;
622 int const last = height_ - height;
624 Cursor const & oldcur = d->cursor_;
626 switch (cursorStatus(oldcur)) {
634 int const y = getPos(oldcur, oldcur.boundary()).y_;
635 newy = min(last, max(y, first));
639 // We reset the cursor because cursorStatus() does not
640 // work when the cursor is within mathed.
642 cur.reset(buffer_.inset());
643 tm.setCursorFromCoordinates(cur, 0, newy);
645 // update the bufferview cursor and notify insets
646 // FIXME: Care about the d->cursor_ flags to redraw if needed
647 Cursor old = d->cursor_;
649 bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
651 d->cursor_.fixIfBroken();
655 Change const BufferView::getCurrentChange() const
657 if (!d->cursor_.selection())
658 return Change(Change::UNCHANGED);
660 DocIterator dit = d->cursor_.selectionBegin();
661 return dit.paragraph().lookupChange(dit.pos());
665 // this could be used elsewhere as well?
666 // FIXME: This does not work within mathed!
667 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
669 Point const p = getPos(dit, dit.boundary());
672 if (p.y_ > workHeight())
678 void BufferView::bookmarkEditPosition()
680 // Don't eat cpu time for each keystroke
681 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
684 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
688 void BufferView::saveBookmark(unsigned int idx)
690 // tentatively save bookmark, id and pos will be used to
691 // acturately locate a bookmark in a 'live' lyx session.
692 // pit and pos will be updated with bottom level pit/pos
694 theSession().bookmarks().save(
696 d->cursor_.bottom().pit(),
697 d->cursor_.bottom().pos(),
698 d->cursor_.paragraph().id(),
703 // emit message signal.
704 message(_("Save bookmark"));
708 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
709 int top_id, pos_type top_pos)
711 bool success = false;
714 d->cursor_.clearSelection();
716 // if a valid par_id is given, try it first
717 // This is the case for a 'live' bookmark when unique paragraph ID
718 // is used to track bookmarks.
720 dit = buffer_.getParFromID(top_id);
722 dit.pos() = min(dit.paragraph().size(), top_pos);
723 // Some slices of the iterator may not be
724 // reachable (e.g. closed collapsable inset)
725 // so the dociterator may need to be
726 // shortened. Otherwise, setCursor may crash
727 // lyx when the cursor can not be set to these
729 size_t const n = dit.depth();
730 for (size_t i = 0; i < n; ++i)
731 if (!dit[i].inset().editable()) {
739 // if top_id == 0, or searching through top_id failed
740 // This is the case for a 'restored' bookmark when only bottom
741 // (document level) pit was saved. Because of this, bookmark
742 // restoration is inaccurate. If a bookmark was within an inset,
743 // it will be restored to the left of the outmost inset that contains
745 if (bottom_pit < int(buffer_.paragraphs().size())) {
746 dit = doc_iterator_begin(&buffer_);
748 dit.pit() = bottom_pit;
749 dit.pos() = min(bottom_pos, dit.paragraph().size());
754 // Note: only bottom (document) level pit is set.
756 // set the current font.
757 d->cursor_.setCurrentFont();
758 // To center the screen on this new position we need the
759 // paragraph position which is computed at draw() time.
760 // So we need a redraw!
770 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
772 if (lyxrc.rtl_support) {
773 if (d->cursor_.real_current_font.isRightToLeft()) {
774 if (d->intl_.keymap == Intl::PRIMARY)
775 d->intl_.keyMapSec();
777 if (d->intl_.keymap == Intl::SECONDARY)
778 d->intl_.keyMapPrim();
782 d->intl_.getTransManager().translateAndInsert(c, t, cur);
786 int BufferView::workWidth() const
792 void BufferView::recenter()
794 showCursor(d->cursor_, true);
798 void BufferView::showCursor()
800 showCursor(d->cursor_, false);
804 void BufferView::showCursor(DocIterator const & dit, bool recenter)
806 if (scrollToCursor(dit, recenter))
811 void BufferView::scrollToCursor()
813 scrollToCursor(d->cursor_, false);
817 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
819 // We are not properly started yet, delay until resizing is
824 LYXERR(Debug::SCROLLING, "recentering!");
826 CursorSlice const & bot = dit.bottom();
827 TextMetrics & tm = d->text_metrics_[bot.text()];
829 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
830 int bot_pit = bot.pit();
831 if (bot_pit > max_pit) {
832 // FIXME: Why does this happen?
833 LYXERR0("bottom pit is greater that max pit: "
834 << bot_pit << " > " << max_pit);
838 if (bot_pit == tm.first().first - 1)
839 tm.newParMetricsUp();
840 else if (bot_pit == tm.last().first + 1)
841 tm.newParMetricsDown();
843 if (tm.contains(bot_pit)) {
844 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
845 LASSERT(!pm.rows().empty(), /**/);
846 // FIXME: smooth scrolling doesn't work in mathed.
847 CursorSlice const & cs = dit.innerTextSlice();
848 int offset = coordOffset(dit, dit.boundary()).y_;
849 int ypos = pm.position() + offset;
850 Dimension const & row_dim =
851 pm.getRow(cs.pos(), dit.boundary()).dimension();
854 scrolled = scroll(ypos - height_/2);
855 else if (ypos - row_dim.ascent() < 0)
856 scrolled = scrollUp(- ypos + row_dim.ascent());
857 else if (ypos + row_dim.descent() > height_)
858 scrolled = scrollDown(ypos - height_ + defaultRowHeight() );
860 // else, nothing to do, the cursor is already visible so we just return.
868 // fix inline completion position
869 if (d->inlineCompletionPos_.fixIfBroken())
870 d->inlineCompletionPos_ = DocIterator();
872 tm.redoParagraph(bot_pit);
873 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
874 int offset = coordOffset(dit, dit.boundary()).y_;
876 d->anchor_pit_ = bot_pit;
877 CursorSlice const & cs = dit.innerTextSlice();
878 Dimension const & row_dim =
879 pm.getRow(cs.pos(), dit.boundary()).dimension();
882 d->anchor_ypos_ = height_/2;
883 else if (d->anchor_pit_ == 0)
884 d->anchor_ypos_ = offset + pm.ascent();
885 else if (d->anchor_pit_ == max_pit)
886 d->anchor_ypos_ = height_ - offset - row_dim.descent();
887 else if (offset > height_)
888 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
890 d->anchor_ypos_ = defaultRowHeight() * 2;
897 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
899 Cursor & cur = d->cursor_;
901 switch (cmd.action) {
904 flag.setEnabled(buffer_.undo().hasUndoStack());
907 flag.setEnabled(buffer_.undo().hasRedoStack());
909 case LFUN_FILE_INSERT:
910 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
911 case LFUN_FILE_INSERT_PLAINTEXT:
912 case LFUN_BOOKMARK_SAVE:
913 // FIXME: Actually, these LFUNS should be moved to Text
914 flag.setEnabled(cur.inTexted());
917 case LFUN_FONT_STATE:
918 case LFUN_LABEL_INSERT:
919 case LFUN_INFO_INSERT:
920 case LFUN_INSET_EDIT:
921 case LFUN_PARAGRAPH_GOTO:
923 case LFUN_REFERENCE_NEXT:
925 case LFUN_WORD_FINDADV:
926 case LFUN_WORD_REPLACE:
929 case LFUN_MARK_TOGGLE:
930 case LFUN_SCREEN_RECENTER:
931 case LFUN_SCREEN_SHOW_CURSOR:
932 case LFUN_BIBTEX_DATABASE_ADD:
933 case LFUN_BIBTEX_DATABASE_DEL:
934 case LFUN_NOTES_MUTATE:
935 case LFUN_ALL_INSETS_TOGGLE:
936 case LFUN_STATISTICS:
937 case LFUN_BRANCH_ADD_INSERT:
938 flag.setEnabled(true);
941 // @todo Test if current WorkArea is the search WorkArea
942 case LFUN_REGEXP_MODE: {
943 bool const embedded_workarea = buffer().isUnnamed()
944 && buffer().fileName().extension() == "internal";
945 flag.setEnabled(embedded_workarea && !cur.inRegexped());
949 case LFUN_LABEL_COPY_AS_REF: {
950 // if there is an inset at cursor, see whether it
952 Inset * inset = cur.nextInset();
953 if (!inset || !inset->getStatus(cur, cmd, flag))
954 flag.setEnabled(false);
958 case LFUN_NEXT_INSET_MODIFY: {
959 // this is the real function we want to invoke
960 FuncRequest tmpcmd = cmd;
961 tmpcmd.action = LFUN_INSET_MODIFY;
962 // if there is an inset at cursor, see whether it
963 // handles the lfun, other start from scratch
964 Inset * inset = cur.nextInset();
965 if (!inset || !inset->getStatus(cur, tmpcmd, flag))
966 flag = lyx::getStatus(tmpcmd);
970 case LFUN_LABEL_GOTO: {
971 flag.setEnabled(!cmd.argument().empty()
972 || getInsetByCode<InsetRef>(cur, REF_CODE));
976 case LFUN_CHANGES_TRACK:
977 flag.setEnabled(true);
978 flag.setOnOff(buffer_.params().trackChanges);
981 case LFUN_CHANGES_OUTPUT:
982 flag.setEnabled(true);
983 flag.setOnOff(buffer_.params().outputChanges);
986 case LFUN_CHANGES_MERGE:
987 case LFUN_CHANGE_NEXT:
988 case LFUN_CHANGE_PREVIOUS:
989 case LFUN_ALL_CHANGES_ACCEPT:
990 case LFUN_ALL_CHANGES_REJECT:
991 // TODO: context-sensitive enabling of LFUNs
992 // In principle, these command should only be enabled if there
993 // is a change in the document. However, without proper
994 // optimizations, this will inevitably result in poor performance.
995 flag.setEnabled(true);
998 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
999 flag.setOnOff(buffer_.params().compressed);
1003 case LFUN_SCREEN_UP:
1004 case LFUN_SCREEN_DOWN:
1006 case LFUN_SCREEN_UP_SELECT:
1007 case LFUN_SCREEN_DOWN_SELECT:
1008 flag.setEnabled(true);
1011 case LFUN_LAYOUT_TABULAR:
1012 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1016 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1019 case LFUN_LAYOUT_PARAGRAPH:
1020 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1023 case LFUN_DIALOG_SHOW_NEW_INSET:
1024 // FIXME: this is wrong, but I do not understand the
1026 if (cur.inset().lyxCode() == CAPTION_CODE)
1027 return cur.inset().getStatus(cur, cmd, flag);
1028 // FIXME we should consider passthru paragraphs too.
1029 flag.setEnabled(!cur.inset().getLayout().isPassThru());
1033 flag.setEnabled(false);
1041 bool BufferView::dispatch(FuncRequest const & cmd)
1043 //lyxerr << [ cmd = " << cmd << "]" << endl;
1045 // Make sure that the cached BufferView is correct.
1046 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1047 << " arg[" << to_utf8(cmd.argument()) << ']'
1048 << " x[" << cmd.x << ']'
1049 << " y[" << cmd.y << ']'
1050 << " button[" << cmd.button() << ']');
1052 Cursor & cur = d->cursor_;
1054 switch (cmd.action) {
1057 cur.message(_("Undo"));
1058 cur.clearSelection();
1059 if (!cur.textUndo())
1060 cur.message(_("No further undo information"));
1062 processUpdateFlags(Update::Force | Update::FitCursor);
1066 cur.message(_("Redo"));
1067 cur.clearSelection();
1068 if (!cur.textRedo())
1069 cur.message(_("No further redo information"));
1071 processUpdateFlags(Update::Force | Update::FitCursor);
1074 case LFUN_FONT_STATE:
1075 cur.message(cur.currentState());
1078 case LFUN_BOOKMARK_SAVE:
1079 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1082 case LFUN_LABEL_GOTO: {
1083 docstring label = cmd.argument();
1084 if (label.empty()) {
1086 getInsetByCode<InsetRef>(cur, REF_CODE);
1088 label = inset->getParam("reference");
1089 // persistent=false: use temp_bookmark
1098 case LFUN_INSET_EDIT: {
1099 FuncRequest fr(cmd);
1100 // if there is an inset at cursor, see whether it
1102 Inset * inset = cur.nextInset();
1104 inset->dispatch(cur, fr);
1105 // if it did not work, try the underlying inset.
1106 if (!inset || !cur.result().dispatched())
1109 // FIXME I'm adding the last break to solve a crash,
1110 // but that is obviously not right.
1111 if (!cur.result().dispatched())
1112 // It did not work too; no action needed.
1117 case LFUN_PARAGRAPH_GOTO: {
1118 int const id = convert<int>(cmd.getArg(0));
1119 int const pos = convert<int>(cmd.getArg(1));
1121 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1122 b = theBufferList().next(b)) {
1124 DocIterator dit = b->getParFromID(id);
1126 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1130 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1131 << " found in buffer `"
1132 << b->absFileName() << "'.");
1134 if (b == &buffer_) {
1138 processUpdateFlags(Update::Force | Update::FitCursor);
1140 // Switch to other buffer view and resend cmd
1141 theLyXFunc().dispatch(FuncRequest(
1142 LFUN_BUFFER_SWITCH, b->absFileName()));
1143 theLyXFunc().dispatch(cmd);
1150 case LFUN_NOTE_NEXT:
1151 gotoInset(this, NOTE_CODE, false);
1154 case LFUN_REFERENCE_NEXT: {
1155 vector<InsetCode> tmp;
1156 tmp.push_back(LABEL_CODE);
1157 tmp.push_back(REF_CODE);
1158 gotoInset(this, tmp, true);
1162 case LFUN_CHANGES_TRACK:
1163 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1166 case LFUN_CHANGES_OUTPUT:
1167 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1168 if (buffer_.params().outputChanges) {
1169 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1170 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1171 LaTeXFeatures::isAvailable("xcolor");
1173 if (!dvipost && !xcolorulem) {
1174 Alert::warning(_("Changes not shown in LaTeX output"),
1175 _("Changes will not be highlighted in LaTeX output, "
1176 "because neither dvipost nor xcolor/ulem are installed.\n"
1177 "Please install these packages or redefine "
1178 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1179 } else if (!xcolorulem) {
1180 Alert::warning(_("Changes not shown in LaTeX output"),
1181 _("Changes will not be highlighted in LaTeX output "
1182 "when using pdflatex, because xcolor and ulem are not installed.\n"
1183 "Please install both packages or redefine "
1184 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1189 case LFUN_CHANGE_NEXT:
1190 findNextChange(this);
1191 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1192 processUpdateFlags(Update::Force | Update::FitCursor);
1195 case LFUN_CHANGE_PREVIOUS:
1196 findPreviousChange(this);
1197 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1198 processUpdateFlags(Update::Force | Update::FitCursor);
1201 case LFUN_CHANGES_MERGE:
1202 if (findNextChange(this) || findPreviousChange(this)) {
1203 processUpdateFlags(Update::Force | Update::FitCursor);
1204 showDialog("changes");
1208 case LFUN_ALL_CHANGES_ACCEPT:
1209 // select complete document
1210 cur.reset(buffer_.inset());
1211 cur.selHandle(true);
1212 buffer_.text().cursorBottom(cur);
1213 // accept everything in a single step to support atomic undo
1214 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1215 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1216 processUpdateFlags(Update::Force | Update::FitCursor);
1219 case LFUN_ALL_CHANGES_REJECT:
1220 // select complete document
1221 cur.reset(buffer_.inset());
1222 cur.selHandle(true);
1223 buffer_.text().cursorBottom(cur);
1224 // reject everything in a single step to support atomic undo
1225 // Note: reject does not work recursively; the user may have to repeat the operation
1226 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1227 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1228 processUpdateFlags(Update::Force | Update::FitCursor);
1231 case LFUN_WORD_FIND: {
1232 FuncRequest req = cmd;
1233 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1234 req = d->search_request_cache_;
1235 if (req.argument().empty()) {
1236 theLyXFunc().dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1239 if (find(this, req))
1242 message(_("String not found!"));
1243 d->search_request_cache_ = req;
1247 case LFUN_WORD_REPLACE: {
1248 bool has_deleted = false;
1249 if (cur.selection()) {
1250 DocIterator beg = cur.selectionBegin();
1251 DocIterator end = cur.selectionEnd();
1252 if (beg.pit() == end.pit()) {
1253 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1254 if (cur.paragraph().isDeleted(p))
1259 replace(this, cmd, has_deleted);
1263 case LFUN_WORD_FINDADV:
1268 cur.clearSelection();
1269 cur.message(from_utf8(N_("Mark off")));
1273 cur.clearSelection();
1275 cur.message(from_utf8(N_("Mark on")));
1278 case LFUN_MARK_TOGGLE:
1279 cur.setSelection(false);
1282 cur.message(from_utf8(N_("Mark removed")));
1285 cur.message(from_utf8(N_("Mark set")));
1290 case LFUN_SCREEN_SHOW_CURSOR:
1294 case LFUN_SCREEN_RECENTER:
1298 case LFUN_BIBTEX_DATABASE_ADD: {
1299 Cursor tmpcur = cur;
1300 findInset(tmpcur, BIBTEX_CODE, false);
1301 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1304 if (inset->addDatabase(cmd.argument()))
1305 buffer_.updateBibfilesCache();
1310 case LFUN_BIBTEX_DATABASE_DEL: {
1311 Cursor tmpcur = cur;
1312 findInset(tmpcur, BIBTEX_CODE, false);
1313 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1316 if (inset->delDatabase(cmd.argument()))
1317 buffer_.updateBibfilesCache();
1322 case LFUN_STATISTICS: {
1323 DocIterator from, to;
1324 if (cur.selection()) {
1325 from = cur.selectionBegin();
1326 to = cur.selectionEnd();
1328 from = doc_iterator_begin(&buffer_);
1329 to = doc_iterator_end(&buffer_);
1331 int const words = countWords(from, to);
1332 int const chars = countChars(from, to, false);
1333 int const chars_blanks = countChars(from, to, true);
1335 if (cur.selection())
1336 message = _("Statistics for the selection:");
1338 message = _("Statistics for the document:");
1341 message += bformat(_("%1$d words"), words);
1343 message += _("One word");
1345 if (chars_blanks != 1)
1346 message += bformat(_("%1$d characters (including blanks)"),
1349 message += _("One character (including blanks)");
1352 message += bformat(_("%1$d characters (excluding blanks)"),
1355 message += _("One character (excluding blanks)");
1357 Alert::information(_("Statistics"), message);
1361 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1362 // turn compression on/off
1363 buffer_.params().compressed = !buffer_.params().compressed;
1366 case LFUN_LABEL_COPY_AS_REF: {
1367 // if there is an inset at cursor, try to copy it
1368 Inset * inset = &cur.inset();
1369 if (!inset || !inset->asInsetMath())
1370 inset = cur.nextInset();
1372 FuncRequest tmpcmd = cmd;
1373 inset->dispatch(cur, tmpcmd);
1375 if (!cur.result().dispatched())
1376 // It did not work too; no action needed.
1378 cur.clearSelection();
1379 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1383 case LFUN_NEXT_INSET_MODIFY: {
1384 // create the the real function we want to invoke
1385 FuncRequest tmpcmd = cmd;
1386 tmpcmd.action = LFUN_INSET_MODIFY;
1387 // if there is an inset at cursor, see whether it
1389 Inset * inset = cur.nextInset();
1392 inset->dispatch(cur, tmpcmd);
1394 // if it did not work, try the underlying inset.
1395 if (!inset || !cur.result().dispatched()) {
1397 cur.dispatch(tmpcmd);
1400 if (!cur.result().dispatched())
1401 // It did not work too; no action needed.
1403 cur.clearSelection();
1404 processUpdateFlags(Update::Force | Update::FitCursor);
1408 case LFUN_SCREEN_UP:
1409 case LFUN_SCREEN_DOWN: {
1410 Point p = getPos(cur, cur.boundary());
1411 // This code has been commented out to enable to scroll down a
1412 // document, even if there are large insets in it (see bug #5465).
1413 /*if (p.y_ < 0 || p.y_ > height_) {
1414 // The cursor is off-screen so recenter before proceeding.
1416 p = getPos(cur, cur.boundary());
1418 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1419 ? -height_ : height_);
1420 if (cmd.action == LFUN_SCREEN_UP && scrolled > -height_)
1422 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1423 p = Point(width_, height_);
1425 bool const in_texted = cur.inTexted();
1426 cur.reset(buffer_.inset());
1429 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1430 true, cmd.action == LFUN_SCREEN_UP);
1431 //FIXME: what to do with cur.x_target()?
1432 bool update = in_texted && cur.bv().checkDepm(cur, old);
1435 processUpdateFlags(Update::Force | Update::FitCursor);
1443 case LFUN_SCREEN_UP_SELECT: {
1444 cur.selHandle(true);
1445 if (isTopScreen()) {
1446 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1450 int y = getPos(cur, cur.boundary()).y_;
1451 int const ymin = y - height_ + defaultRowHeight();
1452 while (y > ymin && cur.up())
1453 y = getPos(cur, cur.boundary()).y_;
1456 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1460 case LFUN_SCREEN_DOWN_SELECT: {
1461 cur.selHandle(true);
1462 if (isBottomScreen()) {
1463 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1467 int y = getPos(cur, cur.boundary()).y_;
1468 int const ymax = y + height_ - defaultRowHeight();
1469 while (y < ymax && cur.down())
1470 y = getPos(cur, cur.boundary()).y_;
1473 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1477 // This could be rewriten using some command like forall <insetname> <command>
1478 // once the insets refactoring is done.
1479 case LFUN_NOTES_MUTATE: {
1480 if (cmd.argument().empty())
1483 if (mutateNotes(cur, cmd.getArg(0), cmd.getArg(1))) {
1484 processUpdateFlags(Update::Force);
1489 case LFUN_ALL_INSETS_TOGGLE: {
1491 string const name = split(to_utf8(cmd.argument()), action, ' ');
1492 InsetCode const inset_code = insetCode(name);
1494 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1496 Inset & inset = cur.buffer()->inset();
1497 InsetIterator it = inset_iterator_begin(inset);
1498 InsetIterator const end = inset_iterator_end(inset);
1499 for (; it != end; ++it) {
1500 if (it->asInsetCollapsable()
1501 && (inset_code == NO_CODE
1502 || inset_code == it->lyxCode())) {
1503 Cursor tmpcur = cur;
1504 tmpcur.pushBackward(*it);
1505 it->dispatch(tmpcur, fr);
1508 processUpdateFlags(Update::Force | Update::FitCursor);
1512 case LFUN_BRANCH_ADD_INSERT: {
1513 docstring branch_name = from_utf8(cmd.getArg(0));
1514 if (branch_name.empty())
1515 if (!Alert::askForText(branch_name, _("Branch name")) ||
1516 branch_name.empty())
1519 DispatchResult drtmp;
1520 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1521 if (drtmp.error()) {
1522 Alert::warning(_("Branch already exists"), drtmp.message());
1525 BranchList & branch_list = buffer_.params().branchlist();
1526 Branch const * branch = branch_list.find(branch_name);
1527 string const x11hexname = X11hexname(branch->color());
1528 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1529 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1530 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1543 docstring const BufferView::requestSelection()
1545 Cursor & cur = d->cursor_;
1547 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1548 if (!cur.selection()) {
1549 d->xsel_cache_.set = false;
1553 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1554 if (!d->xsel_cache_.set ||
1555 cur.top() != d->xsel_cache_.cursor ||
1556 cur.anchor_.top() != d->xsel_cache_.anchor)
1558 d->xsel_cache_.cursor = cur.top();
1559 d->xsel_cache_.anchor = cur.anchor_.top();
1560 d->xsel_cache_.set = cur.selection();
1561 return cur.selectionAsString(false);
1567 void BufferView::clearSelection()
1569 d->cursor_.clearSelection();
1570 // Clear the selection buffer. Otherwise a subsequent
1571 // middle-mouse-button paste would use the selection buffer,
1572 // not the more current external selection.
1573 cap::clearSelection();
1574 d->xsel_cache_.set = false;
1575 // The buffer did not really change, but this causes the
1576 // redraw we need because we cleared the selection above.
1581 void BufferView::resize(int width, int height)
1583 // Update from work area
1587 // Clear the paragraph height cache.
1588 d->par_height_.clear();
1589 // Redo the metrics.
1594 Inset const * BufferView::getCoveringInset(Text const & text,
1597 TextMetrics & tm = d->text_metrics_[&text];
1598 Inset * inset = tm.checkInsetHit(x, y);
1602 if (!inset->descendable())
1603 // No need to go further down if the inset is not
1607 size_t cell_number = inset->nargs();
1608 // Check all the inner cell.
1609 for (size_t i = 0; i != cell_number; ++i) {
1610 Text const * inner_text = inset->getText(i);
1613 Inset const * inset_deeper =
1614 getCoveringInset(*inner_text, x, y);
1616 return inset_deeper;
1624 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1626 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1628 // This is only called for mouse related events including
1629 // LFUN_FILE_OPEN generated by drag-and-drop.
1630 FuncRequest cmd = cmd0;
1632 Cursor old = cursor();
1634 cur.push(buffer_.inset());
1635 cur.setSelection(d->cursor_.selection());
1637 // Either the inset under the cursor or the
1638 // surrounding Text will handle this event.
1640 // make sure we stay within the screen...
1641 cmd.y = min(max(cmd.y, -1), height_);
1643 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1645 // Get inset under mouse, if there is one.
1646 Inset const * covering_inset =
1647 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1648 if (covering_inset == d->last_inset_)
1649 // Same inset, no need to do anything...
1652 bool need_redraw = false;
1653 // const_cast because of setMouseHover().
1654 Inset * inset = const_cast<Inset *>(covering_inset);
1656 // Remove the hint on the last hovered inset (if any).
1657 need_redraw |= d->last_inset_->setMouseHover(false);
1659 // Highlighted the newly hovered inset (if any).
1660 need_redraw |= inset->setMouseHover(true);
1661 d->last_inset_ = inset;
1665 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1666 << cmd.x << ", " << cmd.y << ")");
1668 d->update_strategy_ = DecorationUpdate;
1670 // This event (moving without mouse click) is not passed further.
1671 // This should be changed if it is further utilized.
1676 // Build temporary cursor.
1677 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1679 // Put anchor at the same position.
1682 cur.beginUndoGroup();
1684 // Try to dispatch to an non-editable inset near this position
1685 // via the temp cursor. If the inset wishes to change the real
1686 // cursor it has to do so explicitly by using
1687 // cur.bv().cursor() = cur; (or similar)
1689 inset->dispatch(cur, cmd);
1691 // Now dispatch to the temporary cursor. If the real cursor should
1692 // be modified, the inset's dispatch has to do so explicitly.
1693 if (!inset || !cur.result().dispatched())
1698 // Notify left insets
1701 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
1703 cursor().fixIfBroken();
1706 // Do we have a selection?
1707 theSelection().haveSelection(cursor().selection());
1709 // If the command has been dispatched,
1710 if (cur.result().dispatched() || cur.result().update())
1711 processUpdateFlags(cur.result().update());
1715 void BufferView::lfunScroll(FuncRequest const & cmd)
1717 string const scroll_type = cmd.getArg(0);
1718 int const scroll_step =
1719 (scroll_type == "line") ? d->scrollbarParameters_.single_step
1720 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
1721 if (scroll_step == 0)
1723 string const scroll_quantity = cmd.getArg(1);
1724 if (scroll_quantity == "up")
1725 scrollUp(scroll_step);
1726 else if (scroll_quantity == "down")
1727 scrollDown(scroll_step);
1729 int const scroll_value = convert<int>(scroll_quantity);
1731 scroll(scroll_step * scroll_value);
1738 int BufferView::minVisiblePart()
1740 return 2 * defaultRowHeight();
1744 int BufferView::scroll(int y)
1747 return scrollDown(y);
1749 return scrollUp(-y);
1754 int BufferView::scrollDown(int offset)
1756 Text * text = &buffer_.text();
1757 TextMetrics & tm = d->text_metrics_[text];
1758 int const ymax = height_ + offset;
1760 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1761 int bottom_pos = last.second->position() + last.second->descent();
1762 if (lyxrc.scroll_below_document)
1763 bottom_pos += height_ - minVisiblePart();
1764 if (last.first + 1 == int(text->paragraphs().size())) {
1765 if (bottom_pos <= height_)
1767 offset = min(offset, bottom_pos - height_);
1770 if (bottom_pos > ymax)
1772 tm.newParMetricsDown();
1774 d->anchor_ypos_ -= offset;
1779 int BufferView::scrollUp(int offset)
1781 Text * text = &buffer_.text();
1782 TextMetrics & tm = d->text_metrics_[text];
1783 int ymin = - offset;
1785 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1786 int top_pos = first.second->position() - first.second->ascent();
1787 if (first.first == 0) {
1790 offset = min(offset, - top_pos);
1795 tm.newParMetricsUp();
1797 d->anchor_ypos_ += offset;
1802 void BufferView::setCursorFromRow(int row)
1807 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1809 d->cursor_.reset(buffer_.inset());
1811 buffer_.text().setCursor(d->cursor_, 0, 0);
1813 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1817 bool BufferView::setCursorFromInset(Inset const * inset)
1819 // are we already there?
1820 if (cursor().nextInset() == inset)
1823 // Inset is not at cursor position. Find it in the document.
1825 cur.reset(buffer().inset());
1826 while (cur && cur.nextInset() != inset)
1837 void BufferView::gotoLabel(docstring const & label)
1839 std::vector<Buffer const *> bufs = buffer().allRelatives();
1840 std::vector<Buffer const *>::iterator it = bufs.begin();
1841 for (; it != bufs.end(); ++it) {
1842 Buffer const * buf = *it;
1845 Toc & toc = buf->tocBackend().toc("label");
1846 TocIterator toc_it = toc.begin();
1847 TocIterator end = toc.end();
1848 for (; toc_it != end; ++toc_it) {
1849 if (label == toc_it->str()) {
1850 dispatch(toc_it->action());
1858 TextMetrics const & BufferView::textMetrics(Text const * t) const
1860 return const_cast<BufferView *>(this)->textMetrics(t);
1864 TextMetrics & BufferView::textMetrics(Text const * t)
1866 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1867 if (tmc_it == d->text_metrics_.end()) {
1868 tmc_it = d->text_metrics_.insert(
1869 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1871 return tmc_it->second;
1875 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1878 return textMetrics(t).parMetrics(pit);
1882 int BufferView::workHeight() const
1888 void BufferView::setCursor(DocIterator const & dit)
1890 d->cursor_.reset(buffer().inset());
1891 size_t const n = dit.depth();
1892 for (size_t i = 0; i < n; ++i)
1893 dit[i].inset().edit(d->cursor_, true);
1895 d->cursor_.setCursor(dit);
1896 d->cursor_.setSelection(false);
1900 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1902 // Would be wrong to delete anything if we have a selection.
1903 if (cur.selection())
1906 bool need_anchor_change = false;
1907 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1908 need_anchor_change);
1910 if (need_anchor_change)
1918 buffer_.updateLabels();
1926 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1928 LASSERT(&cur.bv() == this, /**/);
1931 // this event will clear selection so we save selection for
1932 // persistent selection
1933 cap::saveSelection(cursor());
1935 // Has the cursor just left the inset?
1936 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1938 d->cursor_.fixIfBroken();
1940 // FIXME: shift-mouse selection doesn't work well across insets.
1941 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1943 // do the dEPM magic if needed
1944 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1945 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1946 // the leftinset bool would not be necessary (badcursor instead).
1947 bool update = leftinset;
1948 if (!do_selection && d->cursor_.inTexted())
1949 update |= checkDepm(cur, d->cursor_);
1950 d->cursor_.macroModeClose();
1952 d->cursor_.resetAnchor();
1953 d->cursor_.setCursor(cur);
1954 d->cursor_.boundary(cur.boundary());
1956 d->cursor_.setSelection();
1958 d->cursor_.clearSelection();
1960 d->cursor_.finishUndo();
1961 d->cursor_.setCurrentFont();
1966 void BufferView::putSelectionAt(DocIterator const & cur,
1967 int length, bool backwards)
1969 d->cursor_.clearSelection();
1975 d->cursor_.pos() += length;
1976 d->cursor_.setSelection(d->cursor_, -length);
1978 d->cursor_.setSelection(d->cursor_, length);
1980 // Ensure a redraw happens in any case because the new selection could
1981 // possibly be on the same screen as the previous selection.
1982 processUpdateFlags(Update::Force | Update::FitCursor);
1986 Cursor & BufferView::cursor()
1992 Cursor const & BufferView::cursor() const
1998 pit_type BufferView::anchor_ref() const
2000 return d->anchor_pit_;
2004 bool BufferView::singleParUpdate()
2006 Text & buftext = buffer_.text();
2007 pit_type const bottom_pit = d->cursor_.bottom().pit();
2008 TextMetrics & tm = textMetrics(&buftext);
2009 int old_height = tm.parMetrics(bottom_pit).height();
2011 // make sure inline completion pointer is ok
2012 if (d->inlineCompletionPos_.fixIfBroken())
2013 d->inlineCompletionPos_ = DocIterator();
2015 // In Single Paragraph mode, rebreak only
2016 // the (main text, not inset!) paragraph containing the cursor.
2017 // (if this paragraph contains insets etc., rebreaking will
2018 // recursively descend)
2019 tm.redoParagraph(bottom_pit);
2020 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2021 if (pm.height() != old_height)
2022 // Paragraph height has changed so we cannot proceed to
2023 // the singlePar optimisation.
2026 d->update_strategy_ = SingleParUpdate;
2028 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2029 << " y2: " << pm.position() + pm.descent()
2030 << " pit: " << bottom_pit
2031 << " singlepar: 1");
2036 void BufferView::updateMetrics()
2038 if (height_ == 0 || width_ == 0)
2041 Text & buftext = buffer_.text();
2042 pit_type const npit = int(buftext.paragraphs().size());
2044 // Clear out the position cache in case of full screen redraw,
2045 d->coord_cache_.clear();
2047 // Clear out paragraph metrics to avoid having invalid metrics
2048 // in the cache from paragraphs not relayouted below
2049 // The complete text metrics will be redone.
2050 d->text_metrics_.clear();
2052 TextMetrics & tm = textMetrics(&buftext);
2054 // make sure inline completion pointer is ok
2055 if (d->inlineCompletionPos_.fixIfBroken())
2056 d->inlineCompletionPos_ = DocIterator();
2058 if (d->anchor_pit_ >= npit)
2059 // The anchor pit must have been deleted...
2060 d->anchor_pit_ = npit - 1;
2062 // Rebreak anchor paragraph.
2063 tm.redoParagraph(d->anchor_pit_);
2064 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2067 if (d->anchor_pit_ == 0) {
2068 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2070 // Complete buffer visible? Then it's easy.
2071 if (scrollRange == 0)
2072 d->anchor_ypos_ = anchor_pm.ascent();
2074 // FIXME: Some clever handling needed to show
2075 // the _first_ paragraph up to the top if the cursor is
2076 // in the first line.
2078 anchor_pm.setPosition(d->anchor_ypos_);
2080 LYXERR(Debug::PAINTING, "metrics: "
2081 << " anchor pit = " << d->anchor_pit_
2082 << " anchor ypos = " << d->anchor_ypos_);
2084 // Redo paragraphs above anchor if necessary.
2085 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2086 // We are now just above the anchor paragraph.
2087 pit_type pit1 = d->anchor_pit_ - 1;
2088 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2089 tm.redoParagraph(pit1);
2090 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2092 // Save the paragraph position in the cache.
2097 // Redo paragraphs below the anchor if necessary.
2098 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2099 // We are now just below the anchor paragraph.
2100 pit_type pit2 = d->anchor_pit_ + 1;
2101 for (; pit2 < npit && y2 <= height_; ++pit2) {
2102 tm.redoParagraph(pit2);
2103 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2105 // Save the paragraph position in the cache.
2110 LYXERR(Debug::PAINTING, "Metrics: "
2111 << " anchor pit = " << d->anchor_pit_
2112 << " anchor ypos = " << d->anchor_ypos_
2115 << " pit1 = " << pit1
2116 << " pit2 = " << pit2);
2118 d->update_strategy_ = FullScreenUpdate;
2120 if (lyxerr.debugging(Debug::WORKAREA)) {
2121 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2122 d->coord_cache_.dump();
2127 void BufferView::insertLyXFile(FileName const & fname)
2129 LASSERT(d->cursor_.inTexted(), /**/);
2131 // Get absolute path of file and add ".lyx"
2132 // to the filename if necessary
2133 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2135 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2136 // emit message signal.
2137 message(bformat(_("Inserting document %1$s..."), disp_fn));
2140 Buffer buf("", false);
2141 if (buf.loadLyXFile(filename)) {
2142 ErrorList & el = buffer_.errorList("Parse");
2143 // Copy the inserted document error list into the current buffer one.
2144 el = buf.errorList("Parse");
2145 buffer_.undo().recordUndo(d->cursor_);
2146 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2147 buf.params().documentClassPtr(), el);
2148 res = _("Document %1$s inserted.");
2150 res = _("Could not insert document %1$s");
2155 // emit message signal.
2156 message(bformat(res, disp_fn));
2157 buffer_.errors("Parse");
2161 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2167 // Addup contribution of nested insets, from inside to outside,
2168 // keeping the outer paragraph for a special handling below
2169 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2170 CursorSlice const & sl = dit[i];
2174 // get relative position inside sl.inset()
2175 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2177 // Make relative position inside of the edited inset relative to sl.inset()
2181 // In case of an RTL inset, the edited inset will be positioned to the left
2184 bool boundary_i = boundary && i + 1 == dit.depth();
2185 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2190 // remember width for the case that sl.inset() is positioned in an RTL inset
2191 if (i && dit[i - 1].text()) {
2192 // If this Inset is inside a Text Inset, retrieve the Dimension
2193 // from the containing text instead of using Inset::dimension() which
2194 // might not be implemented.
2195 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2196 // elimination of Inset::dim_ cache. This coordOffset() method needs
2197 // to be rewritten in light of the new design.
2198 Dimension const & dim = parMetrics(dit[i - 1].text(),
2199 dit[i - 1].pit()).insetDimension(&sl.inset());
2202 Dimension const dim = sl.inset().dimension(*this);
2206 //lyxerr << "Cursor::getPos, i: "
2207 // << i << " x: " << xx << " y: " << y << endl;
2210 // Add contribution of initial rows of outermost paragraph
2211 CursorSlice const & sl = dit[0];
2212 TextMetrics const & tm = textMetrics(sl.text());
2213 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2214 LASSERT(!pm.rows().empty(), /**/);
2215 y -= pm.rows()[0].ascent();
2217 // FIXME: document this mess
2219 if (sl.pos() > 0 && dit.depth() == 1) {
2221 if (pos && boundary)
2223 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2224 rend = pm.pos2row(pos);
2226 rend = pm.pos2row(sl.pos());
2228 size_t rend = pm.pos2row(sl.pos());
2230 for (size_t rit = 0; rit != rend; ++rit)
2231 y += pm.rows()[rit].height();
2232 y += pm.rows()[rend].ascent();
2234 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2236 // Make relative position from the nested inset now bufferview absolute.
2237 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2240 // In the RTL case place the nested inset at the left of the cursor in
2241 // the outer paragraph
2242 bool boundary_1 = boundary && 1 == dit.depth();
2243 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2251 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2253 if (!paragraphVisible(dit))
2254 return Point(-1, -1);
2256 CursorSlice const & bot = dit.bottom();
2257 TextMetrics const & tm = textMetrics(bot.text());
2259 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2260 p.y_ += tm.parMetrics(bot.pit()).position();
2265 bool BufferView::paragraphVisible(DocIterator const & dit) const
2267 CursorSlice const & bot = dit.bottom();
2268 TextMetrics const & tm = textMetrics(bot.text());
2270 return tm.contains(bot.pit());
2274 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2276 Cursor const & cur = cursor();
2277 Font const font = cur.getFont();
2278 frontend::FontMetrics const & fm = theFontMetrics(font);
2279 int const asc = fm.maxAscent();
2280 int const des = fm.maxDescent();
2282 p = getPos(cur, cur.boundary());
2287 bool BufferView::cursorInView(Point const & p, int h) const
2289 Cursor const & cur = cursor();
2290 // does the cursor touch the screen ?
2291 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2297 void BufferView::draw(frontend::Painter & pain)
2299 if (height_ == 0 || width_ == 0)
2301 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2303 Text & text = buffer_.text();
2304 TextMetrics const & tm = d->text_metrics_[&text];
2305 int const y = tm.first().second->position();
2306 PainterInfo pi(this, pain);
2308 switch (d->update_strategy_) {
2310 case NoScreenUpdate:
2311 // If no screen painting is actually needed, only some the different
2312 // coordinates of insets and paragraphs needs to be updated.
2313 pi.full_repaint = true;
2314 pi.pain.setDrawingEnabled(false);
2318 case SingleParUpdate:
2319 pi.full_repaint = false;
2320 // In general, only the current row of the outermost paragraph
2321 // will be redrawn. Particular cases where selection spans
2322 // multiple paragraph are correctly detected in TextMetrics.
2326 case DecorationUpdate:
2327 // FIXME: We should also distinguish DecorationUpdate to avoid text
2328 // drawing if possible. This is not possible to do easily right now
2329 // because of the single backing pixmap.
2331 case FullScreenUpdate:
2332 // The whole screen, including insets, will be refreshed.
2333 pi.full_repaint = true;
2335 // Clear background.
2336 pain.fillRectangle(0, 0, width_, height_,
2337 pi.backgroundColor(&buffer_.inset()));
2342 // and possibly grey out below
2343 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2344 int const y2 = lastpm.second->position() + lastpm.second->descent();
2347 bool const embedded_workarea = buffer().isUnnamed()
2348 && buffer().fileName().extension() == "internal";
2349 Color color = embedded_workarea ? Color_background
2351 pain.fillRectangle(0, y2, width_, height_ - y2, color);
2355 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2357 // The scrollbar needs an update.
2360 // Normalize anchor for next time
2361 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2362 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2363 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2364 ParagraphMetrics const & pm = tm.parMetrics(pit);
2365 if (pm.position() + pm.descent() > 0) {
2366 d->anchor_pit_ = pit;
2367 d->anchor_ypos_ = pm.position();
2371 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2372 << " anchor ypos = " << d->anchor_ypos_);
2376 void BufferView::message(docstring const & msg)
2379 d->gui_->message(msg);
2383 void BufferView::showDialog(string const & name)
2386 d->gui_->showDialog(name, string());
2390 void BufferView::showDialog(string const & name,
2391 string const & data, Inset * inset)
2394 d->gui_->showDialog(name, data, inset);
2398 void BufferView::updateDialog(string const & name, string const & data)
2401 d->gui_->updateDialog(name, data);
2405 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2411 // FIXME: Move this out of BufferView again
2412 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2414 if (!fname.isReadableFile()) {
2415 docstring const error = from_ascii(strerror(errno));
2416 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2417 docstring const text =
2418 bformat(_("Could not read the specified document\n"
2419 "%1$s\ndue to the error: %2$s"), file, error);
2420 Alert::error(_("Could not read file"), text);
2424 if (!fname.isReadableFile()) {
2425 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2426 docstring const text =
2427 bformat(_("%1$s\n is not readable."), file);
2428 Alert::error(_("Could not open file"), text);
2432 // FIXME UNICODE: We don't know the encoding of the file
2433 docstring file_content = fname.fileContents("UTF-8");
2434 if (file_content.empty()) {
2435 Alert::error(_("Reading not UTF-8 encoded file"),
2436 _("The file is not UTF-8 encoded.\n"
2437 "It will be read as local 8Bit-encoded.\n"
2438 "If this does not give the correct result\n"
2439 "then please change the encoding of the file\n"
2440 "to UTF-8 with a program other than LyX.\n"));
2441 file_content = fname.fileContents("local8bit");
2444 return normalize_c(file_content);
2448 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2450 docstring const tmpstr = contentsOfPlaintextFile(f);
2455 Cursor & cur = cursor();
2456 cap::replaceSelection(cur);
2457 buffer_.undo().recordUndo(cur);
2459 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2461 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2468 docstring const & BufferView::inlineCompletion() const
2470 return d->inlineCompletion_;
2474 size_t const & BufferView::inlineCompletionUniqueChars() const
2476 return d->inlineCompletionUniqueChars_;
2480 DocIterator const & BufferView::inlineCompletionPos() const
2482 return d->inlineCompletionPos_;
2486 bool samePar(DocIterator const & a, DocIterator const & b)
2488 if (a.empty() && b.empty())
2490 if (a.empty() || b.empty())
2492 if (a.depth() != b.depth())
2494 return &a.innerParagraph() == &b.innerParagraph();
2498 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2499 docstring const & completion, size_t uniqueChars)
2501 uniqueChars = min(completion.size(), uniqueChars);
2502 bool changed = d->inlineCompletion_ != completion
2503 || d->inlineCompletionUniqueChars_ != uniqueChars;
2504 bool singlePar = true;
2505 d->inlineCompletion_ = completion;
2506 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2508 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2511 DocIterator const & old = d->inlineCompletionPos_;
2513 //lyxerr << "inlineCompletionPos changed" << std::endl;
2514 // old or pos are in another paragraph?
2515 if ((!samePar(cur, pos) && !pos.empty())
2516 || (!samePar(cur, old) && !old.empty())) {
2518 //lyxerr << "different paragraph" << std::endl;
2520 d->inlineCompletionPos_ = pos;
2525 if (singlePar && !(cur.disp_.update() & Update::Force))
2526 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2528 cur.updateFlags(cur.disp_.update() | Update::Force);