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 "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
49 #include "TextClass.h"
50 #include "TextMetrics.h"
52 #include "TocBackend.h"
54 #include "WordLangTuple.h"
56 #include "insets/InsetBibtex.h"
57 #include "insets/InsetCommand.h" // ChangeRefs
58 #include "insets/InsetExternal.h"
59 #include "insets/InsetGraphics.h"
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
62 #include "insets/InsetNote.h"
64 #include "frontends/alert.h"
65 #include "frontends/Application.h"
66 #include "frontends/Delegates.h"
67 #include "frontends/FontMetrics.h"
68 #include "frontends/Painter.h"
69 #include "frontends/Selection.h"
71 #include "graphics/Previews.h"
73 #include "support/convert.h"
74 #include "support/debug.h"
75 #include "support/ExceptionMessage.h"
76 #include "support/filetools.h"
77 #include "support/gettext.h"
78 #include "support/lstrings.h"
79 #include "support/Package.h"
80 #include "support/types.h"
89 using namespace lyx::support;
93 namespace Alert = frontend::Alert;
97 /// Return an inset of this class if it exists at the current cursor position
99 T * getInsetByCode(Cursor const & cur, InsetCode code)
101 DocIterator it = cur;
102 Inset * inset = it.nextInset();
103 if (inset && inset->lyxCode() == code)
104 return static_cast<T*>(inset);
109 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
112 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
113 docstring const & contents)
115 DocIterator tmpdit = dit;
118 Inset const * inset = tmpdit.nextInset();
120 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
121 && (contents.empty() ||
122 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
126 tmpdit.forwardInset();
133 /// Looks for next inset with one of the given codes.
134 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
138 DocIterator tmpdit = dit;
139 tmpdit.forwardInset();
144 Inset const * inset = tmpdit.nextInset();
146 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
147 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
151 if (!findNextInset(tmpdit, codes, contents)) {
152 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
153 Inset * inset = &tmpdit.bottom().inset();
154 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
155 if (!findNextInset(tmpdit, codes, contents))
167 /// Looks for next inset with the given code
168 void findInset(DocIterator & dit, InsetCode code, bool same_content)
170 findInset(dit, vector<InsetCode>(1, code), same_content);
174 /// Moves cursor to the next inset with one of the given codes.
175 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
178 Cursor tmpcur = bv->cursor();
179 if (!findInset(tmpcur, codes, same_content)) {
180 bv->cursor().message(_("No more insets"));
184 tmpcur.clearSelection();
185 bv->setCursor(tmpcur);
190 /// Moves cursor to the next inset with given code.
191 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
193 gotoInset(bv, vector<InsetCode>(1, code), same_content);
197 /// A map from a Text to the associated text metrics
198 typedef map<Text const *, TextMetrics> TextMetricsCache;
200 enum ScreenUpdateStrategy {
210 /////////////////////////////////////////////////////////////////////
214 /////////////////////////////////////////////////////////////////////
216 struct BufferView::Private
218 Private(BufferView & bv): wh_(0), cursor_(bv),
219 anchor_pit_(0), anchor_ypos_(0),
220 inlineCompletionUniqueChars_(0),
221 last_inset_(0), bookmark_edit_position_(0), gui_(0)
225 ScrollbarParameters scrollbarParameters_;
227 ScreenUpdateStrategy update_strategy_;
229 CoordCache coord_cache_;
231 /// Estimated average par height for scrollbar.
233 /// this is used to handle XSelection events in the right manner.
242 pit_type anchor_pit_;
246 vector<int> par_height_;
249 DocIterator inlineCompletionPos_;
251 docstring inlineCompletion_;
253 size_t inlineCompletionUniqueChars_;
255 /// keyboard mapping object.
258 /// last visited inset.
259 /** kept to send setMouseHover(false).
260 * Not owned, so don't delete.
264 // cache for id of the paragraph which was edited the last time
265 int bookmark_edit_position_;
267 mutable TextMetricsCache text_metrics_;
270 /** Not owned, so don't delete.
272 frontend::GuiBufferViewDelegate * gui_;
274 /// Cache for Find Next
275 FuncRequest search_request_cache_;
279 BufferView::BufferView(Buffer & buf)
280 : width_(0), height_(0), full_screen_(false), buffer_(buf),
281 d(new Private(*this))
283 d->xsel_cache_.set = false;
284 d->intl_.initKeyMapper(lyxrc.use_kbmap);
286 d->cursor_.setBuffer(&buf);
287 d->cursor_.push(buffer_.inset());
288 d->cursor_.resetAnchor();
289 d->cursor_.setCurrentFont();
291 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
292 thePreviews().generateBufferPreviews(buffer_);
296 BufferView::~BufferView()
298 // current buffer is going to be switched-off, save cursor pos
299 // Ideally, the whole cursor stack should be saved, but session
300 // currently can only handle bottom (whole document) level pit and pos.
301 // That is to say, if a cursor is in a nested inset, it will be
302 // restore to the left of the top level inset.
303 LastFilePosSection::FilePos fp;
304 fp.pit = d->cursor_.bottom().pit();
305 fp.pos = d->cursor_.bottom().pos();
306 theSession().lastFilePos().save(buffer_.fileName(), fp);
312 int BufferView::rightMargin() const
314 // The additional test for the case the outliner is opened.
316 !lyxrc.full_screen_limit ||
317 width_ < lyxrc.full_screen_width + 20)
320 return (width_ - lyxrc.full_screen_width) / 2;
324 int BufferView::leftMargin() const
326 return rightMargin();
330 bool BufferView::isTopScreen() const
332 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
336 bool BufferView::isBottomScreen() const
338 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
342 Intl & BufferView::getIntl()
348 Intl const & BufferView::getIntl() const
354 CoordCache & BufferView::coordCache()
356 return d->coord_cache_;
360 CoordCache const & BufferView::coordCache() const
362 return d->coord_cache_;
366 Buffer & BufferView::buffer()
372 Buffer const & BufferView::buffer() const
378 bool BufferView::fitCursor()
380 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
381 frontend::FontMetrics const & fm =
382 theFontMetrics(d->cursor_.getFont().fontInfo());
383 int const asc = fm.maxAscent();
384 int const des = fm.maxDescent();
385 Point const p = getPos(d->cursor_, d->cursor_.boundary());
386 if (p.y_ - asc >= 0 && p.y_ + des < height_)
393 void BufferView::processUpdateFlags(Update::flags flags)
395 // last_inset_ points to the last visited inset. This pointer may become
396 // invalid because of keyboard editing. Since all such operations
397 // causes screen update(), I reset last_inset_ to avoid such a problem.
399 // This is close to a hot-path.
400 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
401 << "[fitcursor = " << (flags & Update::FitCursor)
402 << ", forceupdate = " << (flags & Update::Force)
403 << ", singlepar = " << (flags & Update::SinglePar)
404 << "] buffer: " << &buffer_);
406 buffer_.updateMacros();
408 // Now do the first drawing step if needed. This consists on updating
409 // the CoordCache in updateMetrics().
410 // The second drawing step is done in WorkArea::redraw() if needed.
412 // Case when no explicit update is requested.
414 // no need to redraw anything.
415 d->update_strategy_ = NoScreenUpdate;
419 if (flags == Update::Decoration) {
420 d->update_strategy_ = DecorationUpdate;
425 if (flags == Update::FitCursor
426 || flags == (Update::Decoration | Update::FitCursor)) {
427 // tell the frontend to update the screen if needed.
432 if (flags & Update::Decoration) {
433 d->update_strategy_ = DecorationUpdate;
437 // no screen update is needed.
438 d->update_strategy_ = NoScreenUpdate;
442 bool const full_metrics = flags & Update::Force || !singleParUpdate();
445 // We have to update the full screen metrics.
448 if (!(flags & Update::FitCursor)) {
449 // Nothing to do anymore. Trigger a redraw and return
454 // updateMetrics() does not update paragraph position
455 // This is done at draw() time. So we need a redraw!
459 // The cursor is off screen so ensure it is visible.
466 void BufferView::updateScrollbar()
468 if (height_ == 0 && width_ == 0)
471 // We prefer fixed size line scrolling.
472 d->scrollbarParameters_.single_step = defaultRowHeight();
473 // We prefer full screen page scrolling.
474 d->scrollbarParameters_.page_step = height_;
476 Text & t = buffer_.text();
477 TextMetrics & tm = d->text_metrics_[&t];
479 LYXERR(Debug::GUI, " Updating scrollbar: height: "
480 << t.paragraphs().size()
481 << " curr par: " << d->cursor_.bottom().pit()
482 << " default height " << defaultRowHeight());
484 size_t const parsize = t.paragraphs().size();
485 if (d->par_height_.size() != parsize) {
486 d->par_height_.clear();
487 // FIXME: We assume a default paragraph height of 2 rows. This
488 // should probably be pondered with the screen width.
489 d->par_height_.resize(parsize, defaultRowHeight() * 2);
492 // Look at paragraph heights on-screen
493 pair<pit_type, ParagraphMetrics const *> first = tm.first();
494 pair<pit_type, ParagraphMetrics const *> last = tm.last();
495 for (pit_type pit = first.first; pit <= last.first; ++pit) {
496 d->par_height_[pit] = tm.parMetrics(pit).height();
497 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
498 << d->par_height_[pit]);
501 int top_pos = first.second->position() - first.second->ascent();
502 int bottom_pos = last.second->position() + last.second->descent();
503 bool first_visible = first.first == 0 && top_pos >= 0;
504 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
505 if (first_visible && last_visible) {
506 d->scrollbarParameters_.min = 0;
507 d->scrollbarParameters_.max = 0;
511 d->scrollbarParameters_.min = top_pos;
512 for (size_t i = 0; i != size_t(first.first); ++i)
513 d->scrollbarParameters_.min -= d->par_height_[i];
514 d->scrollbarParameters_.max = bottom_pos;
515 for (size_t i = last.first + 1; i != parsize; ++i)
516 d->scrollbarParameters_.max += d->par_height_[i];
518 d->scrollbarParameters_.position = 0;
519 // The reference is the top position so we remove one page.
520 if (lyxrc.scroll_below_document)
521 d->scrollbarParameters_.max -= minVisiblePart();
523 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
527 ScrollbarParameters const & BufferView::scrollbarParameters() const
529 return d->scrollbarParameters_;
533 docstring BufferView::toolTip(int x, int y) const
535 // Get inset under mouse, if there is one.
536 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
538 // No inset, no tooltip...
540 return covering_inset->toolTip(*this, x, y);
544 docstring BufferView::contextMenu(int x, int y) const
546 //If there is a selection, return the containing inset menu
547 if (d->cursor_.selection())
548 return d->cursor_.inset().contextMenu(*this, x, y);
550 // Get inset under mouse, if there is one.
551 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
553 return covering_inset->contextMenu(*this, x, y);
555 return buffer_.inset().contextMenu(*this, x, y);
559 void BufferView::scrollDocView(int value)
561 int const offset = value - d->scrollbarParameters_.position;
563 // No scrolling at all? No need to redraw anything
567 // If the offset is less than 2 screen height, prefer to scroll instead.
568 if (abs(offset) <= 2 * height_) {
569 d->anchor_ypos_ -= offset;
575 // cut off at the top
576 if (value <= d->scrollbarParameters_.min) {
577 DocIterator dit = doc_iterator_begin(&buffer_);
579 LYXERR(Debug::SCROLLING, "scroll to top");
583 // cut off at the bottom
584 if (value >= d->scrollbarParameters_.max) {
585 DocIterator dit = doc_iterator_end(&buffer_);
588 LYXERR(Debug::SCROLLING, "scroll to bottom");
592 // find paragraph at target position
593 int par_pos = d->scrollbarParameters_.min;
595 for (; i != int(d->par_height_.size()); ++i) {
596 par_pos += d->par_height_[i];
597 if (par_pos >= value)
601 if (par_pos < value) {
602 // It seems we didn't find the correct pit so stay on the safe side and
604 LYXERR0("scrolling position not found!");
605 scrollDocView(d->scrollbarParameters_.max);
609 DocIterator dit = doc_iterator_begin(&buffer_);
611 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
616 // FIXME: this method is not working well.
617 void BufferView::setCursorFromScrollbar()
619 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
621 int const height = 2 * defaultRowHeight();
622 int const first = height;
623 int const last = height_ - height;
625 Cursor const & oldcur = d->cursor_;
627 switch (cursorStatus(oldcur)) {
635 int const y = getPos(oldcur, oldcur.boundary()).y_;
636 newy = min(last, max(y, first));
640 // We reset the cursor because cursorStatus() does not
641 // work when the cursor is within mathed.
643 cur.reset(buffer_.inset());
644 tm.setCursorFromCoordinates(cur, 0, newy);
646 // update the bufferview cursor and notify insets
647 // FIXME: Care about the d->cursor_ flags to redraw if needed
648 Cursor old = d->cursor_;
650 bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
652 d->cursor_.fixIfBroken();
656 Change const BufferView::getCurrentChange() const
658 if (!d->cursor_.selection())
659 return Change(Change::UNCHANGED);
661 DocIterator dit = d->cursor_.selectionBegin();
662 return dit.paragraph().lookupChange(dit.pos());
666 // this could be used elsewhere as well?
667 // FIXME: This does not work within mathed!
668 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
670 Point const p = getPos(dit, dit.boundary());
673 if (p.y_ > workHeight())
679 void BufferView::bookmarkEditPosition()
681 // Don't eat cpu time for each keystroke
682 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
685 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
689 void BufferView::saveBookmark(unsigned int idx)
691 // tentatively save bookmark, id and pos will be used to
692 // acturately locate a bookmark in a 'live' lyx session.
693 // pit and pos will be updated with bottom level pit/pos
695 theSession().bookmarks().save(
697 d->cursor_.bottom().pit(),
698 d->cursor_.bottom().pos(),
699 d->cursor_.paragraph().id(),
704 // emit message signal.
705 message(_("Save bookmark"));
709 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
710 int top_id, pos_type top_pos)
712 bool success = false;
715 d->cursor_.clearSelection();
717 // if a valid par_id is given, try it first
718 // This is the case for a 'live' bookmark when unique paragraph ID
719 // is used to track bookmarks.
721 dit = buffer_.getParFromID(top_id);
723 dit.pos() = min(dit.paragraph().size(), top_pos);
724 // Some slices of the iterator may not be
725 // reachable (e.g. closed collapsable inset)
726 // so the dociterator may need to be
727 // shortened. Otherwise, setCursor may crash
728 // lyx when the cursor can not be set to these
730 size_t const n = dit.depth();
731 for (size_t i = 0; i < n; ++i)
732 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
740 // if top_id == 0, or searching through top_id failed
741 // This is the case for a 'restored' bookmark when only bottom
742 // (document level) pit was saved. Because of this, bookmark
743 // restoration is inaccurate. If a bookmark was within an inset,
744 // it will be restored to the left of the outmost inset that contains
746 if (bottom_pit < int(buffer_.paragraphs().size())) {
747 dit = doc_iterator_begin(&buffer_);
749 dit.pit() = bottom_pit;
750 dit.pos() = min(bottom_pos, dit.paragraph().size());
755 // Note: only bottom (document) level pit is set.
757 // set the current font.
758 d->cursor_.setCurrentFont();
759 // To center the screen on this new position we need the
760 // paragraph position which is computed at draw() time.
761 // So we need a redraw!
771 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
773 if (lyxrc.rtl_support) {
774 if (d->cursor_.real_current_font.isRightToLeft()) {
775 if (d->intl_.keymap == Intl::PRIMARY)
776 d->intl_.keyMapSec();
778 if (d->intl_.keymap == Intl::SECONDARY)
779 d->intl_.keyMapPrim();
783 d->intl_.getTransManager().translateAndInsert(c, t, cur);
787 int BufferView::workWidth() const
793 void BufferView::recenter()
795 showCursor(d->cursor_, true);
799 void BufferView::showCursor()
801 showCursor(d->cursor_, false);
805 void BufferView::showCursor(DocIterator const & dit, bool recenter)
807 if (scrollToCursor(dit, recenter))
812 void BufferView::scrollToCursor()
814 scrollToCursor(d->cursor_, false);
818 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
820 // We are not properly started yet, delay until resizing is
825 LYXERR(Debug::SCROLLING, "recentering!");
827 CursorSlice const & bot = dit.bottom();
828 TextMetrics & tm = d->text_metrics_[bot.text()];
830 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
831 int bot_pit = bot.pit();
832 if (bot_pit > max_pit) {
833 // FIXME: Why does this happen?
834 LYXERR0("bottom pit is greater that max pit: "
835 << bot_pit << " > " << max_pit);
839 if (bot_pit == tm.first().first - 1)
840 tm.newParMetricsUp();
841 else if (bot_pit == tm.last().first + 1)
842 tm.newParMetricsDown();
844 if (tm.contains(bot_pit)) {
845 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
846 LASSERT(!pm.rows().empty(), /**/);
847 // FIXME: smooth scrolling doesn't work in mathed.
848 CursorSlice const & cs = dit.innerTextSlice();
849 int offset = coordOffset(dit, dit.boundary()).y_;
850 int ypos = pm.position() + offset;
851 Dimension const & row_dim =
852 pm.getRow(cs.pos(), dit.boundary()).dimension();
855 scrolled = scroll(ypos - height_/2);
856 else if (ypos - row_dim.ascent() < 0)
857 scrolled = scrollUp(- ypos + row_dim.ascent());
858 else if (ypos + row_dim.descent() > height_)
859 scrolled = scrollDown(ypos - height_ + defaultRowHeight() );
861 // else, nothing to do, the cursor is already visible so we just return.
869 // fix inline completion position
870 if (d->inlineCompletionPos_.fixIfBroken())
871 d->inlineCompletionPos_ = DocIterator();
873 tm.redoParagraph(bot_pit);
874 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
875 int offset = coordOffset(dit, dit.boundary()).y_;
877 d->anchor_pit_ = bot_pit;
878 CursorSlice const & cs = dit.innerTextSlice();
879 Dimension const & row_dim =
880 pm.getRow(cs.pos(), dit.boundary()).dimension();
883 d->anchor_ypos_ = height_/2;
884 else if (d->anchor_pit_ == 0)
885 d->anchor_ypos_ = offset + pm.ascent();
886 else if (d->anchor_pit_ == max_pit)
887 d->anchor_ypos_ = height_ - offset - row_dim.descent();
888 else if (offset > height_)
889 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
891 d->anchor_ypos_ = defaultRowHeight() * 2;
898 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
902 Cursor & cur = d->cursor_;
904 switch (cmd.action) {
907 flag.setEnabled(buffer_.undo().hasUndoStack());
910 flag.setEnabled(buffer_.undo().hasRedoStack());
912 case LFUN_FILE_INSERT:
913 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
914 case LFUN_FILE_INSERT_PLAINTEXT:
915 case LFUN_BOOKMARK_SAVE:
916 // FIXME: Actually, these LFUNS should be moved to Text
917 flag.setEnabled(cur.inTexted());
919 case LFUN_FONT_STATE:
920 case LFUN_LABEL_INSERT:
921 case LFUN_INFO_INSERT:
922 case LFUN_INSET_EDIT:
923 case LFUN_PARAGRAPH_GOTO:
925 case LFUN_REFERENCE_NEXT:
927 case LFUN_WORD_FINDADV:
928 case LFUN_WORD_REPLACE:
931 case LFUN_MARK_TOGGLE:
932 case LFUN_SCREEN_RECENTER:
933 case LFUN_SCREEN_SHOW_CURSOR:
934 case LFUN_BIBTEX_DATABASE_ADD:
935 case LFUN_BIBTEX_DATABASE_DEL:
936 case LFUN_NOTES_MUTATE:
937 case LFUN_ALL_INSETS_TOGGLE:
938 case LFUN_STATISTICS:
939 flag.setEnabled(true);
942 // @todo Test if current WorkArea is the search WorkArea
943 case LFUN_REGEXP_MODE:
944 flag.setEnabled(! this->cursor().inRegexped());
947 case LFUN_COPY_LABEL_AS_REF: {
948 // if there is an inset at cursor, see whether it
950 Inset * inset = cur.nextInset();
951 if (!inset || !inset->getStatus(cur, cmd, flag))
952 flag.setEnabled(false);
956 case LFUN_NEXT_INSET_MODIFY: {
957 // this is the real function we want to invoke
958 FuncRequest tmpcmd = cmd;
959 tmpcmd.action = LFUN_INSET_MODIFY;
960 // if there is an inset at cursor, see whether it
961 // handles the lfun, other start from scratch
962 Inset * inset = cur.nextInset();
963 if (!inset || !inset->getStatus(cur, tmpcmd, flag))
964 flag = lyx::getStatus(tmpcmd);
968 case LFUN_LABEL_GOTO: {
969 flag.setEnabled(!cmd.argument().empty()
970 || getInsetByCode<InsetRef>(cur, REF_CODE));
974 case LFUN_CHANGES_TRACK:
975 flag.setEnabled(true);
976 flag.setOnOff(buffer_.params().trackChanges);
979 case LFUN_CHANGES_OUTPUT:
980 flag.setEnabled(true);
981 flag.setOnOff(buffer_.params().outputChanges);
984 case LFUN_CHANGES_MERGE:
985 case LFUN_CHANGE_NEXT:
986 case LFUN_CHANGE_PREVIOUS:
987 case LFUN_ALL_CHANGES_ACCEPT:
988 case LFUN_ALL_CHANGES_REJECT:
989 // TODO: context-sensitive enabling of LFUNs
990 // In principle, these command should only be enabled if there
991 // is a change in the document. However, without proper
992 // optimizations, this will inevitably result in poor performance.
993 flag.setEnabled(true);
996 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
997 flag.setOnOff(buffer_.params().compressed);
1001 case LFUN_SCREEN_UP:
1002 case LFUN_SCREEN_DOWN:
1004 case LFUN_SCREEN_UP_SELECT:
1005 case LFUN_SCREEN_DOWN_SELECT:
1006 flag.setEnabled(true);
1009 case LFUN_LAYOUT_TABULAR:
1010 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1014 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1017 case LFUN_LAYOUT_PARAGRAPH:
1018 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1021 case LFUN_INSET_SETTINGS: {
1022 InsetCode code = cur.inset().lyxCode();
1023 if (cmd.getArg(0) == insetName(code)) {
1024 flag.setEnabled(true);
1027 bool enable = false;
1028 InsetCode next_code = cur.nextInset()
1029 ? cur.nextInset()->lyxCode() : NO_CODE;
1030 //FIXME: remove these special cases:
1031 switch (next_code) {
1041 enable = (cmd.argument().empty() ||
1042 cmd.getArg(0) == insetName(next_code));
1047 flag.setEnabled(enable);
1051 case LFUN_DIALOG_SHOW_NEW_INSET:
1052 flag.setEnabled(cur.inset().lyxCode() != ERT_CODE &&
1053 cur.inset().lyxCode() != LISTINGS_CODE);
1054 if (cur.inset().lyxCode() == CAPTION_CODE) {
1056 if (cur.inset().getStatus(cur, cmd, flag))
1061 case LFUN_BRANCH_ACTIVATE:
1062 case LFUN_BRANCH_DEACTIVATE: {
1063 BranchList const & branchList = buffer_.params().branchlist();
1064 docstring const branchName = cmd.argument();
1065 flag.setEnabled(!branchName.empty()
1066 && branchList.find(branchName));
1071 flag.setEnabled(false);
1078 bool BufferView::dispatch(FuncRequest const & cmd)
1080 //lyxerr << [ cmd = " << cmd << "]" << endl;
1082 // Make sure that the cached BufferView is correct.
1083 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1084 << " arg[" << to_utf8(cmd.argument()) << ']'
1085 << " x[" << cmd.x << ']'
1086 << " y[" << cmd.y << ']'
1087 << " button[" << cmd.button() << ']');
1089 Cursor & cur = d->cursor_;
1091 switch (cmd.action) {
1094 cur.message(_("Undo"));
1095 cur.clearSelection();
1096 if (!cur.textUndo())
1097 cur.message(_("No further undo information"));
1099 processUpdateFlags(Update::Force | Update::FitCursor);
1103 cur.message(_("Redo"));
1104 cur.clearSelection();
1105 if (!cur.textRedo())
1106 cur.message(_("No further redo information"));
1108 processUpdateFlags(Update::Force | Update::FitCursor);
1111 case LFUN_FONT_STATE:
1112 cur.message(cur.currentState());
1115 case LFUN_BOOKMARK_SAVE:
1116 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1119 case LFUN_LABEL_GOTO: {
1120 docstring label = cmd.argument();
1121 if (label.empty()) {
1123 getInsetByCode<InsetRef>(d->cursor_, REF_CODE);
1125 label = inset->getParam("reference");
1126 // persistent=false: use temp_bookmark
1135 case LFUN_INSET_EDIT: {
1136 FuncRequest fr(cmd);
1137 // if there is an inset at cursor, see whether it
1139 Inset * inset = cur.nextInset();
1141 inset->dispatch(cur, fr);
1142 // if it did not work, try the underlying inset.
1143 if (!inset || !cur.result().dispatched())
1146 // FIXME I'm adding the last break to solve a crash,
1147 // but that is obviously not right.
1148 if (!cur.result().dispatched())
1149 // It did not work too; no action needed.
1154 case LFUN_PARAGRAPH_GOTO: {
1155 int const id = convert<int>(cmd.getArg(0));
1156 int const pos = convert<int>(cmd.getArg(1));
1158 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1159 b = theBufferList().next(b)) {
1161 DocIterator dit = b->getParFromID(id);
1163 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1167 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1168 << " found in buffer `"
1169 << b->absFileName() << "'.");
1171 if (b == &buffer_) {
1175 processUpdateFlags(Update::Force | Update::FitCursor);
1177 // Switch to other buffer view and resend cmd
1178 theLyXFunc().dispatch(FuncRequest(
1179 LFUN_BUFFER_SWITCH, b->absFileName()));
1180 theLyXFunc().dispatch(cmd);
1187 case LFUN_NOTE_NEXT:
1188 gotoInset(this, NOTE_CODE, false);
1191 case LFUN_REFERENCE_NEXT: {
1192 vector<InsetCode> tmp;
1193 tmp.push_back(LABEL_CODE);
1194 tmp.push_back(REF_CODE);
1195 gotoInset(this, tmp, true);
1199 case LFUN_CHANGES_TRACK:
1200 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1203 case LFUN_CHANGES_OUTPUT:
1204 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1205 if (buffer_.params().outputChanges) {
1206 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1207 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1208 LaTeXFeatures::isAvailable("xcolor");
1210 if (!dvipost && !xcolorulem) {
1211 Alert::warning(_("Changes not shown in LaTeX output"),
1212 _("Changes will not be highlighted in LaTeX output, "
1213 "because neither dvipost nor xcolor/ulem are installed.\n"
1214 "Please install these packages or redefine "
1215 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1216 } else if (!xcolorulem) {
1217 Alert::warning(_("Changes not shown in LaTeX output"),
1218 _("Changes will not be highlighted in LaTeX output "
1219 "when using pdflatex, because xcolor and ulem are not installed.\n"
1220 "Please install both packages or redefine "
1221 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1226 case LFUN_CHANGE_NEXT:
1227 findNextChange(this);
1228 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1229 processUpdateFlags(Update::Force | Update::FitCursor);
1232 case LFUN_CHANGE_PREVIOUS:
1233 findPreviousChange(this);
1234 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1235 processUpdateFlags(Update::Force | Update::FitCursor);
1238 case LFUN_CHANGES_MERGE:
1239 if (findNextChange(this)) {
1240 processUpdateFlags(Update::Force | Update::FitCursor);
1241 showDialog("changes");
1245 case LFUN_ALL_CHANGES_ACCEPT:
1246 // select complete document
1247 d->cursor_.reset(buffer_.inset());
1248 d->cursor_.selHandle(true);
1249 buffer_.text().cursorBottom(d->cursor_);
1250 // accept everything in a single step to support atomic undo
1251 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1252 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1253 processUpdateFlags(Update::Force | Update::FitCursor);
1256 case LFUN_ALL_CHANGES_REJECT:
1257 // select complete document
1258 d->cursor_.reset(buffer_.inset());
1259 d->cursor_.selHandle(true);
1260 buffer_.text().cursorBottom(d->cursor_);
1261 // reject everything in a single step to support atomic undo
1262 // Note: reject does not work recursively; the user may have to repeat the operation
1263 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1264 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1265 processUpdateFlags(Update::Force | Update::FitCursor);
1268 case LFUN_WORD_FIND: {
1269 FuncRequest req = cmd;
1270 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1271 req = d->search_request_cache_;
1272 if (req.argument().empty()) {
1273 theLyXFunc().dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1276 if (find(this, req))
1279 message(_("String not found!"));
1280 d->search_request_cache_ = req;
1284 case LFUN_WORD_REPLACE: {
1285 bool has_deleted = false;
1286 if (cur.selection()) {
1287 DocIterator beg = cur.selectionBegin();
1288 DocIterator end = cur.selectionEnd();
1289 if (beg.pit() == end.pit()) {
1290 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1291 if (cur.paragraph().isDeleted(p))
1296 replace(this, cmd, has_deleted);
1300 case LFUN_WORD_FINDADV:
1305 cur.clearSelection();
1307 cur.message(from_utf8(N_("Mark off")));
1311 cur.clearSelection();
1314 cur.message(from_utf8(N_("Mark on")));
1317 case LFUN_MARK_TOGGLE:
1318 cur.clearSelection();
1321 cur.message(from_utf8(N_("Mark removed")));
1324 cur.message(from_utf8(N_("Mark set")));
1329 case LFUN_SCREEN_SHOW_CURSOR:
1333 case LFUN_SCREEN_RECENTER:
1337 case LFUN_BIBTEX_DATABASE_ADD: {
1338 Cursor tmpcur = d->cursor_;
1339 findInset(tmpcur, BIBTEX_CODE, false);
1340 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1343 if (inset->addDatabase(cmd.argument()))
1344 buffer_.updateBibfilesCache();
1349 case LFUN_BIBTEX_DATABASE_DEL: {
1350 Cursor tmpcur = d->cursor_;
1351 findInset(tmpcur, BIBTEX_CODE, false);
1352 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1355 if (inset->delDatabase(cmd.argument()))
1356 buffer_.updateBibfilesCache();
1361 case LFUN_STATISTICS: {
1362 DocIterator from, to;
1363 if (cur.selection()) {
1364 from = cur.selectionBegin();
1365 to = cur.selectionEnd();
1367 from = doc_iterator_begin(&buffer_);
1368 to = doc_iterator_end(&buffer_);
1370 int const words = countWords(from, to);
1371 int const chars = countChars(from, to, false);
1372 int const chars_blanks = countChars(from, to, true);
1374 if (cur.selection())
1375 message = _("Statistics for the selection:");
1377 message = _("Statistics for the document:");
1380 message += bformat(_("%1$d words"), words);
1382 message += _("One word");
1384 if (chars_blanks != 1)
1385 message += bformat(_("%1$d characters (including blanks)"),
1388 message += _("One character (including blanks)");
1391 message += bformat(_("%1$d characters (excluding blanks)"),
1394 message += _("One character (excluding blanks)");
1396 Alert::information(_("Statistics"), message);
1400 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1401 // turn compression on/off
1402 buffer_.params().compressed = !buffer_.params().compressed;
1404 case LFUN_COPY_LABEL_AS_REF: {
1405 // if there is an inset at cursor, try to copy it
1406 Inset * inset = cur.nextInset();
1408 FuncRequest tmpcmd = cmd;
1409 inset->dispatch(cur, tmpcmd);
1411 if (!cur.result().dispatched())
1412 // It did not work too; no action needed.
1414 cur.clearSelection();
1415 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1418 case LFUN_NEXT_INSET_MODIFY: {
1419 // create the the real function we want to invoke
1420 FuncRequest tmpcmd = cmd;
1421 tmpcmd.action = LFUN_INSET_MODIFY;
1422 // if there is an inset at cursor, see whether it
1424 Inset * inset = cur.nextInset();
1427 inset->dispatch(cur, tmpcmd);
1429 // if it did not work, try the underlying inset.
1430 if (!inset || !cur.result().dispatched()) {
1432 cur.dispatch(tmpcmd);
1435 if (!cur.result().dispatched())
1436 // It did not work too; no action needed.
1438 cur.clearSelection();
1439 processUpdateFlags(Update::Force | Update::FitCursor);
1443 case LFUN_SCREEN_UP:
1444 case LFUN_SCREEN_DOWN: {
1445 Point p = getPos(cur, cur.boundary());
1446 if (p.y_ < 0 || p.y_ > height_) {
1447 // The cursor is off-screen so recenter before proceeding.
1449 p = getPos(cur, cur.boundary());
1451 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1452 ? - height_ : height_);
1453 if (cmd.action == LFUN_SCREEN_UP && scrolled > - height_)
1455 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1456 p = Point(width_, height_);
1458 bool const in_texted = cur.inTexted();
1459 cur.reset(buffer_.inset());
1462 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1463 //FIXME: what to do with cur.x_target()?
1464 bool update = in_texted && cur.bv().checkDepm(cur, old);
1467 processUpdateFlags(Update::Force | Update::FitCursor);
1475 case LFUN_SCREEN_UP_SELECT: {
1476 cur.selHandle(true);
1477 if (isTopScreen()) {
1478 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1482 int y = getPos(cur, cur.boundary()).y_;
1483 int const ymin = y - height_ + defaultRowHeight();
1484 while (y > ymin && cur.up())
1485 y = getPos(cur, cur.boundary()).y_;
1488 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1492 case LFUN_SCREEN_DOWN_SELECT: {
1493 cur.selHandle(true);
1494 if (isBottomScreen()) {
1495 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1499 int y = getPos(cur, cur.boundary()).y_;
1500 int const ymax = y + height_ - defaultRowHeight();
1501 while (y < ymax && cur.down())
1502 y = getPos(cur, cur.boundary()).y_;
1505 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1509 case LFUN_BRANCH_ACTIVATE:
1510 case LFUN_BRANCH_DEACTIVATE:
1511 if (cmd.argument().empty())
1513 buffer_.dispatch(cmd);
1514 processUpdateFlags(Update::Force);
1517 // This could be rewriten using some command like forall <insetname> <command>
1518 // once the insets refactoring is done.
1519 case LFUN_NOTES_MUTATE: {
1520 if (cmd.argument().empty())
1523 if (mutateNotes(cur, cmd.getArg(0), cmd.getArg(1))) {
1524 processUpdateFlags(Update::Force);
1529 case LFUN_ALL_INSETS_TOGGLE: {
1531 string const name = split(to_utf8(cmd.argument()), action, ' ');
1532 InsetCode const inset_code = insetCode(name);
1534 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1536 Inset & inset = cur.buffer()->inset();
1537 InsetIterator it = inset_iterator_begin(inset);
1538 InsetIterator const end = inset_iterator_end(inset);
1539 for (; it != end; ++it) {
1540 if (it->asInsetCollapsable()
1541 && (inset_code == NO_CODE
1542 || inset_code == it->lyxCode())) {
1543 Cursor tmpcur = cur;
1544 tmpcur.pushBackward(*it);
1545 it->dispatch(tmpcur, fr);
1548 processUpdateFlags(Update::Force | Update::FitCursor);
1560 docstring const BufferView::requestSelection()
1562 Cursor & cur = d->cursor_;
1564 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1565 if (!cur.selection()) {
1566 d->xsel_cache_.set = false;
1570 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1571 if (!d->xsel_cache_.set ||
1572 cur.top() != d->xsel_cache_.cursor ||
1573 cur.anchor_.top() != d->xsel_cache_.anchor)
1575 d->xsel_cache_.cursor = cur.top();
1576 d->xsel_cache_.anchor = cur.anchor_.top();
1577 d->xsel_cache_.set = cur.selection();
1578 return cur.selectionAsString(false);
1584 void BufferView::clearSelection()
1586 d->cursor_.clearSelection();
1587 // Clear the selection buffer. Otherwise a subsequent
1588 // middle-mouse-button paste would use the selection buffer,
1589 // not the more current external selection.
1590 cap::clearSelection();
1591 d->xsel_cache_.set = false;
1592 // The buffer did not really change, but this causes the
1593 // redraw we need because we cleared the selection above.
1598 void BufferView::resize(int width, int height)
1600 // Update from work area
1604 // Clear the paragraph height cache.
1605 d->par_height_.clear();
1606 // Redo the metrics.
1611 Inset const * BufferView::getCoveringInset(Text const & text,
1614 TextMetrics & tm = d->text_metrics_[&text];
1615 Inset * inset = tm.checkInsetHit(x, y);
1619 if (!inset->descendable())
1620 // No need to go further down if the inset is not
1624 size_t cell_number = inset->nargs();
1625 // Check all the inner cell.
1626 for (size_t i = 0; i != cell_number; ++i) {
1627 Text const * inner_text = inset->getText(i);
1630 Inset const * inset_deeper =
1631 getCoveringInset(*inner_text, x, y);
1633 return inset_deeper;
1641 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1643 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1645 // This is only called for mouse related events including
1646 // LFUN_FILE_OPEN generated by drag-and-drop.
1647 FuncRequest cmd = cmd0;
1649 Cursor old = cursor();
1651 cur.push(buffer_.inset());
1652 cur.setSelection(d->cursor_.selection());
1654 // Either the inset under the cursor or the
1655 // surrounding Text will handle this event.
1657 // make sure we stay within the screen...
1658 cmd.y = min(max(cmd.y, -1), height_);
1660 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1662 // Get inset under mouse, if there is one.
1663 Inset const * covering_inset =
1664 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1665 if (covering_inset == d->last_inset_)
1666 // Same inset, no need to do anything...
1669 bool need_redraw = false;
1670 // const_cast because of setMouseHover().
1671 Inset * inset = const_cast<Inset *>(covering_inset);
1673 // Remove the hint on the last hovered inset (if any).
1674 need_redraw |= d->last_inset_->setMouseHover(false);
1676 // Highlighted the newly hovered inset (if any).
1677 need_redraw |= inset->setMouseHover(true);
1678 d->last_inset_ = inset;
1682 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1683 << cmd.x << ", " << cmd.y << ")");
1685 d->update_strategy_ = DecorationUpdate;
1687 // This event (moving without mouse click) is not passed further.
1688 // This should be changed if it is further utilized.
1693 // Build temporary cursor.
1694 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1696 // Put anchor at the same position.
1699 cur.beginUndoGroup();
1701 // Try to dispatch to an non-editable inset near this position
1702 // via the temp cursor. If the inset wishes to change the real
1703 // cursor it has to do so explicitly by using
1704 // cur.bv().cursor() = cur; (or similar)
1706 inset->dispatch(cur, cmd);
1708 // Now dispatch to the temporary cursor. If the real cursor should
1709 // be modified, the inset's dispatch has to do so explicitly.
1710 if (!inset || !cur.result().dispatched())
1715 // Notify left insets
1718 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
1720 cursor().fixIfBroken();
1723 // Do we have a selection?
1724 theSelection().haveSelection(cursor().selection());
1726 // If the command has been dispatched,
1727 if (cur.result().dispatched() || cur.result().update())
1728 processUpdateFlags(cur.result().update());
1732 void BufferView::lfunScroll(FuncRequest const & cmd)
1734 string const scroll_type = cmd.getArg(0);
1735 int const scroll_step =
1736 (scroll_type == "line") ? d->scrollbarParameters_.single_step
1737 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
1738 if (scroll_step == 0)
1740 string const scroll_quantity = cmd.getArg(1);
1741 if (scroll_quantity == "up")
1742 scrollUp(scroll_step);
1743 else if (scroll_quantity == "down")
1744 scrollDown(scroll_step);
1746 int const scroll_value = convert<int>(scroll_quantity);
1748 scroll(scroll_step * scroll_value);
1755 int BufferView::minVisiblePart()
1757 return 2 * defaultRowHeight();
1761 int BufferView::scroll(int y)
1764 return scrollDown(y);
1766 return scrollUp(-y);
1771 int BufferView::scrollDown(int offset)
1773 Text * text = &buffer_.text();
1774 TextMetrics & tm = d->text_metrics_[text];
1775 int const ymax = height_ + offset;
1777 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1778 int bottom_pos = last.second->position() + last.second->descent();
1779 if (lyxrc.scroll_below_document)
1780 bottom_pos += height_ - minVisiblePart();
1781 if (last.first + 1 == int(text->paragraphs().size())) {
1782 if (bottom_pos <= height_)
1784 offset = min(offset, bottom_pos - height_);
1787 if (bottom_pos > ymax)
1789 tm.newParMetricsDown();
1791 d->anchor_ypos_ -= offset;
1796 int BufferView::scrollUp(int offset)
1798 Text * text = &buffer_.text();
1799 TextMetrics & tm = d->text_metrics_[text];
1800 int ymin = - offset;
1802 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1803 int top_pos = first.second->position() - first.second->ascent();
1804 if (first.first == 0) {
1807 offset = min(offset, - top_pos);
1812 tm.newParMetricsUp();
1814 d->anchor_ypos_ += offset;
1819 void BufferView::setCursorFromRow(int row)
1824 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1826 d->cursor_.reset(buffer_.inset());
1828 buffer_.text().setCursor(d->cursor_, 0, 0);
1830 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1834 bool BufferView::setCursorFromInset(Inset const * inset)
1836 // are we already there?
1837 if (cursor().nextInset() == inset)
1840 // Inset is not at cursor position. Find it in the document.
1842 cur.reset(buffer().inset());
1843 while (cur && cur.nextInset() != inset)
1854 void BufferView::gotoLabel(docstring const & label)
1856 std::vector<Buffer const *> bufs = buffer().allRelatives();
1857 std::vector<Buffer const *>::iterator it = bufs.begin();
1858 for (; it != bufs.end(); ++it) {
1859 Buffer const * buf = *it;
1862 Toc & toc = buf->tocBackend().toc("label");
1863 TocIterator toc_it = toc.begin();
1864 TocIterator end = toc.end();
1865 for (; toc_it != end; ++toc_it) {
1866 if (label == toc_it->str()) {
1867 dispatch(toc_it->action());
1875 TextMetrics const & BufferView::textMetrics(Text const * t) const
1877 return const_cast<BufferView *>(this)->textMetrics(t);
1881 TextMetrics & BufferView::textMetrics(Text const * t)
1883 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1884 if (tmc_it == d->text_metrics_.end()) {
1885 tmc_it = d->text_metrics_.insert(
1886 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1888 return tmc_it->second;
1892 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1895 return textMetrics(t).parMetrics(pit);
1899 int BufferView::workHeight() const
1905 void BufferView::setCursor(DocIterator const & dit)
1907 size_t const n = dit.depth();
1908 for (size_t i = 0; i < n; ++i)
1909 dit[i].inset().edit(d->cursor_, true);
1911 d->cursor_.setCursor(dit);
1912 d->cursor_.setSelection(false);
1916 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1918 // Would be wrong to delete anything if we have a selection.
1919 if (cur.selection())
1922 bool need_anchor_change = false;
1923 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1924 need_anchor_change);
1926 if (need_anchor_change)
1934 buffer_.updateLabels();
1942 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1944 LASSERT(&cur.bv() == this, /**/);
1947 // this event will clear selection so we save selection for
1948 // persistent selection
1949 cap::saveSelection(cursor());
1951 // Has the cursor just left the inset?
1952 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1954 d->cursor_.fixIfBroken();
1956 // FIXME: shift-mouse selection doesn't work well across insets.
1957 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1959 // do the dEPM magic if needed
1960 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1961 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1962 // the leftinset bool would not be necessary (badcursor instead).
1963 bool update = leftinset;
1964 if (!do_selection && d->cursor_.inTexted())
1965 update |= checkDepm(cur, d->cursor_);
1967 d->cursor_.setCursor(cur);
1968 d->cursor_.boundary(cur.boundary());
1970 d->cursor_.setSelection();
1972 d->cursor_.clearSelection();
1974 d->cursor_.finishUndo();
1975 d->cursor_.setCurrentFont();
1980 void BufferView::putSelectionAt(DocIterator const & cur,
1981 int length, bool backwards)
1983 d->cursor_.clearSelection();
1989 d->cursor_.pos() += length;
1990 d->cursor_.setSelection(d->cursor_, -length);
1992 d->cursor_.setSelection(d->cursor_, length);
1994 // Ensure a redraw happens in any case because the new selection could
1995 // possibly be on the same screen as the previous selection.
1996 processUpdateFlags(Update::Force | Update::FitCursor);
2000 Cursor & BufferView::cursor()
2006 Cursor const & BufferView::cursor() const
2012 pit_type BufferView::anchor_ref() const
2014 return d->anchor_pit_;
2018 bool BufferView::singleParUpdate()
2020 Text & buftext = buffer_.text();
2021 pit_type const bottom_pit = d->cursor_.bottom().pit();
2022 TextMetrics & tm = textMetrics(&buftext);
2023 int old_height = tm.parMetrics(bottom_pit).height();
2025 // make sure inline completion pointer is ok
2026 if (d->inlineCompletionPos_.fixIfBroken())
2027 d->inlineCompletionPos_ = DocIterator();
2029 // In Single Paragraph mode, rebreak only
2030 // the (main text, not inset!) paragraph containing the cursor.
2031 // (if this paragraph contains insets etc., rebreaking will
2032 // recursively descend)
2033 tm.redoParagraph(bottom_pit);
2034 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2035 if (pm.height() != old_height)
2036 // Paragraph height has changed so we cannot proceed to
2037 // the singlePar optimisation.
2040 d->update_strategy_ = SingleParUpdate;
2042 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2043 << " y2: " << pm.position() + pm.descent()
2044 << " pit: " << bottom_pit
2045 << " singlepar: 1");
2050 void BufferView::updateMetrics()
2052 if (height_ == 0 || width_ == 0)
2055 Text & buftext = buffer_.text();
2056 pit_type const npit = int(buftext.paragraphs().size());
2058 // Clear out the position cache in case of full screen redraw,
2059 d->coord_cache_.clear();
2061 // Clear out paragraph metrics to avoid having invalid metrics
2062 // in the cache from paragraphs not relayouted below
2063 // The complete text metrics will be redone.
2064 d->text_metrics_.clear();
2066 TextMetrics & tm = textMetrics(&buftext);
2068 // make sure inline completion pointer is ok
2069 if (d->inlineCompletionPos_.fixIfBroken())
2070 d->inlineCompletionPos_ = DocIterator();
2072 if (d->anchor_pit_ >= npit)
2073 // The anchor pit must have been deleted...
2074 d->anchor_pit_ = npit - 1;
2076 // Rebreak anchor paragraph.
2077 tm.redoParagraph(d->anchor_pit_);
2078 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2081 if (d->anchor_pit_ == 0) {
2082 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2084 // Complete buffer visible? Then it's easy.
2085 if (scrollRange == 0)
2086 d->anchor_ypos_ = anchor_pm.ascent();
2088 // FIXME: Some clever handling needed to show
2089 // the _first_ paragraph up to the top if the cursor is
2090 // in the first line.
2092 anchor_pm.setPosition(d->anchor_ypos_);
2094 LYXERR(Debug::PAINTING, "metrics: "
2095 << " anchor pit = " << d->anchor_pit_
2096 << " anchor ypos = " << d->anchor_ypos_);
2098 // Redo paragraphs above anchor if necessary.
2099 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2100 // We are now just above the anchor paragraph.
2101 pit_type pit1 = d->anchor_pit_ - 1;
2102 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2103 tm.redoParagraph(pit1);
2104 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2106 // Save the paragraph position in the cache.
2111 // Redo paragraphs below the anchor if necessary.
2112 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2113 // We are now just below the anchor paragraph.
2114 pit_type pit2 = d->anchor_pit_ + 1;
2115 for (; pit2 < npit && y2 <= height_; ++pit2) {
2116 tm.redoParagraph(pit2);
2117 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2119 // Save the paragraph position in the cache.
2124 LYXERR(Debug::PAINTING, "Metrics: "
2125 << " anchor pit = " << d->anchor_pit_
2126 << " anchor ypos = " << d->anchor_ypos_
2129 << " pit1 = " << pit1
2130 << " pit2 = " << pit2);
2132 d->update_strategy_ = FullScreenUpdate;
2134 if (lyxerr.debugging(Debug::WORKAREA)) {
2135 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2136 d->coord_cache_.dump();
2141 void BufferView::insertLyXFile(FileName const & fname)
2143 LASSERT(d->cursor_.inTexted(), /**/);
2145 // Get absolute path of file and add ".lyx"
2146 // to the filename if necessary
2147 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2149 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2150 // emit message signal.
2151 message(bformat(_("Inserting document %1$s..."), disp_fn));
2154 Buffer buf("", false);
2155 if (buf.loadLyXFile(filename)) {
2156 ErrorList & el = buffer_.errorList("Parse");
2157 // Copy the inserted document error list into the current buffer one.
2158 el = buf.errorList("Parse");
2159 buffer_.undo().recordUndo(d->cursor_);
2160 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2161 buf.params().documentClassPtr(), el);
2162 res = _("Document %1$s inserted.");
2164 res = _("Could not insert document %1$s");
2169 // emit message signal.
2170 message(bformat(res, disp_fn));
2171 buffer_.errors("Parse");
2175 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2181 // Addup contribution of nested insets, from inside to outside,
2182 // keeping the outer paragraph for a special handling below
2183 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2184 CursorSlice const & sl = dit[i];
2188 // get relative position inside sl.inset()
2189 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2191 // Make relative position inside of the edited inset relative to sl.inset()
2195 // In case of an RTL inset, the edited inset will be positioned to the left
2198 bool boundary_i = boundary && i + 1 == dit.depth();
2199 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2204 // remember width for the case that sl.inset() is positioned in an RTL inset
2205 if (i && dit[i - 1].text()) {
2206 // If this Inset is inside a Text Inset, retrieve the Dimension
2207 // from the containing text instead of using Inset::dimension() which
2208 // might not be implemented.
2209 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2210 // elimination of Inset::dim_ cache. This coordOffset() method needs
2211 // to be rewritten in light of the new design.
2212 Dimension const & dim = parMetrics(dit[i - 1].text(),
2213 dit[i - 1].pit()).insetDimension(&sl.inset());
2216 Dimension const dim = sl.inset().dimension(*this);
2220 //lyxerr << "Cursor::getPos, i: "
2221 // << i << " x: " << xx << " y: " << y << endl;
2224 // Add contribution of initial rows of outermost paragraph
2225 CursorSlice const & sl = dit[0];
2226 TextMetrics const & tm = textMetrics(sl.text());
2227 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2228 LASSERT(!pm.rows().empty(), /**/);
2229 y -= pm.rows()[0].ascent();
2231 // FIXME: document this mess
2233 if (sl.pos() > 0 && dit.depth() == 1) {
2235 if (pos && boundary)
2237 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2238 rend = pm.pos2row(pos);
2240 rend = pm.pos2row(sl.pos());
2242 size_t rend = pm.pos2row(sl.pos());
2244 for (size_t rit = 0; rit != rend; ++rit)
2245 y += pm.rows()[rit].height();
2246 y += pm.rows()[rend].ascent();
2248 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2250 // Make relative position from the nested inset now bufferview absolute.
2251 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2254 // In the RTL case place the nested inset at the left of the cursor in
2255 // the outer paragraph
2256 bool boundary_1 = boundary && 1 == dit.depth();
2257 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2265 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2267 if (!paragraphVisible(dit))
2268 return Point(-1, -1);
2270 CursorSlice const & bot = dit.bottom();
2271 TextMetrics const & tm = textMetrics(bot.text());
2273 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2274 p.y_ += tm.parMetrics(bot.pit()).position();
2279 bool BufferView::paragraphVisible(DocIterator const & dit) const
2281 CursorSlice const & bot = dit.bottom();
2282 TextMetrics const & tm = textMetrics(bot.text());
2284 return tm.contains(bot.pit());
2288 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2290 Cursor const & cur = cursor();
2291 Font const font = cur.getFont();
2292 frontend::FontMetrics const & fm = theFontMetrics(font);
2293 int const asc = fm.maxAscent();
2294 int const des = fm.maxDescent();
2296 p = getPos(cur, cur.boundary());
2301 bool BufferView::cursorInView(Point const & p, int h) const
2303 Cursor const & cur = cursor();
2304 // does the cursor touch the screen ?
2305 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2311 void BufferView::draw(frontend::Painter & pain)
2313 if (height_ == 0 || width_ == 0)
2315 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2317 Text & text = buffer_.text();
2318 TextMetrics const & tm = d->text_metrics_[&text];
2319 int const y = tm.first().second->position();
2320 PainterInfo pi(this, pain);
2322 switch (d->update_strategy_) {
2324 case NoScreenUpdate:
2325 // If no screen painting is actually needed, only some the different
2326 // coordinates of insets and paragraphs needs to be updated.
2327 pi.full_repaint = true;
2328 pi.pain.setDrawingEnabled(false);
2332 case SingleParUpdate:
2333 pi.full_repaint = false;
2334 // In general, only the current row of the outermost paragraph
2335 // will be redrawn. Particular cases where selection spans
2336 // multiple paragraph are correctly detected in TextMetrics.
2340 case DecorationUpdate:
2341 // FIXME: We should also distinguish DecorationUpdate to avoid text
2342 // drawing if possible. This is not possible to do easily right now
2343 // because of the single backing pixmap.
2345 case FullScreenUpdate:
2346 // The whole screen, including insets, will be refreshed.
2347 pi.full_repaint = true;
2349 // Clear background.
2350 pain.fillRectangle(0, 0, width_, height_,
2351 pi.backgroundColor(&buffer_.inset()));
2356 // and possibly grey out below
2357 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2358 int const y2 = lastpm.second->position() + lastpm.second->descent();
2360 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2363 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2365 // The scrollbar needs an update.
2368 // Normalize anchor for next time
2369 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2370 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2371 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2372 ParagraphMetrics const & pm = tm.parMetrics(pit);
2373 if (pm.position() + pm.descent() > 0) {
2374 d->anchor_pit_ = pit;
2375 d->anchor_ypos_ = pm.position();
2379 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2380 << " anchor ypos = " << d->anchor_ypos_);
2384 void BufferView::message(docstring const & msg)
2387 d->gui_->message(msg);
2391 void BufferView::showDialog(string const & name)
2394 d->gui_->showDialog(name, string());
2398 void BufferView::showDialog(string const & name,
2399 string const & data, Inset * inset)
2402 d->gui_->showDialog(name, data, inset);
2406 void BufferView::updateDialog(string const & name, string const & data)
2409 d->gui_->updateDialog(name, data);
2413 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2419 // FIXME: Move this out of BufferView again
2420 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2422 if (!fname.isReadableFile()) {
2423 docstring const error = from_ascii(strerror(errno));
2424 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2425 docstring const text =
2426 bformat(_("Could not read the specified document\n"
2427 "%1$s\ndue to the error: %2$s"), file, error);
2428 Alert::error(_("Could not read file"), text);
2432 if (!fname.isReadableFile()) {
2433 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2434 docstring const text =
2435 bformat(_("%1$s\n is not readable."), file);
2436 Alert::error(_("Could not open file"), text);
2440 // FIXME UNICODE: We don't know the encoding of the file
2441 docstring file_content = fname.fileContents("UTF-8");
2442 if (file_content.empty()) {
2443 Alert::error(_("Reading not UTF-8 encoded file"),
2444 _("The file is not UTF-8 encoded.\n"
2445 "It will be read as local 8Bit-encoded.\n"
2446 "If this does not give the correct result\n"
2447 "then please change the encoding of the file\n"
2448 "to UTF-8 with a program other than LyX.\n"));
2449 file_content = fname.fileContents("local8bit");
2452 return normalize_c(file_content);
2456 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2458 docstring const tmpstr = contentsOfPlaintextFile(f);
2463 Cursor & cur = cursor();
2464 cap::replaceSelection(cur);
2465 buffer_.undo().recordUndo(cur);
2467 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2469 cur.innerText()->insertStringAsLines(cur, tmpstr);
2476 docstring const & BufferView::inlineCompletion() const
2478 return d->inlineCompletion_;
2482 size_t const & BufferView::inlineCompletionUniqueChars() const
2484 return d->inlineCompletionUniqueChars_;
2488 DocIterator const & BufferView::inlineCompletionPos() const
2490 return d->inlineCompletionPos_;
2494 bool samePar(DocIterator const & a, DocIterator const & b)
2496 if (a.empty() && b.empty())
2498 if (a.empty() || b.empty())
2500 if (a.depth() != b.depth())
2502 return &a.innerParagraph() == &b.innerParagraph();
2506 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2507 docstring const & completion, size_t uniqueChars)
2509 uniqueChars = min(completion.size(), uniqueChars);
2510 bool changed = d->inlineCompletion_ != completion
2511 || d->inlineCompletionUniqueChars_ != uniqueChars;
2512 bool singlePar = true;
2513 d->inlineCompletion_ = completion;
2514 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2516 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2519 DocIterator const & old = d->inlineCompletionPos_;
2521 //lyxerr << "inlineCompletionPos changed" << std::endl;
2522 // old or pos are in another paragraph?
2523 if ((!samePar(cur, pos) && !pos.empty())
2524 || (!samePar(cur, old) && !old.empty())) {
2526 //lyxerr << "different paragraph" << std::endl;
2528 d->inlineCompletionPos_ = pos;
2533 if (singlePar && !(cur.disp_.update() & Update::Force))
2534 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2536 cur.updateFlags(cur.disp_.update() | Update::Force);