3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
19 #include "BranchList.h"
21 #include "buffer_funcs.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "CoordCache.h"
26 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
34 #include "InsetIterator.h"
36 #include "LaTeXFeatures.h"
37 #include "LayoutFile.h"
40 #include "LyXAction.h"
44 #include "MetricsInfo.h"
45 #include "Paragraph.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
50 #include "TextClass.h"
51 #include "TextMetrics.h"
53 #include "TocBackend.h"
55 #include "WordLangTuple.h"
57 #include "insets/InsetBibtex.h"
58 #include "insets/InsetCommand.h" // ChangeRefs
59 #include "insets/InsetExternal.h"
60 #include "insets/InsetGraphics.h"
61 #include "insets/InsetNote.h"
62 #include "insets/InsetRef.h"
63 #include "insets/InsetText.h"
65 #include "frontends/alert.h"
66 #include "frontends/Application.h"
67 #include "frontends/Delegates.h"
68 #include "frontends/FontMetrics.h"
69 #include "frontends/Painter.h"
70 #include "frontends/Selection.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/lassert.h"
78 #include "support/lstrings.h"
79 #include "support/Package.h"
80 #include "support/types.h"
90 using namespace lyx::support;
94 namespace Alert = frontend::Alert;
98 /// Return an inset of this class if it exists at the current cursor position
100 T * getInsetByCode(Cursor const & cur, InsetCode code)
102 DocIterator it = cur;
103 Inset * inset = it.nextInset();
104 if (inset && inset->lyxCode() == code)
105 return static_cast<T*>(inset);
109 /// Note that comparing contents can only be used for InsetCommand
110 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
111 docstring const & contents)
113 DocIterator tmpdit = dit;
116 Inset const * inset = tmpdit.nextInset();
118 bool const valid_code = std::find(codes.begin(), codes.end(),
119 inset->lyxCode()) != codes.end();
120 InsetCommand const * ic = inset->asInsetCommand();
121 bool const same_or_no_contents = contents.empty()
122 || (ic && (ic->getFirstNonOptParam() == contents));
124 if (valid_code && same_or_no_contents) {
129 tmpdit.forwardInset();
136 /// Looks for next inset with one of the given codes.
137 /// Note that same_content can only be used for InsetCommand
138 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
142 DocIterator tmpdit = dit;
143 tmpdit.forwardInset();
147 Inset const * inset = tmpdit.nextInset();
148 if (same_content && inset) {
149 InsetCommand const * ic = inset->asInsetCommand();
151 bool const valid_code = std::find(codes.begin(), codes.end(),
152 ic->lyxCode()) != codes.end();
154 contents = ic->getFirstNonOptParam();
158 if (!findNextInset(tmpdit, codes, contents)) {
159 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
160 Inset * inset = &tmpdit.bottom().inset();
161 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
162 if (!findNextInset(tmpdit, codes, contents))
174 /// Looks for next inset with the given code
175 void findInset(DocIterator & dit, InsetCode code, bool same_content)
177 findInset(dit, vector<InsetCode>(1, code), same_content);
181 /// Moves cursor to the next inset with one of the given codes.
182 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
185 Cursor tmpcur = bv->cursor();
186 if (!findInset(tmpcur, codes, same_content)) {
187 bv->cursor().message(_("No more insets"));
191 tmpcur.clearSelection();
192 bv->setCursor(tmpcur);
197 /// Moves cursor to the next inset with given code.
198 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
200 gotoInset(bv, vector<InsetCode>(1, code), same_content);
204 /// A map from a Text to the associated text metrics
205 typedef map<Text const *, TextMetrics> TextMetricsCache;
207 enum ScreenUpdateStrategy {
217 /////////////////////////////////////////////////////////////////////
221 /////////////////////////////////////////////////////////////////////
223 struct BufferView::Private
225 Private(BufferView & bv): wh_(0), cursor_(bv),
226 anchor_pit_(0), anchor_ypos_(0),
227 inlineCompletionUniqueChars_(0),
228 last_inset_(0), clickable_inset_(false),
229 mouse_position_cache_(),
230 bookmark_edit_position_(-1), gui_(0)
234 ScrollbarParameters scrollbarParameters_;
236 ScreenUpdateStrategy update_strategy_;
238 CoordCache coord_cache_;
240 /// Estimated average par height for scrollbar.
242 /// this is used to handle XSelection events in the right manner.
251 pit_type anchor_pit_;
255 vector<int> par_height_;
258 DocIterator inlineCompletionPos_;
260 docstring inlineCompletion_;
262 size_t inlineCompletionUniqueChars_;
264 /// keyboard mapping object.
267 /// last visited inset.
268 /** kept to send setMouseHover(false).
269 * Not owned, so don't delete.
271 Inset const * last_inset_;
272 /// are we hovering something that we can click
273 bool clickable_inset_;
275 /// position of the mouse at the time of the last mouse move
276 /// This is used to update the hovering status of inset in
277 /// cases where the buffer is scrolled, but the mouse didn't move.
278 Point mouse_position_cache_;
280 // cache for id of the paragraph which was edited the last time
281 int bookmark_edit_position_;
283 mutable TextMetricsCache text_metrics_;
286 /** Not owned, so don't delete.
288 frontend::GuiBufferViewDelegate * gui_;
290 /// Cache for Find Next
291 FuncRequest search_request_cache_;
294 map<string, Inset *> edited_insets_;
298 BufferView::BufferView(Buffer & buf)
299 : width_(0), height_(0), full_screen_(false), buffer_(buf),
300 d(new Private(*this))
302 d->xsel_cache_.set = false;
303 d->intl_.initKeyMapper(lyxrc.use_kbmap);
305 d->cursor_.setBuffer(&buf);
306 d->cursor_.push(buffer_.inset());
307 d->cursor_.resetAnchor();
308 d->cursor_.setCurrentFont();
310 buffer_.updatePreviews();
314 BufferView::~BufferView()
316 // current buffer is going to be switched-off, save cursor pos
317 // Ideally, the whole cursor stack should be saved, but session
318 // currently can only handle bottom (whole document) level pit and pos.
319 // That is to say, if a cursor is in a nested inset, it will be
320 // restore to the left of the top level inset.
321 LastFilePosSection::FilePos fp;
322 fp.pit = d->cursor_.bottom().pit();
323 fp.pos = d->cursor_.bottom().pos();
324 theSession().lastFilePos().save(buffer_.fileName(), fp);
327 d->last_inset_->setMouseHover(this, false);
333 int BufferView::rightMargin() const
335 // The additional test for the case the outliner is opened.
337 !lyxrc.full_screen_limit ||
338 width_ < lyxrc.full_screen_width + 20)
341 return (width_ - lyxrc.full_screen_width) / 2;
345 int BufferView::leftMargin() const
347 return rightMargin();
351 bool BufferView::isTopScreen() const
353 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
357 bool BufferView::isBottomScreen() const
359 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
363 Intl & BufferView::getIntl()
369 Intl const & BufferView::getIntl() const
375 CoordCache & BufferView::coordCache()
377 return d->coord_cache_;
381 CoordCache const & BufferView::coordCache() const
383 return d->coord_cache_;
387 Buffer & BufferView::buffer()
393 Buffer const & BufferView::buffer() const
399 bool BufferView::fitCursor()
401 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
402 frontend::FontMetrics const & fm =
403 theFontMetrics(d->cursor_.getFont().fontInfo());
404 int const asc = fm.maxAscent();
405 int const des = fm.maxDescent();
406 Point const p = getPos(d->cursor_);
407 if (p.y_ - asc >= 0 && p.y_ + des < height_)
414 void BufferView::processUpdateFlags(Update::flags flags)
416 // This is close to a hot-path.
417 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
418 << "[fitcursor = " << (flags & Update::FitCursor)
419 << ", forceupdate = " << (flags & Update::Force)
420 << ", singlepar = " << (flags & Update::SinglePar)
421 << "] buffer: " << &buffer_);
423 // FIXME Does this really need doing here? It's done in updateBuffer, and
424 // if the Buffer doesn't need updating, then do the macros?
425 buffer_.updateMacros();
427 // Now do the first drawing step if needed. This consists on updating
428 // the CoordCache in updateMetrics().
429 // The second drawing step is done in WorkArea::redraw() if needed.
431 // Case when no explicit update is requested.
433 // no need to redraw anything.
434 d->update_strategy_ = NoScreenUpdate;
438 if (flags == Update::Decoration) {
439 d->update_strategy_ = DecorationUpdate;
440 buffer_.changed(false);
444 if (flags == Update::FitCursor
445 || flags == (Update::Decoration | Update::FitCursor)) {
446 // tell the frontend to update the screen if needed.
451 if (flags & Update::Decoration) {
452 d->update_strategy_ = DecorationUpdate;
453 buffer_.changed(false);
456 // no screen update is needed.
457 d->update_strategy_ = NoScreenUpdate;
461 bool const full_metrics = flags & Update::Force || !singleParUpdate();
464 // We have to update the full screen metrics.
467 if (!(flags & Update::FitCursor)) {
468 // Nothing to do anymore. Trigger a redraw and return
469 buffer_.changed(false);
473 // updateMetrics() does not update paragraph position
474 // This is done at draw() time. So we need a redraw!
475 buffer_.changed(false);
478 // The cursor is off screen so ensure it is visible.
483 updateHoveredInset();
487 void BufferView::updateScrollbar()
489 if (height_ == 0 && width_ == 0)
492 // We prefer fixed size line scrolling.
493 d->scrollbarParameters_.single_step = defaultRowHeight();
494 // We prefer full screen page scrolling.
495 d->scrollbarParameters_.page_step = height_;
497 Text & t = buffer_.text();
498 TextMetrics & tm = d->text_metrics_[&t];
500 LYXERR(Debug::GUI, " Updating scrollbar: height: "
501 << t.paragraphs().size()
502 << " curr par: " << d->cursor_.bottom().pit()
503 << " default height " << defaultRowHeight());
505 size_t const parsize = t.paragraphs().size();
506 if (d->par_height_.size() != parsize) {
507 d->par_height_.clear();
508 // FIXME: We assume a default paragraph height of 2 rows. This
509 // should probably be pondered with the screen width.
510 d->par_height_.resize(parsize, defaultRowHeight() * 2);
513 // Look at paragraph heights on-screen
514 pair<pit_type, ParagraphMetrics const *> first = tm.first();
515 pair<pit_type, ParagraphMetrics const *> last = tm.last();
516 for (pit_type pit = first.first; pit <= last.first; ++pit) {
517 d->par_height_[pit] = tm.parMetrics(pit).height();
518 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
519 << d->par_height_[pit]);
522 int top_pos = first.second->position() - first.second->ascent();
523 int bottom_pos = last.second->position() + last.second->descent();
524 bool first_visible = first.first == 0 && top_pos >= 0;
525 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
526 if (first_visible && last_visible) {
527 d->scrollbarParameters_.min = 0;
528 d->scrollbarParameters_.max = 0;
532 d->scrollbarParameters_.min = top_pos;
533 for (size_t i = 0; i != size_t(first.first); ++i)
534 d->scrollbarParameters_.min -= d->par_height_[i];
535 d->scrollbarParameters_.max = bottom_pos;
536 for (size_t i = last.first + 1; i != parsize; ++i)
537 d->scrollbarParameters_.max += d->par_height_[i];
539 d->scrollbarParameters_.position = 0;
540 // The reference is the top position so we remove one page.
541 if (lyxrc.scroll_below_document)
542 d->scrollbarParameters_.max -= minVisiblePart();
544 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
548 ScrollbarParameters const & BufferView::scrollbarParameters() const
550 return d->scrollbarParameters_;
554 docstring BufferView::toolTip(int x, int y) const
556 // Get inset under mouse, if there is one.
557 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
559 // No inset, no tooltip...
561 return covering_inset->toolTip(*this, x, y);
565 docstring BufferView::contextMenu(int x, int y) const
567 //If there is a selection, return the containing inset menu
568 if (d->cursor_.selection())
569 return d->cursor_.inset().contextMenu(*this, x, y);
571 // Get inset under mouse, if there is one.
572 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
574 return covering_inset->contextMenu(*this, x, y);
576 return buffer_.inset().contextMenu(*this, x, y);
580 void BufferView::scrollDocView(int value, bool update)
582 int const offset = value - d->scrollbarParameters_.position;
584 // No scrolling at all? No need to redraw anything
588 // If the offset is less than 2 screen height, prefer to scroll instead.
589 if (abs(offset) <= 2 * height_) {
590 d->anchor_ypos_ -= offset;
591 buffer_.changed(true);
592 updateHoveredInset();
596 // cut off at the top
597 if (value <= d->scrollbarParameters_.min) {
598 DocIterator dit = doc_iterator_begin(&buffer_);
599 showCursor(dit, false, update);
600 LYXERR(Debug::SCROLLING, "scroll to top");
604 // cut off at the bottom
605 if (value >= d->scrollbarParameters_.max) {
606 DocIterator dit = doc_iterator_end(&buffer_);
608 showCursor(dit, false, update);
609 LYXERR(Debug::SCROLLING, "scroll to bottom");
613 // find paragraph at target position
614 int par_pos = d->scrollbarParameters_.min;
616 for (; i != int(d->par_height_.size()); ++i) {
617 par_pos += d->par_height_[i];
618 if (par_pos >= value)
622 if (par_pos < value) {
623 // It seems we didn't find the correct pit so stay on the safe side and
625 LYXERR0("scrolling position not found!");
626 scrollDocView(d->scrollbarParameters_.max, update);
630 DocIterator dit = doc_iterator_begin(&buffer_);
632 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
633 showCursor(dit, false, update);
637 // FIXME: this method is not working well.
638 void BufferView::setCursorFromScrollbar()
640 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
642 int const height = 2 * defaultRowHeight();
643 int const first = height;
644 int const last = height_ - height;
646 Cursor const & oldcur = d->cursor_;
648 switch (cursorStatus(oldcur)) {
656 int const y = getPos(oldcur).y_;
657 newy = min(last, max(y, first));
661 // We reset the cursor because cursorStatus() does not
662 // work when the cursor is within mathed.
665 tm.setCursorFromCoordinates(cur, 0, newy);
667 // update the bufferview cursor and notify insets
668 // FIXME: Care about the d->cursor_ flags to redraw if needed
669 Cursor old = d->cursor_;
671 // the DEPM call in mouseSetCursor() might have destroyed the
672 // paragraph the cursor is in.
673 bool badcursor = old.fixIfBroken();
674 badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
676 d->cursor_.fixIfBroken();
680 Change const BufferView::getCurrentChange() const
682 if (!d->cursor_.selection())
683 return Change(Change::UNCHANGED);
685 DocIterator dit = d->cursor_.selectionBegin();
686 return dit.paragraph().lookupChange(dit.pos());
690 // this could be used elsewhere as well?
691 // FIXME: This does not work within mathed!
692 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
694 Point const p = getPos(dit);
697 if (p.y_ > workHeight())
703 void BufferView::bookmarkEditPosition()
705 // Don't eat cpu time for each keystroke
706 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
709 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
713 void BufferView::saveBookmark(unsigned int idx)
715 // tentatively save bookmark, id and pos will be used to
716 // acturately locate a bookmark in a 'live' lyx session.
717 // pit and pos will be updated with bottom level pit/pos
719 if (!buffer_.isInternal()) {
720 theSession().bookmarks().save(
722 d->cursor_.bottom().pit(),
723 d->cursor_.bottom().pos(),
724 d->cursor_.paragraph().id(),
729 // emit message signal.
730 message(_("Save bookmark"));
735 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
736 int top_id, pos_type top_pos)
738 bool success = false;
741 d->cursor_.clearSelection();
743 // if a valid par_id is given, try it first
744 // This is the case for a 'live' bookmark when unique paragraph ID
745 // is used to track bookmarks.
747 dit = buffer_.getParFromID(top_id);
749 dit.pos() = min(dit.paragraph().size(), top_pos);
750 // Some slices of the iterator may not be
751 // reachable (e.g. closed collapsable inset)
752 // so the dociterator may need to be
753 // shortened. Otherwise, setCursor may crash
754 // lyx when the cursor can not be set to these
756 size_t const n = dit.depth();
757 for (size_t i = 0; i < n; ++i)
758 if (!dit[i].inset().editable()) {
766 // if top_id == 0, or searching through top_id failed
767 // This is the case for a 'restored' bookmark when only bottom
768 // (document level) pit was saved. Because of this, bookmark
769 // restoration is inaccurate. If a bookmark was within an inset,
770 // it will be restored to the left of the outmost inset that contains
772 if (bottom_pit < int(buffer_.paragraphs().size())) {
773 dit = doc_iterator_begin(&buffer_);
775 dit.pit() = bottom_pit;
776 dit.pos() = min(bottom_pos, dit.paragraph().size());
781 // Note: only bottom (document) level pit is set.
783 // set the current font.
784 d->cursor_.setCurrentFont();
785 // To center the screen on this new position we need the
786 // paragraph position which is computed at draw() time.
787 // So we need a redraw!
788 buffer_.changed(false);
797 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
799 if (lyxrc.rtl_support) {
800 if (d->cursor_.real_current_font.isRightToLeft()) {
801 if (d->intl_.keymap == Intl::PRIMARY)
802 d->intl_.keyMapSec();
804 if (d->intl_.keymap == Intl::SECONDARY)
805 d->intl_.keyMapPrim();
809 d->intl_.getTransManager().translateAndInsert(c, t, cur);
813 int BufferView::workWidth() const
819 void BufferView::recenter()
821 showCursor(d->cursor_, true, true);
825 void BufferView::showCursor()
827 showCursor(d->cursor_, false, true);
831 void BufferView::showCursor(DocIterator const & dit,
832 bool recenter, bool update)
834 if (scrollToCursor(dit, recenter) && update) {
835 buffer_.changed(true);
836 updateHoveredInset();
841 void BufferView::scrollToCursor()
843 if (scrollToCursor(d->cursor_, false)) {
844 buffer_.changed(true);
845 updateHoveredInset();
850 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
852 // We are not properly started yet, delay until resizing is
857 LYXERR(Debug::SCROLLING, "recentering!");
859 CursorSlice const & bot = dit.bottom();
860 TextMetrics & tm = d->text_metrics_[bot.text()];
862 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
863 int bot_pit = bot.pit();
864 if (bot_pit > max_pit) {
865 // FIXME: Why does this happen?
866 LYXERR0("bottom pit is greater that max pit: "
867 << bot_pit << " > " << max_pit);
871 if (bot_pit == tm.first().first - 1)
872 tm.newParMetricsUp();
873 else if (bot_pit == tm.last().first + 1)
874 tm.newParMetricsDown();
876 if (tm.contains(bot_pit)) {
877 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
878 LASSERT(!pm.rows().empty(), /**/);
879 // FIXME: smooth scrolling doesn't work in mathed.
880 CursorSlice const & cs = dit.innerTextSlice();
881 int offset = coordOffset(dit).y_;
882 int ypos = pm.position() + offset;
883 Dimension const & row_dim =
884 pm.getRow(cs.pos(), dit.boundary()).dimension();
887 scrolled = scroll(ypos - height_/2);
889 // We try to visualize the whole row, if the row height is larger than
890 // the screen height, we scroll to a heuristic value of height_ / 4.
891 // FIXME: This heuristic value should be replaced by a recursive search
892 // for a row in the inset that can be visualized completely.
893 else if (row_dim.height() > height_) {
894 if (ypos < defaultRowHeight())
895 scrolled = scroll(ypos - height_ / 4);
896 else if (ypos > height_ - defaultRowHeight())
897 scrolled = scroll(ypos - 3 * height_ / 4);
900 // If the top part of the row falls of the screen, we scroll
901 // up to align the top of the row with the top of the screen.
902 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
903 int ynew = row_dim.ascent();
904 scrolled = scrollUp(ynew - ypos);
907 // If the bottom of the row falls of the screen, we scroll down.
908 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
909 int ynew = height_ - row_dim.descent();
910 scrolled = scrollDown(ypos - ynew);
913 // else, nothing to do, the cursor is already visible so we just return.
914 return scrolled != 0;
917 // fix inline completion position
918 if (d->inlineCompletionPos_.fixIfBroken())
919 d->inlineCompletionPos_ = DocIterator();
921 tm.redoParagraph(bot_pit);
922 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
923 int offset = coordOffset(dit).y_;
925 d->anchor_pit_ = bot_pit;
926 CursorSlice const & cs = dit.innerTextSlice();
927 Dimension const & row_dim =
928 pm.getRow(cs.pos(), dit.boundary()).dimension();
931 d->anchor_ypos_ = height_/2;
932 else if (d->anchor_pit_ == 0)
933 d->anchor_ypos_ = offset + pm.ascent();
934 else if (d->anchor_pit_ == max_pit)
935 d->anchor_ypos_ = height_ - offset - row_dim.descent();
936 else if (offset > height_)
937 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
939 d->anchor_ypos_ = defaultRowHeight() * 2;
945 void BufferView::updateDocumentClass(DocumentClass const * const olddc)
947 message(_("Converting document to new document class..."));
949 StableDocIterator backcur(d->cursor_);
950 ErrorList & el = buffer_.errorList("Class Switch");
951 cap::switchBetweenClasses(
952 olddc, buffer_.params().documentClassPtr(),
953 static_cast<InsetText &>(buffer_.inset()), el);
955 setCursor(backcur.asDocIterator(&buffer_));
957 buffer_.errors("Class Switch");
960 /** Return the change status at cursor position, taking in account the
961 * status at each level of the document iterator (a table in a deleted
962 * footnote is deleted).
963 * When \param outer is true, the top slice is not looked at.
965 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
967 size_t const depth = dit.depth() - (outer ? 1 : 0);
969 for (size_t i = 0 ; i < depth ; ++i) {
970 CursorSlice const & slice = dit[i];
971 if (!slice.inset().inMathed()
972 && slice.pos() < slice.paragraph().size()) {
973 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
974 if (ch != Change::UNCHANGED)
978 return Change::UNCHANGED;
982 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
984 FuncCode const act = cmd.action();
986 // Can we use a readonly buffer?
987 if (buffer_.isReadonly()
988 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
989 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
990 flag.message(from_utf8(N_("Document is read-only")));
991 flag.setEnabled(false);
995 // Are we in a DELETED change-tracking region?
996 if (lookupChangeType(d->cursor_, true) == Change::DELETED
997 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
998 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
999 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1000 flag.setEnabled(false);
1004 Cursor & cur = d->cursor_;
1006 if (cur.getStatus(cmd, flag))
1011 // FIXME: This is a bit problematic because we don't check if this is
1012 // a document BufferView or not for these LFUNs. We probably have to
1013 // dispatch both to currentBufferView() and, if that fails,
1014 // to documentBufferView(); same as we do now for current Buffer and
1015 // document Buffer. Ideally those LFUN should go to Buffer as they
1016 // operate on the full Buffer and the cursor is only needed either for
1017 // an Undo record or to restore a cursor position. But we don't know
1018 // how to do that inside Buffer of course.
1019 case LFUN_BUFFER_PARAMS_APPLY:
1020 case LFUN_LAYOUT_MODULES_CLEAR:
1021 case LFUN_LAYOUT_MODULE_ADD:
1022 case LFUN_LAYOUT_RELOAD:
1023 case LFUN_TEXTCLASS_APPLY:
1024 case LFUN_TEXTCLASS_LOAD:
1025 flag.setEnabled(!buffer_.isReadonly());
1029 // We do not use the LyXAction flag for readonly because Undo sets the
1030 // buffer clean/dirty status by itself.
1031 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1034 // We do not use the LyXAction flag for readonly because Redo sets the
1035 // buffer clean/dirty status by itself.
1036 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1038 case LFUN_FILE_INSERT:
1039 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1040 case LFUN_FILE_INSERT_PLAINTEXT:
1041 case LFUN_BOOKMARK_SAVE:
1042 // FIXME: Actually, these LFUNS should be moved to Text
1043 flag.setEnabled(cur.inTexted());
1046 case LFUN_FONT_STATE:
1047 case LFUN_LABEL_INSERT:
1048 case LFUN_INFO_INSERT:
1049 case LFUN_PARAGRAPH_GOTO:
1050 case LFUN_NOTE_NEXT:
1051 case LFUN_REFERENCE_NEXT:
1052 case LFUN_WORD_FIND:
1053 case LFUN_WORD_FIND_FORWARD:
1054 case LFUN_WORD_FIND_BACKWARD:
1055 case LFUN_WORD_FINDADV:
1056 case LFUN_WORD_REPLACE:
1059 case LFUN_MARK_TOGGLE:
1060 case LFUN_SCREEN_RECENTER:
1061 case LFUN_SCREEN_SHOW_CURSOR:
1062 case LFUN_BIBTEX_DATABASE_ADD:
1063 case LFUN_BIBTEX_DATABASE_DEL:
1064 case LFUN_STATISTICS:
1065 case LFUN_BRANCH_ADD_INSERT:
1066 case LFUN_KEYMAP_OFF:
1067 case LFUN_KEYMAP_PRIMARY:
1068 case LFUN_KEYMAP_SECONDARY:
1069 case LFUN_KEYMAP_TOGGLE:
1070 flag.setEnabled(true);
1073 case LFUN_LABEL_GOTO: {
1074 flag.setEnabled(!cmd.argument().empty()
1075 || getInsetByCode<InsetRef>(cur, REF_CODE));
1079 case LFUN_CHANGES_TRACK:
1080 flag.setEnabled(true);
1081 flag.setOnOff(buffer_.params().trackChanges);
1084 case LFUN_CHANGES_OUTPUT:
1085 flag.setEnabled(true);
1086 flag.setOnOff(buffer_.params().outputChanges);
1089 case LFUN_CHANGES_MERGE:
1090 case LFUN_CHANGE_NEXT:
1091 case LFUN_CHANGE_PREVIOUS:
1092 case LFUN_ALL_CHANGES_ACCEPT:
1093 case LFUN_ALL_CHANGES_REJECT:
1094 // TODO: context-sensitive enabling of LFUNs
1095 // In principle, these command should only be enabled if there
1096 // is a change in the document. However, without proper
1097 // optimizations, this will inevitably result in poor performance.
1098 flag.setEnabled(true);
1101 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1102 flag.setOnOff(buffer_.params().compressed);
1106 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
1107 flag.setOnOff(buffer_.params().output_sync);
1111 case LFUN_SCREEN_UP:
1112 case LFUN_SCREEN_DOWN:
1114 case LFUN_SCREEN_UP_SELECT:
1115 case LFUN_SCREEN_DOWN_SELECT:
1116 case LFUN_INSET_FORALL:
1117 flag.setEnabled(true);
1120 case LFUN_LAYOUT_TABULAR:
1121 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1125 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1128 case LFUN_LAYOUT_PARAGRAPH:
1129 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1132 case LFUN_DIALOG_SHOW_NEW_INSET:
1133 // FIXME: this is wrong, but I do not understand the
1135 if (cur.inset().lyxCode() == CAPTION_CODE)
1136 return cur.inset().getStatus(cur, cmd, flag);
1137 // FIXME we should consider passthru paragraphs too.
1138 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1141 case LFUN_CITATION_INSERT: {
1142 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1143 // FIXME: This could turn in a recursive hell.
1144 // Shouldn't we use Buffer::getStatus() instead?
1145 flag.setEnabled(lyx::getStatus(fr).enabled());
1148 case LFUN_INSET_APPLY: {
1149 string const name = cmd.getArg(0);
1150 Inset * inset = editedInset(name);
1152 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1153 if (!inset->getStatus(cur, fr, flag)) {
1154 // Every inset is supposed to handle this
1155 LASSERT(false, break);
1158 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1159 flag = lyx::getStatus(fr);
1172 Inset * BufferView::editedInset(string const & name) const
1174 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1175 return it == d->edited_insets_.end() ? 0 : it->second;
1179 void BufferView::editInset(string const & name, Inset * inset)
1181 d->edited_insets_[name] = inset;
1185 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1187 //lyxerr << [ cmd = " << cmd << "]" << endl;
1189 // Make sure that the cached BufferView is correct.
1190 LYXERR(Debug::ACTION, " action[" << cmd.action() << ']'
1191 << " arg[" << to_utf8(cmd.argument()) << ']'
1192 << " x[" << cmd.x() << ']'
1193 << " y[" << cmd.y() << ']'
1194 << " button[" << cmd.button() << ']');
1196 string const argument = to_utf8(cmd.argument());
1197 Cursor & cur = d->cursor_;
1199 // Don't dispatch function that does not apply to internal buffers.
1200 if (buffer_.isInternal()
1201 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1204 // We'll set this back to false if need be.
1205 bool dispatched = true;
1206 buffer_.undo().beginUndoGroup();
1208 FuncCode const act = cmd.action();
1211 case LFUN_BUFFER_PARAMS_APPLY: {
1212 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1213 cur.recordUndoFullDocument();
1214 istringstream ss(to_utf8(cmd.argument()));
1217 int const unknown_tokens = buffer_.readHeader(lex);
1218 if (unknown_tokens != 0) {
1219 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1220 << unknown_tokens << " unknown token"
1221 << (unknown_tokens == 1 ? "" : "s"));
1223 updateDocumentClass(oldClass);
1225 // We are most certainly here because of a change in the document
1226 // It is then better to make sure that all dialogs are in sync with
1227 // current document settings.
1228 dr.screenUpdate(Update::Force | Update::FitCursor);
1229 dr.forceBufferUpdate();
1233 case LFUN_LAYOUT_MODULES_CLEAR: {
1234 DocumentClass const * const oldClass =
1235 buffer_.params().documentClassPtr();
1236 cur.recordUndoFullDocument();
1237 buffer_.params().clearLayoutModules();
1238 buffer_.params().makeDocumentClass();
1239 updateDocumentClass(oldClass);
1240 dr.screenUpdate(Update::Force);
1241 dr.forceBufferUpdate();
1245 case LFUN_LAYOUT_MODULE_ADD: {
1246 BufferParams const & params = buffer_.params();
1247 if (!params.moduleCanBeAdded(argument)) {
1248 LYXERR0("Module `" << argument <<
1249 "' cannot be added due to failed requirements or "
1250 "conflicts with installed modules.");
1253 DocumentClass const * const oldClass = params.documentClassPtr();
1254 cur.recordUndoFullDocument();
1255 buffer_.params().addLayoutModule(argument);
1256 buffer_.params().makeDocumentClass();
1257 updateDocumentClass(oldClass);
1258 dr.screenUpdate(Update::Force);
1259 dr.forceBufferUpdate();
1263 case LFUN_TEXTCLASS_APPLY: {
1264 // since this shortcircuits, the second call is made only if
1266 bool const success =
1267 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1268 LayoutFileList::get().load(argument, buffer_.filePath());
1270 docstring s = bformat(_("The document class `%1$s' "
1271 "could not be loaded."), from_utf8(argument));
1272 frontend::Alert::error(_("Could not load class"), s);
1276 LayoutFile const * old_layout = buffer_.params().baseClass();
1277 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1279 if (old_layout == new_layout)
1283 // Save the old, possibly modular, layout for use in conversion.
1284 DocumentClass const * const oldDocClass =
1285 buffer_.params().documentClassPtr();
1286 cur.recordUndoFullDocument();
1287 buffer_.params().setBaseClass(argument);
1288 buffer_.params().makeDocumentClass();
1289 updateDocumentClass(oldDocClass);
1290 dr.screenUpdate(Update::Force);
1291 dr.forceBufferUpdate();
1295 case LFUN_TEXTCLASS_LOAD: {
1296 // since this shortcircuits, the second call is made only if
1298 bool const success =
1299 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1300 LayoutFileList::get().load(argument, buffer_.filePath());
1302 docstring s = bformat(_("The document class `%1$s' "
1303 "could not be loaded."), from_utf8(argument));
1304 frontend::Alert::error(_("Could not load class"), s);
1309 case LFUN_LAYOUT_RELOAD: {
1310 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1311 LayoutFileIndex bc = buffer_.params().baseClassID();
1312 LayoutFileList::get().reset(bc);
1313 buffer_.params().setBaseClass(bc);
1314 buffer_.params().makeDocumentClass();
1315 updateDocumentClass(oldClass);
1316 dr.screenUpdate(Update::Force);
1317 dr.forceBufferUpdate();
1322 dr.setMessage(_("Undo"));
1323 cur.clearSelection();
1324 if (!cur.textUndo())
1325 dr.setMessage(_("No further undo information"));
1327 dr.screenUpdate(Update::Force | Update::FitCursor);
1328 dr.forceBufferUpdate();
1332 dr.setMessage(_("Redo"));
1333 cur.clearSelection();
1334 if (!cur.textRedo())
1335 dr.setMessage(_("No further redo information"));
1337 dr.screenUpdate(Update::Force | Update::FitCursor);
1338 dr.forceBufferUpdate();
1341 case LFUN_FONT_STATE:
1342 dr.setMessage(cur.currentState());
1345 case LFUN_BOOKMARK_SAVE:
1346 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1349 case LFUN_LABEL_GOTO: {
1350 docstring label = cmd.argument();
1351 if (label.empty()) {
1353 getInsetByCode<InsetRef>(cur, REF_CODE);
1355 label = inset->getParam("reference");
1356 // persistent=false: use temp_bookmark
1360 if (!label.empty()) {
1362 // at the moment, this is redundant, since gotoLabel will
1363 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1365 dr.screenUpdate(Update::Force | Update::FitCursor);
1370 case LFUN_PARAGRAPH_GOTO: {
1371 int const id = convert<int>(cmd.getArg(0));
1372 int const pos = convert<int>(cmd.getArg(1));
1374 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1375 b = theBufferList().next(b)) {
1377 DocIterator dit = b->getParFromID(id);
1379 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1383 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1384 << " found in buffer `"
1385 << b->absFileName() << "'.");
1387 if (b == &buffer_) {
1391 dr.screenUpdate(Update::Force | Update::FitCursor);
1393 // Switch to other buffer view and resend cmd
1394 lyx::dispatch(FuncRequest(
1395 LFUN_BUFFER_SWITCH, b->absFileName()));
1403 case LFUN_NOTE_NEXT:
1404 gotoInset(this, NOTE_CODE, false);
1407 case LFUN_REFERENCE_NEXT: {
1408 vector<InsetCode> tmp;
1409 tmp.push_back(LABEL_CODE);
1410 tmp.push_back(REF_CODE);
1411 gotoInset(this, tmp, true);
1415 case LFUN_CHANGES_TRACK:
1416 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1419 case LFUN_CHANGES_OUTPUT:
1420 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1421 if (buffer_.params().outputChanges) {
1422 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1423 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1424 LaTeXFeatures::isAvailable("xcolor");
1426 if (!dvipost && !xcolorulem) {
1427 Alert::warning(_("Changes not shown in LaTeX output"),
1428 _("Changes will not be highlighted in LaTeX output, "
1429 "because neither dvipost nor xcolor/ulem are installed.\n"
1430 "Please install these packages or redefine "
1431 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1432 } else if (!xcolorulem) {
1433 Alert::warning(_("Changes not shown in LaTeX output"),
1434 _("Changes will not be highlighted in LaTeX output "
1435 "when using pdflatex, because xcolor and ulem are not installed.\n"
1436 "Please install both packages or redefine "
1437 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1442 case LFUN_CHANGE_NEXT:
1443 findNextChange(this);
1444 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1445 dr.screenUpdate(Update::Force | Update::FitCursor);
1448 case LFUN_CHANGE_PREVIOUS:
1449 findPreviousChange(this);
1450 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1451 dr.screenUpdate(Update::Force | Update::FitCursor);
1454 case LFUN_CHANGES_MERGE:
1455 if (findNextChange(this) || findPreviousChange(this)) {
1456 dr.screenUpdate(Update::Force | Update::FitCursor);
1457 dr.forceBufferUpdate();
1458 showDialog("changes");
1462 case LFUN_ALL_CHANGES_ACCEPT:
1463 // select complete document
1465 cur.selHandle(true);
1466 buffer_.text().cursorBottom(cur);
1467 // accept everything in a single step to support atomic undo
1468 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1470 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1471 dr.screenUpdate(Update::Force | Update::FitCursor);
1472 dr.forceBufferUpdate();
1475 case LFUN_ALL_CHANGES_REJECT:
1476 // select complete document
1478 cur.selHandle(true);
1479 buffer_.text().cursorBottom(cur);
1480 // reject everything in a single step to support atomic undo
1481 // Note: reject does not work recursively; the user may have to repeat the operation
1482 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1484 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1485 dr.screenUpdate(Update::Force | Update::FitCursor);
1486 dr.forceBufferUpdate();
1489 case LFUN_WORD_FIND_FORWARD:
1490 case LFUN_WORD_FIND_BACKWARD: {
1491 static docstring last_search;
1492 docstring searched_string;
1494 if (!cmd.argument().empty()) {
1495 last_search = cmd.argument();
1496 searched_string = cmd.argument();
1498 searched_string = last_search;
1501 if (searched_string.empty())
1504 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1505 docstring const data =
1506 find2string(searched_string, true, false, fw);
1507 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1509 dr.screenUpdate(Update::Force | Update::FitCursor);
1513 case LFUN_WORD_FIND: {
1514 FuncRequest req = cmd;
1515 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1516 req = d->search_request_cache_;
1517 if (req.argument().empty()) {
1518 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1521 if (lyxfind(this, req))
1522 dr.screenUpdate(Update::Force | Update::FitCursor);
1524 message(_("String not found!"));
1525 d->search_request_cache_ = req;
1529 case LFUN_WORD_REPLACE: {
1530 bool has_deleted = false;
1531 if (cur.selection()) {
1532 DocIterator beg = cur.selectionBegin();
1533 DocIterator end = cur.selectionEnd();
1534 if (beg.pit() == end.pit()) {
1535 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1536 if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1543 if (lyxreplace(this, cmd, has_deleted)) {
1544 dr.forceBufferUpdate();
1545 dr.screenUpdate(Update::Force | Update::FitCursor);
1550 case LFUN_WORD_FINDADV: {
1551 FindAndReplaceOptions opt;
1552 istringstream iss(to_utf8(cmd.argument()));
1554 if (findAdv(this, opt)) {
1555 dr.screenUpdate(Update::Force | Update::FitCursor);
1566 cur.clearSelection();
1567 dr.setMessage(from_utf8(N_("Mark off")));
1571 cur.clearSelection();
1573 dr.setMessage(from_utf8(N_("Mark on")));
1576 case LFUN_MARK_TOGGLE:
1577 cur.setSelection(false);
1580 dr.setMessage(from_utf8(N_("Mark removed")));
1583 dr.setMessage(from_utf8(N_("Mark set")));
1588 case LFUN_SCREEN_SHOW_CURSOR:
1592 case LFUN_SCREEN_RECENTER:
1596 case LFUN_BIBTEX_DATABASE_ADD: {
1597 Cursor tmpcur = cur;
1598 findInset(tmpcur, BIBTEX_CODE, false);
1599 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1602 if (inset->addDatabase(cmd.argument())) {
1603 buffer_.invalidateBibfileCache();
1604 dr.forceBufferUpdate();
1610 case LFUN_BIBTEX_DATABASE_DEL: {
1611 Cursor tmpcur = cur;
1612 findInset(tmpcur, BIBTEX_CODE, false);
1613 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1616 if (inset->delDatabase(cmd.argument())) {
1617 buffer_.invalidateBibfileCache();
1618 dr.forceBufferUpdate();
1624 case LFUN_STATISTICS: {
1625 DocIterator from, to;
1626 if (cur.selection()) {
1627 from = cur.selectionBegin();
1628 to = cur.selectionEnd();
1630 from = doc_iterator_begin(&buffer_);
1631 to = doc_iterator_end(&buffer_);
1633 int const words = countWords(from, to);
1634 int const chars = countChars(from, to, false);
1635 int const chars_blanks = countChars(from, to, true);
1637 if (cur.selection())
1638 message = _("Statistics for the selection:");
1640 message = _("Statistics for the document:");
1643 message += bformat(_("%1$d words"), words);
1645 message += _("One word");
1647 if (chars_blanks != 1)
1648 message += bformat(_("%1$d characters (including blanks)"),
1651 message += _("One character (including blanks)");
1654 message += bformat(_("%1$d characters (excluding blanks)"),
1657 message += _("One character (excluding blanks)");
1659 Alert::information(_("Statistics"), message);
1663 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1664 // turn compression on/off
1665 buffer_.params().compressed = !buffer_.params().compressed;
1668 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
1669 buffer_.params().output_sync = !buffer_.params().output_sync;
1672 case LFUN_SCREEN_UP:
1673 case LFUN_SCREEN_DOWN: {
1674 Point p = getPos(cur);
1675 // This code has been commented out to enable to scroll down a
1676 // document, even if there are large insets in it (see bug #5465).
1677 /*if (p.y_ < 0 || p.y_ > height_) {
1678 // The cursor is off-screen so recenter before proceeding.
1682 int const scrolled = scroll(act == LFUN_SCREEN_UP
1683 ? -height_ : height_);
1684 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1686 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1687 p = Point(width_, height_);
1689 bool const in_texted = cur.inTexted();
1691 buffer_.changed(true);
1692 updateHoveredInset();
1694 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1695 true, act == LFUN_SCREEN_UP);
1697 //FIXME: what to do with cur.x_target()?
1698 bool update = in_texted && cur.bv().checkDepm(cur, old);
1701 dr.screenUpdate(Update::Force | Update::FitCursor);
1702 dr.forceBufferUpdate();
1709 dr.forceBufferUpdate();
1712 case LFUN_SCREEN_UP_SELECT: {
1713 cur.selHandle(true);
1714 if (isTopScreen()) {
1715 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1719 int y = getPos(cur).y_;
1720 int const ymin = y - height_ + defaultRowHeight();
1721 while (y > ymin && cur.up())
1725 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1729 case LFUN_SCREEN_DOWN_SELECT: {
1730 cur.selHandle(true);
1731 if (isBottomScreen()) {
1732 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1736 int y = getPos(cur).y_;
1737 int const ymax = y + height_ - defaultRowHeight();
1738 while (y < ymax && cur.down())
1742 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1747 // This would be in Buffer class if only Cursor did not
1748 // require a bufferview
1749 case LFUN_INSET_FORALL: {
1750 docstring const name = from_utf8(cmd.getArg(0));
1751 string const commandstr = cmd.getLongArg(1);
1752 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1754 // an arbitrary number to limit number of iterations
1755 const int max_iter = 10000;
1757 Cursor & cur = d->cursor_;
1758 Cursor const savecur = cur;
1760 if (!cur.nextInset())
1762 cur.beginUndoGroup();
1763 while(cur && iterations < max_iter) {
1764 Inset * ins = cur.nextInset();
1767 docstring insname = ins->layoutName();
1768 while (!insname.empty()) {
1769 if (insname == name || name == from_utf8("*")) {
1771 lyx::dispatch(fr, dr);
1775 size_t const i = insname.rfind(':');
1776 if (i == string::npos)
1778 insname = insname.substr(0, i);
1785 dr.screenUpdate(Update::Force);
1786 dr.forceBufferUpdate();
1788 if (iterations >= max_iter) {
1790 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1792 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1797 case LFUN_BRANCH_ADD_INSERT: {
1798 docstring branch_name = from_utf8(cmd.getArg(0));
1799 if (branch_name.empty())
1800 if (!Alert::askForText(branch_name, _("Branch name")) ||
1801 branch_name.empty())
1804 DispatchResult drtmp;
1805 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1806 if (drtmp.error()) {
1807 Alert::warning(_("Branch already exists"), drtmp.message());
1810 BranchList & branch_list = buffer_.params().branchlist();
1811 vector<docstring> const branches =
1812 getVectorFromString(branch_name, branch_list.separator());
1813 for (vector<docstring>::const_iterator it = branches.begin();
1814 it != branches.end(); ++it) {
1816 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1821 case LFUN_KEYMAP_OFF:
1822 getIntl().keyMapOn(false);
1825 case LFUN_KEYMAP_PRIMARY:
1826 getIntl().keyMapPrim();
1829 case LFUN_KEYMAP_SECONDARY:
1830 getIntl().keyMapSec();
1833 case LFUN_KEYMAP_TOGGLE:
1834 getIntl().toggleKeyMap();
1837 case LFUN_DIALOG_SHOW_NEW_INSET: {
1838 string const name = cmd.getArg(0);
1839 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1840 if (decodeInsetParam(name, data, buffer_))
1841 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1843 lyxerr << "Inset type '" << name <<
1844 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1848 case LFUN_CITATION_INSERT: {
1849 if (argument.empty()) {
1850 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1853 // we can have one optional argument, delimited by '|'
1854 // citation-insert <key>|<text_before>
1855 // this should be enhanced to also support text_after
1856 // and citation style
1857 string arg = argument;
1859 if (contains(argument, "|")) {
1860 arg = token(argument, '|', 0);
1861 opt1 = token(argument, '|', 1);
1863 InsetCommandParams icp(CITE_CODE);
1864 icp["key"] = from_utf8(arg);
1866 icp["before"] = from_utf8(opt1);
1867 string icstr = InsetCommand::params2string(icp);
1868 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1873 case LFUN_INSET_APPLY: {
1874 string const name = cmd.getArg(0);
1875 Inset * inset = editedInset(name);
1877 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1881 // put cursor in front of inset.
1882 if (!setCursorFromInset(inset)) {
1883 LASSERT(false, break);
1886 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1887 inset->dispatch(cur, fr);
1888 dr.screenUpdate(cur.result().screenUpdate());
1889 if (cur.result().needBufferUpdate())
1890 dr.forceBufferUpdate();
1895 // The change of language of buffer belongs to the Buffer class.
1896 // We have to do it here because we need a cursor for Undo.
1897 // When Undo::recordUndoBufferParams() is implemented someday
1898 // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
1899 case LFUN_BUFFER_LANGUAGE: {
1900 Language const * oldL = buffer_.params().language;
1901 Language const * newL = languages.getLanguage(argument);
1902 if (!newL || oldL == newL)
1904 if (oldL->rightToLeft() == newL->rightToLeft() && !buffer_.isMultiLingual()) {
1905 cur.recordUndoFullDocument();
1906 buffer_.changeLanguage(oldL, newL);
1907 cur.setCurrentFont();
1908 dr.forceBufferUpdate();
1914 // OK, so try the Buffer itself...
1915 buffer_.dispatch(cmd, dr);
1916 dispatched = dr.dispatched();
1920 buffer_.undo().endUndoGroup();
1921 dr.dispatched(dispatched);
1925 docstring const BufferView::requestSelection()
1927 Cursor & cur = d->cursor_;
1929 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1930 if (!cur.selection()) {
1931 d->xsel_cache_.set = false;
1935 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1936 if (!d->xsel_cache_.set ||
1937 cur.top() != d->xsel_cache_.cursor ||
1938 cur.realAnchor().top() != d->xsel_cache_.anchor)
1940 d->xsel_cache_.cursor = cur.top();
1941 d->xsel_cache_.anchor = cur.realAnchor().top();
1942 d->xsel_cache_.set = cur.selection();
1943 return cur.selectionAsString(false);
1949 void BufferView::clearSelection()
1951 d->cursor_.clearSelection();
1952 // Clear the selection buffer. Otherwise a subsequent
1953 // middle-mouse-button paste would use the selection buffer,
1954 // not the more current external selection.
1955 cap::clearSelection();
1956 d->xsel_cache_.set = false;
1957 // The buffer did not really change, but this causes the
1958 // redraw we need because we cleared the selection above.
1959 buffer_.changed(false);
1963 void BufferView::resize(int width, int height)
1965 // Update from work area
1969 // Clear the paragraph height cache.
1970 d->par_height_.clear();
1971 // Redo the metrics.
1976 Inset const * BufferView::getCoveringInset(Text const & text,
1979 TextMetrics & tm = d->text_metrics_[&text];
1980 Inset * inset = tm.checkInsetHit(x, y);
1984 if (!inset->descendable(*this))
1985 // No need to go further down if the inset is not
1989 size_t cell_number = inset->nargs();
1990 // Check all the inner cell.
1991 for (size_t i = 0; i != cell_number; ++i) {
1992 Text const * inner_text = inset->getText(i);
1995 Inset const * inset_deeper =
1996 getCoveringInset(*inner_text, x, y);
1998 return inset_deeper;
2006 void BufferView::updateHoveredInset() const
2008 // Get inset under mouse, if there is one.
2009 int const x = d->mouse_position_cache_.x_;
2010 int const y = d->mouse_position_cache_.y_;
2011 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2013 d->clickable_inset_ = covering_inset && covering_inset->clickable(x, y);
2015 if (covering_inset == d->last_inset_)
2016 // Same inset, no need to do anything...
2019 bool need_redraw = false;
2020 if (d->last_inset_) {
2021 // Remove the hint on the last hovered inset (if any).
2022 need_redraw |= d->last_inset_->setMouseHover(this, false);
2026 if (covering_inset && covering_inset->setMouseHover(this, true)) {
2028 // Only the insets that accept the hover state, do
2029 // clear the last_inset_, so only set the last_inset_
2030 // member if the hovered setting is accepted.
2031 d->last_inset_ = covering_inset;
2035 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2036 << d->mouse_position_cache_.x_ << ", "
2037 << d->mouse_position_cache_.y_ << ")");
2039 d->update_strategy_ = DecorationUpdate;
2041 // This event (moving without mouse click) is not passed further.
2042 // This should be changed if it is further utilized.
2043 buffer_.changed(false);
2048 void BufferView::clearLastInset(Inset * inset) const
2050 if (d->last_inset_ != inset) {
2051 LYXERR0("Wrong last_inset!");
2052 LASSERT(false, /**/);
2058 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2060 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2062 // This is only called for mouse related events including
2063 // LFUN_FILE_OPEN generated by drag-and-drop.
2064 FuncRequest cmd = cmd0;
2066 Cursor old = cursor();
2068 cur.push(buffer_.inset());
2069 cur.setSelection(d->cursor_.selection());
2071 // Either the inset under the cursor or the
2072 // surrounding Text will handle this event.
2074 // make sure we stay within the screen...
2075 cmd.set_y(min(max(cmd.y(), -1), height_));
2077 d->mouse_position_cache_.x_ = cmd.x();
2078 d->mouse_position_cache_.y_ = cmd.y();
2080 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2081 updateHoveredInset();
2085 // Build temporary cursor.
2086 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2088 // Put anchor at the same position.
2091 cur.beginUndoGroup();
2093 // Try to dispatch to an non-editable inset near this position
2094 // via the temp cursor. If the inset wishes to change the real
2095 // cursor it has to do so explicitly by using
2096 // cur.bv().cursor() = cur; (or similar)
2098 inset->dispatch(cur, cmd);
2100 // Now dispatch to the temporary cursor. If the real cursor should
2101 // be modified, the inset's dispatch has to do so explicitly.
2102 if (!inset || !cur.result().dispatched())
2107 // Notify left insets
2110 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
2112 cursor().fixIfBroken();
2115 // Do we have a selection?
2116 theSelection().haveSelection(cursor().selection());
2118 if (cur.needBufferUpdate()) {
2119 cur.clearBufferUpdate();
2120 buffer().updateBuffer();
2123 // If the command has been dispatched,
2124 if (cur.result().dispatched() || cur.result().screenUpdate())
2125 processUpdateFlags(cur.result().screenUpdate());
2129 void BufferView::lfunScroll(FuncRequest const & cmd)
2131 string const scroll_type = cmd.getArg(0);
2132 int scroll_step = 0;
2133 if (scroll_type == "line")
2134 scroll_step = d->scrollbarParameters_.single_step;
2135 else if (scroll_type == "page")
2136 scroll_step = d->scrollbarParameters_.page_step;
2139 string const scroll_quantity = cmd.getArg(1);
2140 if (scroll_quantity == "up")
2141 scrollUp(scroll_step);
2142 else if (scroll_quantity == "down")
2143 scrollDown(scroll_step);
2145 int const scroll_value = convert<int>(scroll_quantity);
2147 scroll(scroll_step * scroll_value);
2149 buffer_.changed(true);
2150 updateHoveredInset();
2154 int BufferView::minVisiblePart()
2156 return 2 * defaultRowHeight();
2160 int BufferView::scroll(int y)
2163 return scrollDown(y);
2165 return scrollUp(-y);
2170 int BufferView::scrollDown(int offset)
2172 Text * text = &buffer_.text();
2173 TextMetrics & tm = d->text_metrics_[text];
2174 int const ymax = height_ + offset;
2176 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2177 int bottom_pos = last.second->position() + last.second->descent();
2178 if (lyxrc.scroll_below_document)
2179 bottom_pos += height_ - minVisiblePart();
2180 if (last.first + 1 == int(text->paragraphs().size())) {
2181 if (bottom_pos <= height_)
2183 offset = min(offset, bottom_pos - height_);
2186 if (bottom_pos > ymax)
2188 tm.newParMetricsDown();
2190 d->anchor_ypos_ -= offset;
2195 int BufferView::scrollUp(int offset)
2197 Text * text = &buffer_.text();
2198 TextMetrics & tm = d->text_metrics_[text];
2199 int ymin = - offset;
2201 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2202 int top_pos = first.second->position() - first.second->ascent();
2203 if (first.first == 0) {
2206 offset = min(offset, - top_pos);
2211 tm.newParMetricsUp();
2213 d->anchor_ypos_ += offset;
2218 void BufferView::setCursorFromRow(int row)
2222 pit_type newpit = 0;
2223 pos_type newpos = 0;
2225 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
2227 bool posvalid = (tmpid != -1);
2229 // we need to make sure that the row and position
2230 // we got back are valid, because the buffer may well
2231 // have changed since we last generated the LaTeX.
2232 DocIterator const dit = buffer_.getParFromID(tmpid);
2233 if (dit == doc_iterator_end(&buffer_))
2237 // now have to check pos.
2239 Paragraph const & par = buffer_.text().getPar(newpit);
2240 if (newpos > par.size()) {
2241 LYXERR0("Requested position no longer valid.");
2242 newpos = par.size() - 1;
2247 frontend::Alert::error(_("Inverse Search Failed"),
2248 _("Invalid position requested by inverse search.\n"
2249 "You need to update the viewed document."));
2253 buffer_.text().setCursor(d->cursor_, newpit, newpos);
2254 d->cursor_.setSelection(false);
2255 d->cursor_.resetAnchor();
2260 bool BufferView::setCursorFromInset(Inset const * inset)
2262 // are we already there?
2263 if (cursor().nextInset() == inset)
2266 // Inset is not at cursor position. Find it in the document.
2269 while (cur && cur.nextInset() != inset)
2280 void BufferView::gotoLabel(docstring const & label)
2282 ListOfBuffers bufs = buffer().allRelatives();
2283 ListOfBuffers::iterator it = bufs.begin();
2284 for (; it != bufs.end(); ++it) {
2285 Buffer const * buf = *it;
2288 Toc & toc = buf->tocBackend().toc("label");
2289 TocIterator toc_it = toc.begin();
2290 TocIterator end = toc.end();
2291 for (; toc_it != end; ++toc_it) {
2292 if (label == toc_it->str()) {
2293 lyx::dispatch(toc_it->action());
2301 TextMetrics const & BufferView::textMetrics(Text const * t) const
2303 return const_cast<BufferView *>(this)->textMetrics(t);
2307 TextMetrics & BufferView::textMetrics(Text const * t)
2310 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2311 if (tmc_it == d->text_metrics_.end()) {
2312 tmc_it = d->text_metrics_.insert(
2313 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2315 return tmc_it->second;
2319 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2322 return textMetrics(t).parMetrics(pit);
2326 int BufferView::workHeight() const
2332 void BufferView::setCursor(DocIterator const & dit)
2335 size_t const n = dit.depth();
2336 for (size_t i = 0; i < n; ++i)
2337 dit[i].inset().edit(d->cursor_, true);
2339 d->cursor_.setCursor(dit);
2340 d->cursor_.setSelection(false);
2342 // It seems on general grounds as if this is probably needed, but
2343 // it is not yet clear.
2344 // See bug #7394 and r38388.
2345 // d->cursor.resetAnchor();
2349 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2351 // Would be wrong to delete anything if we have a selection.
2352 if (cur.selection())
2355 bool need_anchor_change = false;
2356 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2357 need_anchor_change);
2359 if (need_anchor_change)
2367 cur.forceBufferUpdate();
2368 buffer_.changed(true);
2373 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2375 LASSERT(&cur.bv() == this, /**/);
2378 // this event will clear selection so we save selection for
2379 // persistent selection
2380 cap::saveSelection(cursor());
2382 d->cursor_.macroModeClose();
2384 // Has the cursor just left the inset?
2385 bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2387 d->cursor_.fixIfBroken();
2389 // FIXME: shift-mouse selection doesn't work well across insets.
2390 bool const do_selection =
2391 select && &d->cursor_.normalAnchor().inset() == &cur.inset();
2393 // do the dEPM magic if needed
2394 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2395 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2396 // the leftinset bool would not be necessary (badcursor instead).
2397 bool update = leftinset;
2398 if (!do_selection && d->cursor_.inTexted())
2399 update |= checkDepm(cur, d->cursor_);
2402 d->cursor_.resetAnchor();
2403 d->cursor_.setCursor(cur);
2404 d->cursor_.boundary(cur.boundary());
2406 d->cursor_.setSelection();
2408 d->cursor_.clearSelection();
2410 d->cursor_.finishUndo();
2411 d->cursor_.setCurrentFont();
2413 cur.forceBufferUpdate();
2418 void BufferView::putSelectionAt(DocIterator const & cur,
2419 int length, bool backwards)
2421 d->cursor_.clearSelection();
2427 d->cursor_.pos() += length;
2428 d->cursor_.setSelection(d->cursor_, -length);
2430 d->cursor_.setSelection(d->cursor_, length);
2435 bool BufferView::selectIfEmpty(DocIterator & cur)
2437 if (!cur.paragraph().empty())
2440 pit_type const beg_pit = cur.pit();
2442 // The paragraph associated to this item isn't
2443 // the first one, so it can be selected
2446 // We have to resort to select the space between the
2447 // end of this item and the begin of the next one
2451 // If it is the only item in the document,
2452 // nothing can be selected
2455 pit_type const end_pit = cur.pit();
2456 pos_type const end_pos = cur.pos();
2457 d->cursor_.clearSelection();
2459 d->cursor_.setCursor(cur);
2460 d->cursor_.pit() = beg_pit;
2461 d->cursor_.pos() = 0;
2462 d->cursor_.setSelection(false);
2463 d->cursor_.resetAnchor();
2464 d->cursor_.pit() = end_pit;
2465 d->cursor_.pos() = end_pos;
2466 d->cursor_.setSelection();
2471 Cursor & BufferView::cursor()
2477 Cursor const & BufferView::cursor() const
2483 pit_type BufferView::anchor_ref() const
2485 return d->anchor_pit_;
2489 bool BufferView::singleParUpdate()
2491 Text & buftext = buffer_.text();
2492 pit_type const bottom_pit = d->cursor_.bottom().pit();
2493 TextMetrics & tm = textMetrics(&buftext);
2494 int old_height = tm.parMetrics(bottom_pit).height();
2496 // make sure inline completion pointer is ok
2497 if (d->inlineCompletionPos_.fixIfBroken())
2498 d->inlineCompletionPos_ = DocIterator();
2500 // In Single Paragraph mode, rebreak only
2501 // the (main text, not inset!) paragraph containing the cursor.
2502 // (if this paragraph contains insets etc., rebreaking will
2503 // recursively descend)
2504 tm.redoParagraph(bottom_pit);
2505 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2506 if (pm.height() != old_height)
2507 // Paragraph height has changed so we cannot proceed to
2508 // the singlePar optimisation.
2511 d->update_strategy_ = SingleParUpdate;
2513 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2514 << " y2: " << pm.position() + pm.descent()
2515 << " pit: " << bottom_pit
2516 << " singlepar: 1");
2521 void BufferView::updateMetrics()
2523 if (height_ == 0 || width_ == 0)
2526 Text & buftext = buffer_.text();
2527 pit_type const npit = int(buftext.paragraphs().size());
2529 // Clear out the position cache in case of full screen redraw,
2530 d->coord_cache_.clear();
2532 // Clear out paragraph metrics to avoid having invalid metrics
2533 // in the cache from paragraphs not relayouted below
2534 // The complete text metrics will be redone.
2535 d->text_metrics_.clear();
2537 TextMetrics & tm = textMetrics(&buftext);
2539 // make sure inline completion pointer is ok
2540 if (d->inlineCompletionPos_.fixIfBroken())
2541 d->inlineCompletionPos_ = DocIterator();
2543 if (d->anchor_pit_ >= npit)
2544 // The anchor pit must have been deleted...
2545 d->anchor_pit_ = npit - 1;
2547 // Rebreak anchor paragraph.
2548 tm.redoParagraph(d->anchor_pit_);
2549 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2552 if (d->anchor_pit_ == 0) {
2553 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2555 // Complete buffer visible? Then it's easy.
2556 if (scrollRange == 0)
2557 d->anchor_ypos_ = anchor_pm.ascent();
2559 // FIXME: Some clever handling needed to show
2560 // the _first_ paragraph up to the top if the cursor is
2561 // in the first line.
2563 anchor_pm.setPosition(d->anchor_ypos_);
2565 LYXERR(Debug::PAINTING, "metrics: "
2566 << " anchor pit = " << d->anchor_pit_
2567 << " anchor ypos = " << d->anchor_ypos_);
2569 // Redo paragraphs above anchor if necessary.
2570 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2571 // We are now just above the anchor paragraph.
2572 pit_type pit1 = d->anchor_pit_ - 1;
2573 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2574 tm.redoParagraph(pit1);
2575 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2577 // Save the paragraph position in the cache.
2582 // Redo paragraphs below the anchor if necessary.
2583 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2584 // We are now just below the anchor paragraph.
2585 pit_type pit2 = d->anchor_pit_ + 1;
2586 for (; pit2 < npit && y2 <= height_; ++pit2) {
2587 tm.redoParagraph(pit2);
2588 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2590 // Save the paragraph position in the cache.
2595 LYXERR(Debug::PAINTING, "Metrics: "
2596 << " anchor pit = " << d->anchor_pit_
2597 << " anchor ypos = " << d->anchor_ypos_
2600 << " pit1 = " << pit1
2601 << " pit2 = " << pit2);
2603 d->update_strategy_ = FullScreenUpdate;
2605 if (lyxerr.debugging(Debug::WORKAREA)) {
2606 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2607 d->coord_cache_.dump();
2612 void BufferView::insertLyXFile(FileName const & fname)
2614 LASSERT(d->cursor_.inTexted(), /**/);
2616 // Get absolute path of file and add ".lyx"
2617 // to the filename if necessary
2618 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2620 docstring const disp_fn = makeDisplayPath(filename.absFileName());
2621 // emit message signal.
2622 message(bformat(_("Inserting document %1$s..."), disp_fn));
2625 Buffer buf(filename.absFileName(), false);
2626 if (buf.loadLyXFile() == Buffer::ReadSuccess) {
2627 ErrorList & el = buffer_.errorList("Parse");
2628 // Copy the inserted document error list into the current buffer one.
2629 el = buf.errorList("Parse");
2630 buffer_.undo().recordUndo(d->cursor_);
2631 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2632 buf.params().documentClassPtr(), el);
2633 res = _("Document %1$s inserted.");
2635 res = _("Could not insert document %1$s");
2638 buffer_.changed(true);
2639 // emit message signal.
2640 message(bformat(res, disp_fn));
2644 Point BufferView::coordOffset(DocIterator const & dit) const
2650 // Addup contribution of nested insets, from inside to outside,
2651 // keeping the outer paragraph for a special handling below
2652 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2653 CursorSlice const & sl = dit[i];
2657 // get relative position inside sl.inset()
2658 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2660 // Make relative position inside of the edited inset relative to sl.inset()
2664 // In case of an RTL inset, the edited inset will be positioned to the left
2667 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2668 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2673 // remember width for the case that sl.inset() is positioned in an RTL inset
2674 if (i && dit[i - 1].text()) {
2675 // If this Inset is inside a Text Inset, retrieve the Dimension
2676 // from the containing text instead of using Inset::dimension() which
2677 // might not be implemented.
2678 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2679 // elimination of Inset::dim_ cache. This coordOffset() method needs
2680 // to be rewritten in light of the new design.
2681 Dimension const & dim = parMetrics(dit[i - 1].text(),
2682 dit[i - 1].pit()).insetDimension(&sl.inset());
2685 Dimension const dim = sl.inset().dimension(*this);
2689 //lyxerr << "Cursor::getPos, i: "
2690 // << i << " x: " << xx << " y: " << y << endl;
2693 // Add contribution of initial rows of outermost paragraph
2694 CursorSlice const & sl = dit[0];
2695 TextMetrics const & tm = textMetrics(sl.text());
2696 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2697 LASSERT(!pm.rows().empty(), /**/);
2698 y -= pm.rows()[0].ascent();
2700 // FIXME: document this mess
2702 if (sl.pos() > 0 && dit.depth() == 1) {
2704 if (pos && dit.boundary())
2706 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2707 rend = pm.pos2row(pos);
2709 rend = pm.pos2row(sl.pos());
2711 size_t rend = pm.pos2row(sl.pos());
2713 for (size_t rit = 0; rit != rend; ++rit)
2714 y += pm.rows()[rit].height();
2715 y += pm.rows()[rend].ascent();
2717 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2719 // Make relative position from the nested inset now bufferview absolute.
2720 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2723 // In the RTL case place the nested inset at the left of the cursor in
2724 // the outer paragraph
2725 bool boundary_1 = dit.boundary() && 1 == dit.depth();
2726 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2734 Point BufferView::getPos(DocIterator const & dit) const
2736 if (!paragraphVisible(dit))
2737 return Point(-1, -1);
2739 CursorSlice const & bot = dit.bottom();
2740 TextMetrics const & tm = textMetrics(bot.text());
2742 // offset from outer paragraph
2743 Point p = coordOffset(dit);
2744 p.y_ += tm.parMetrics(bot.pit()).position();
2749 bool BufferView::paragraphVisible(DocIterator const & dit) const
2751 CursorSlice const & bot = dit.bottom();
2752 TextMetrics const & tm = textMetrics(bot.text());
2754 return tm.contains(bot.pit());
2758 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2760 Cursor const & cur = cursor();
2761 Font const font = cur.getFont();
2762 frontend::FontMetrics const & fm = theFontMetrics(font);
2763 int const asc = fm.maxAscent();
2764 int const des = fm.maxDescent();
2771 bool BufferView::cursorInView(Point const & p, int h) const
2773 Cursor const & cur = cursor();
2774 // does the cursor touch the screen ?
2775 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2781 void BufferView::draw(frontend::Painter & pain)
2783 if (height_ == 0 || width_ == 0)
2785 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2787 Text & text = buffer_.text();
2788 TextMetrics const & tm = d->text_metrics_[&text];
2789 int const y = tm.first().second->position();
2790 PainterInfo pi(this, pain);
2792 switch (d->update_strategy_) {
2794 case NoScreenUpdate:
2795 // If no screen painting is actually needed, only some the different
2796 // coordinates of insets and paragraphs needs to be updated.
2797 pi.full_repaint = true;
2798 pi.pain.setDrawingEnabled(false);
2802 case SingleParUpdate:
2803 pi.full_repaint = false;
2804 // In general, only the current row of the outermost paragraph
2805 // will be redrawn. Particular cases where selection spans
2806 // multiple paragraph are correctly detected in TextMetrics.
2810 case DecorationUpdate:
2811 // FIXME: We should also distinguish DecorationUpdate to avoid text
2812 // drawing if possible. This is not possible to do easily right now
2813 // because of the single backing pixmap.
2815 case FullScreenUpdate:
2816 // The whole screen, including insets, will be refreshed.
2817 pi.full_repaint = true;
2819 // Clear background.
2820 pain.fillRectangle(0, 0, width_, height_,
2821 pi.backgroundColor(&buffer_.inset()));
2826 // and possibly grey out below
2827 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2828 int const y2 = lastpm.second->position() + lastpm.second->descent();
2831 Color color = buffer().isInternal()
2832 ? Color_background : Color_bottomarea;
2833 pain.fillRectangle(0, y2, width_, height_ - y2, color);
2837 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2839 // The scrollbar needs an update.
2842 // Normalize anchor for next time
2843 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2844 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2845 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2846 ParagraphMetrics const & pm = tm.parMetrics(pit);
2847 if (pm.position() + pm.descent() > 0) {
2848 d->anchor_pit_ = pit;
2849 d->anchor_ypos_ = pm.position();
2853 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2854 << " anchor ypos = " << d->anchor_ypos_);
2858 void BufferView::message(docstring const & msg)
2861 d->gui_->message(msg);
2865 void BufferView::showDialog(string const & name)
2868 d->gui_->showDialog(name, string());
2872 void BufferView::showDialog(string const & name,
2873 string const & data, Inset * inset)
2876 d->gui_->showDialog(name, data, inset);
2880 void BufferView::updateDialog(string const & name, string const & data)
2883 d->gui_->updateDialog(name, data);
2887 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2893 // FIXME: Move this out of BufferView again
2894 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2896 if (!fname.isReadableFile()) {
2897 docstring const error = from_ascii(strerror(errno));
2898 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2899 docstring const text =
2900 bformat(_("Could not read the specified document\n"
2901 "%1$s\ndue to the error: %2$s"), file, error);
2902 Alert::error(_("Could not read file"), text);
2906 if (!fname.isReadableFile()) {
2907 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2908 docstring const text =
2909 bformat(_("%1$s\n is not readable."), file);
2910 Alert::error(_("Could not open file"), text);
2914 // FIXME UNICODE: We don't know the encoding of the file
2915 docstring file_content = fname.fileContents("UTF-8");
2916 if (file_content.empty()) {
2917 Alert::error(_("Reading not UTF-8 encoded file"),
2918 _("The file is not UTF-8 encoded.\n"
2919 "It will be read as local 8Bit-encoded.\n"
2920 "If this does not give the correct result\n"
2921 "then please change the encoding of the file\n"
2922 "to UTF-8 with a program other than LyX.\n"));
2923 file_content = fname.fileContents("local8bit");
2926 return normalize_c(file_content);
2930 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2932 docstring const tmpstr = contentsOfPlaintextFile(f);
2937 Cursor & cur = cursor();
2938 cap::replaceSelection(cur);
2939 buffer_.undo().recordUndo(cur);
2941 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2943 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2945 buffer_.changed(true);
2949 docstring const & BufferView::inlineCompletion() const
2951 return d->inlineCompletion_;
2955 size_t const & BufferView::inlineCompletionUniqueChars() const
2957 return d->inlineCompletionUniqueChars_;
2961 DocIterator const & BufferView::inlineCompletionPos() const
2963 return d->inlineCompletionPos_;
2967 void BufferView::resetInlineCompletionPos()
2969 d->inlineCompletionPos_ = DocIterator();
2973 bool samePar(DocIterator const & a, DocIterator const & b)
2975 if (a.empty() && b.empty())
2977 if (a.empty() || b.empty())
2979 if (a.depth() != b.depth())
2981 return &a.innerParagraph() == &b.innerParagraph();
2985 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2986 docstring const & completion, size_t uniqueChars)
2988 uniqueChars = min(completion.size(), uniqueChars);
2989 bool changed = d->inlineCompletion_ != completion
2990 || d->inlineCompletionUniqueChars_ != uniqueChars;
2991 bool singlePar = true;
2992 d->inlineCompletion_ = completion;
2993 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2995 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2998 DocIterator const & old = d->inlineCompletionPos_;
3000 //lyxerr << "inlineCompletionPos changed" << std::endl;
3001 // old or pos are in another paragraph?
3002 if ((!samePar(cur, pos) && !pos.empty())
3003 || (!samePar(cur, old) && !old.empty())) {
3005 //lyxerr << "different paragraph" << std::endl;
3007 d->inlineCompletionPos_ = pos;
3012 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3013 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3015 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3020 bool BufferView::clickableInset() const
3022 return d->clickable_inset_;