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"
45 #include "MetricsInfo.h"
46 #include "Paragraph.h"
47 #include "ParagraphParameters.h"
48 #include "ParIterator.h"
51 #include "TextClass.h"
52 #include "TextMetrics.h"
54 #include "TocBackend.h"
56 #include "WordLangTuple.h"
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetExternal.h"
61 #include "insets/InsetGraphics.h"
62 #include "insets/InsetRef.h"
63 #include "insets/InsetText.h"
64 #include "insets/InsetNote.h"
65 #include "insets/InsetERT.h"
67 #include "frontends/alert.h"
68 #include "frontends/Application.h"
69 #include "frontends/Delegates.h"
70 #include "frontends/FontMetrics.h"
71 #include "frontends/Painter.h"
72 #include "frontends/Selection.h"
74 #include "graphics/Previews.h"
76 #include "support/convert.h"
77 #include "support/debug.h"
78 #include "support/ExceptionMessage.h"
79 #include "support/filetools.h"
80 #include "support/gettext.h"
81 #include "support/lstrings.h"
82 #include "support/Package.h"
83 #include "support/types.h"
93 using namespace lyx::support;
97 namespace Alert = frontend::Alert;
101 /// Return an inset of this class if it exists at the current cursor position
103 T * getInsetByCode(Cursor const & cur, InsetCode code)
105 DocIterator it = cur;
106 Inset * inset = it.nextInset();
107 if (inset && inset->lyxCode() == code)
108 return static_cast<T*>(inset);
113 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
116 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
117 docstring const & contents)
119 DocIterator tmpdit = dit;
122 Inset const * inset = tmpdit.nextInset();
124 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
125 && (contents.empty() ||
126 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
130 tmpdit.forwardInset();
137 /// Looks for next inset with one of the given codes.
138 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
142 DocIterator tmpdit = dit;
143 tmpdit.forwardInset();
148 Inset const * inset = tmpdit.nextInset();
150 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
151 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
155 if (!findNextInset(tmpdit, codes, contents)) {
156 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
157 Inset * inset = &tmpdit.bottom().inset();
158 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
159 if (!findNextInset(tmpdit, codes, contents))
171 /// Looks for next inset with the given code
172 void findInset(DocIterator & dit, InsetCode code, bool same_content)
174 findInset(dit, vector<InsetCode>(1, code), same_content);
178 /// Moves cursor to the next inset with one of the given codes.
179 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
182 Cursor tmpcur = bv->cursor();
183 if (!findInset(tmpcur, codes, same_content)) {
184 bv->cursor().message(_("No more insets"));
188 tmpcur.clearSelection();
189 bv->setCursor(tmpcur);
194 /// Moves cursor to the next inset with given code.
195 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
197 gotoInset(bv, vector<InsetCode>(1, code), same_content);
201 /// A map from a Text to the associated text metrics
202 typedef map<Text const *, TextMetrics> TextMetricsCache;
204 enum ScreenUpdateStrategy {
214 /////////////////////////////////////////////////////////////////////
218 /////////////////////////////////////////////////////////////////////
220 struct BufferView::Private
222 Private(BufferView & bv): wh_(0), cursor_(bv),
223 anchor_pit_(0), anchor_ypos_(0),
224 inlineCompletionUniqueChars_(0),
225 last_inset_(0), bookmark_edit_position_(0), gui_(0)
229 ScrollbarParameters scrollbarParameters_;
231 ScreenUpdateStrategy update_strategy_;
233 CoordCache coord_cache_;
235 /// Estimated average par height for scrollbar.
237 /// this is used to handle XSelection events in the right manner.
246 pit_type anchor_pit_;
250 vector<int> par_height_;
253 DocIterator inlineCompletionPos_;
255 docstring inlineCompletion_;
257 size_t inlineCompletionUniqueChars_;
259 /// keyboard mapping object.
262 /// last visited inset.
263 /** kept to send setMouseHover(false).
264 * Not owned, so don't delete.
268 // cache for id of the paragraph which was edited the last time
269 int bookmark_edit_position_;
271 mutable TextMetricsCache text_metrics_;
274 /** Not owned, so don't delete.
276 frontend::GuiBufferViewDelegate * gui_;
278 /// Cache for Find Next
279 FuncRequest search_request_cache_;
282 map<string, Inset *> edited_insets_;
286 BufferView::BufferView(Buffer & buf)
287 : width_(0), height_(0), full_screen_(false), buffer_(buf),
288 d(new Private(*this))
290 d->xsel_cache_.set = false;
291 d->intl_.initKeyMapper(lyxrc.use_kbmap);
293 d->cursor_.setBuffer(&buf);
294 d->cursor_.push(buffer_.inset());
295 d->cursor_.resetAnchor();
296 d->cursor_.setCurrentFont();
298 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
299 thePreviews().generateBufferPreviews(buffer_);
303 BufferView::~BufferView()
305 // current buffer is going to be switched-off, save cursor pos
306 // Ideally, the whole cursor stack should be saved, but session
307 // currently can only handle bottom (whole document) level pit and pos.
308 // That is to say, if a cursor is in a nested inset, it will be
309 // restore to the left of the top level inset.
310 LastFilePosSection::FilePos fp;
311 fp.pit = d->cursor_.bottom().pit();
312 fp.pos = d->cursor_.bottom().pos();
313 theSession().lastFilePos().save(buffer_.fileName(), fp);
319 int BufferView::rightMargin() const
321 // The additional test for the case the outliner is opened.
323 !lyxrc.full_screen_limit ||
324 width_ < lyxrc.full_screen_width + 20)
327 return (width_ - lyxrc.full_screen_width) / 2;
331 int BufferView::leftMargin() const
333 return rightMargin();
337 bool BufferView::isTopScreen() const
339 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
343 bool BufferView::isBottomScreen() const
345 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
349 Intl & BufferView::getIntl()
355 Intl const & BufferView::getIntl() const
361 CoordCache & BufferView::coordCache()
363 return d->coord_cache_;
367 CoordCache const & BufferView::coordCache() const
369 return d->coord_cache_;
373 Buffer & BufferView::buffer()
379 Buffer const & BufferView::buffer() const
385 bool BufferView::fitCursor()
387 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
388 frontend::FontMetrics const & fm =
389 theFontMetrics(d->cursor_.getFont().fontInfo());
390 int const asc = fm.maxAscent();
391 int const des = fm.maxDescent();
392 Point const p = getPos(d->cursor_, d->cursor_.boundary());
393 if (p.y_ - asc >= 0 && p.y_ + des < height_)
400 void BufferView::processUpdateFlags(Update::flags flags)
402 // last_inset_ points to the last visited inset. This pointer may become
403 // invalid because of keyboard editing. Since all such operations
404 // causes screen update(), I reset last_inset_ to avoid such a problem.
406 // This is close to a hot-path.
407 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
408 << "[fitcursor = " << (flags & Update::FitCursor)
409 << ", forceupdate = " << (flags & Update::Force)
410 << ", singlepar = " << (flags & Update::SinglePar)
411 << "] buffer: " << &buffer_);
413 buffer_.updateMacros();
415 // Now do the first drawing step if needed. This consists on updating
416 // the CoordCache in updateMetrics().
417 // The second drawing step is done in WorkArea::redraw() if needed.
419 // Case when no explicit update is requested.
421 // no need to redraw anything.
422 d->update_strategy_ = NoScreenUpdate;
426 if (flags == Update::Decoration) {
427 d->update_strategy_ = DecorationUpdate;
428 buffer_.changed(false);
432 if (flags == Update::FitCursor
433 || flags == (Update::Decoration | Update::FitCursor)) {
434 // tell the frontend to update the screen if needed.
439 if (flags & Update::Decoration) {
440 d->update_strategy_ = DecorationUpdate;
441 buffer_.changed(false);
444 // no screen update is needed.
445 d->update_strategy_ = NoScreenUpdate;
449 bool const full_metrics = flags & Update::Force || !singleParUpdate();
452 // We have to update the full screen metrics.
455 if (!(flags & Update::FitCursor)) {
456 // Nothing to do anymore. Trigger a redraw and return
457 buffer_.changed(false);
461 // updateMetrics() does not update paragraph position
462 // This is done at draw() time. So we need a redraw!
463 buffer_.changed(false);
466 // The cursor is off screen so ensure it is visible.
473 void BufferView::updateScrollbar()
475 if (height_ == 0 && width_ == 0)
478 // We prefer fixed size line scrolling.
479 d->scrollbarParameters_.single_step = defaultRowHeight();
480 // We prefer full screen page scrolling.
481 d->scrollbarParameters_.page_step = height_;
483 Text & t = buffer_.text();
484 TextMetrics & tm = d->text_metrics_[&t];
486 LYXERR(Debug::GUI, " Updating scrollbar: height: "
487 << t.paragraphs().size()
488 << " curr par: " << d->cursor_.bottom().pit()
489 << " default height " << defaultRowHeight());
491 size_t const parsize = t.paragraphs().size();
492 if (d->par_height_.size() != parsize) {
493 d->par_height_.clear();
494 // FIXME: We assume a default paragraph height of 2 rows. This
495 // should probably be pondered with the screen width.
496 d->par_height_.resize(parsize, defaultRowHeight() * 2);
499 // Look at paragraph heights on-screen
500 pair<pit_type, ParagraphMetrics const *> first = tm.first();
501 pair<pit_type, ParagraphMetrics const *> last = tm.last();
502 for (pit_type pit = first.first; pit <= last.first; ++pit) {
503 d->par_height_[pit] = tm.parMetrics(pit).height();
504 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
505 << d->par_height_[pit]);
508 int top_pos = first.second->position() - first.second->ascent();
509 int bottom_pos = last.second->position() + last.second->descent();
510 bool first_visible = first.first == 0 && top_pos >= 0;
511 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
512 if (first_visible && last_visible) {
513 d->scrollbarParameters_.min = 0;
514 d->scrollbarParameters_.max = 0;
518 d->scrollbarParameters_.min = top_pos;
519 for (size_t i = 0; i != size_t(first.first); ++i)
520 d->scrollbarParameters_.min -= d->par_height_[i];
521 d->scrollbarParameters_.max = bottom_pos;
522 for (size_t i = last.first + 1; i != parsize; ++i)
523 d->scrollbarParameters_.max += d->par_height_[i];
525 d->scrollbarParameters_.position = 0;
526 // The reference is the top position so we remove one page.
527 if (lyxrc.scroll_below_document)
528 d->scrollbarParameters_.max -= minVisiblePart();
530 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
534 ScrollbarParameters const & BufferView::scrollbarParameters() const
536 return d->scrollbarParameters_;
540 docstring BufferView::toolTip(int x, int y) const
542 // Get inset under mouse, if there is one.
543 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
545 // No inset, no tooltip...
547 return covering_inset->toolTip(*this, x, y);
551 docstring BufferView::contextMenu(int x, int y) const
553 //If there is a selection, return the containing inset menu
554 if (d->cursor_.selection())
555 return d->cursor_.inset().contextMenu(*this, x, y);
557 // Get inset under mouse, if there is one.
558 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
560 return covering_inset->contextMenu(*this, x, y);
562 return buffer_.inset().contextMenu(*this, x, y);
566 void BufferView::scrollDocView(int value)
568 int const offset = value - d->scrollbarParameters_.position;
570 // No scrolling at all? No need to redraw anything
574 // If the offset is less than 2 screen height, prefer to scroll instead.
575 if (abs(offset) <= 2 * height_) {
576 d->anchor_ypos_ -= offset;
577 buffer_.changed(true);
581 // cut off at the top
582 if (value <= d->scrollbarParameters_.min) {
583 DocIterator dit = doc_iterator_begin(&buffer_);
585 LYXERR(Debug::SCROLLING, "scroll to top");
589 // cut off at the bottom
590 if (value >= d->scrollbarParameters_.max) {
591 DocIterator dit = doc_iterator_end(&buffer_);
594 LYXERR(Debug::SCROLLING, "scroll to bottom");
598 // find paragraph at target position
599 int par_pos = d->scrollbarParameters_.min;
601 for (; i != int(d->par_height_.size()); ++i) {
602 par_pos += d->par_height_[i];
603 if (par_pos >= value)
607 if (par_pos < value) {
608 // It seems we didn't find the correct pit so stay on the safe side and
610 LYXERR0("scrolling position not found!");
611 scrollDocView(d->scrollbarParameters_.max);
615 DocIterator dit = doc_iterator_begin(&buffer_);
617 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
622 // FIXME: this method is not working well.
623 void BufferView::setCursorFromScrollbar()
625 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
627 int const height = 2 * defaultRowHeight();
628 int const first = height;
629 int const last = height_ - height;
631 Cursor const & oldcur = d->cursor_;
633 switch (cursorStatus(oldcur)) {
641 int const y = getPos(oldcur, oldcur.boundary()).y_;
642 newy = min(last, max(y, first));
646 // We reset the cursor because cursorStatus() does not
647 // work when the cursor is within mathed.
650 tm.setCursorFromCoordinates(cur, 0, newy);
652 // update the bufferview cursor and notify insets
653 // FIXME: Care about the d->cursor_ flags to redraw if needed
654 Cursor old = d->cursor_;
656 bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
658 d->cursor_.fixIfBroken();
662 Change const BufferView::getCurrentChange() const
664 if (!d->cursor_.selection())
665 return Change(Change::UNCHANGED);
667 DocIterator dit = d->cursor_.selectionBegin();
668 return dit.paragraph().lookupChange(dit.pos());
672 // this could be used elsewhere as well?
673 // FIXME: This does not work within mathed!
674 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
676 Point const p = getPos(dit, dit.boundary());
679 if (p.y_ > workHeight())
685 void BufferView::bookmarkEditPosition()
687 // Don't eat cpu time for each keystroke
688 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
691 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
695 void BufferView::saveBookmark(unsigned int idx)
697 // tentatively save bookmark, id and pos will be used to
698 // acturately locate a bookmark in a 'live' lyx session.
699 // pit and pos will be updated with bottom level pit/pos
701 theSession().bookmarks().save(
703 d->cursor_.bottom().pit(),
704 d->cursor_.bottom().pos(),
705 d->cursor_.paragraph().id(),
710 // emit message signal.
711 message(_("Save bookmark"));
715 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
716 int top_id, pos_type top_pos)
718 bool success = false;
721 d->cursor_.clearSelection();
723 // if a valid par_id is given, try it first
724 // This is the case for a 'live' bookmark when unique paragraph ID
725 // is used to track bookmarks.
727 dit = buffer_.getParFromID(top_id);
729 dit.pos() = min(dit.paragraph().size(), top_pos);
730 // Some slices of the iterator may not be
731 // reachable (e.g. closed collapsable inset)
732 // so the dociterator may need to be
733 // shortened. Otherwise, setCursor may crash
734 // lyx when the cursor can not be set to these
736 size_t const n = dit.depth();
737 for (size_t i = 0; i < n; ++i)
738 if (!dit[i].inset().editable()) {
746 // if top_id == 0, or searching through top_id failed
747 // This is the case for a 'restored' bookmark when only bottom
748 // (document level) pit was saved. Because of this, bookmark
749 // restoration is inaccurate. If a bookmark was within an inset,
750 // it will be restored to the left of the outmost inset that contains
752 if (bottom_pit < int(buffer_.paragraphs().size())) {
753 dit = doc_iterator_begin(&buffer_);
755 dit.pit() = bottom_pit;
756 dit.pos() = min(bottom_pos, dit.paragraph().size());
761 // Note: only bottom (document) level pit is set.
763 // set the current font.
764 d->cursor_.setCurrentFont();
765 // To center the screen on this new position we need the
766 // paragraph position which is computed at draw() time.
767 // So we need a redraw!
768 buffer_.changed(false);
777 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
779 if (lyxrc.rtl_support) {
780 if (d->cursor_.real_current_font.isRightToLeft()) {
781 if (d->intl_.keymap == Intl::PRIMARY)
782 d->intl_.keyMapSec();
784 if (d->intl_.keymap == Intl::SECONDARY)
785 d->intl_.keyMapPrim();
789 d->intl_.getTransManager().translateAndInsert(c, t, cur);
793 int BufferView::workWidth() const
799 void BufferView::recenter()
801 showCursor(d->cursor_, true);
805 void BufferView::showCursor()
807 showCursor(d->cursor_, false);
811 void BufferView::showCursor(DocIterator const & dit, bool recenter)
813 if (scrollToCursor(dit, recenter))
814 buffer_.changed(false);
818 void BufferView::scrollToCursor()
820 scrollToCursor(d->cursor_, false);
824 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
826 // We are not properly started yet, delay until resizing is
831 LYXERR(Debug::SCROLLING, "recentering!");
833 CursorSlice const & bot = dit.bottom();
834 TextMetrics & tm = d->text_metrics_[bot.text()];
836 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
837 int bot_pit = bot.pit();
838 if (bot_pit > max_pit) {
839 // FIXME: Why does this happen?
840 LYXERR0("bottom pit is greater that max pit: "
841 << bot_pit << " > " << max_pit);
845 if (bot_pit == tm.first().first - 1)
846 tm.newParMetricsUp();
847 else if (bot_pit == tm.last().first + 1)
848 tm.newParMetricsDown();
850 if (tm.contains(bot_pit)) {
851 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
852 LASSERT(!pm.rows().empty(), /**/);
853 // FIXME: smooth scrolling doesn't work in mathed.
854 CursorSlice const & cs = dit.innerTextSlice();
855 int offset = coordOffset(dit, dit.boundary()).y_;
856 int ypos = pm.position() + offset;
857 Dimension const & row_dim =
858 pm.getRow(cs.pos(), dit.boundary()).dimension();
861 scrolled = scroll(ypos - height_/2);
862 else if (ypos - row_dim.ascent() < 0)
863 scrolled = scrollUp(- ypos + row_dim.ascent());
864 else if (ypos + row_dim.descent() > height_)
865 scrolled = scrollDown(ypos - height_ + defaultRowHeight() );
867 // else, nothing to do, the cursor is already visible so we just return.
875 // fix inline completion position
876 if (d->inlineCompletionPos_.fixIfBroken())
877 d->inlineCompletionPos_ = DocIterator();
879 tm.redoParagraph(bot_pit);
880 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
881 int offset = coordOffset(dit, dit.boundary()).y_;
883 d->anchor_pit_ = bot_pit;
884 CursorSlice const & cs = dit.innerTextSlice();
885 Dimension const & row_dim =
886 pm.getRow(cs.pos(), dit.boundary()).dimension();
889 d->anchor_ypos_ = height_/2;
890 else if (d->anchor_pit_ == 0)
891 d->anchor_ypos_ = offset + pm.ascent();
892 else if (d->anchor_pit_ == max_pit)
893 d->anchor_ypos_ = height_ - offset - row_dim.descent();
894 else if (offset > height_)
895 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
897 d->anchor_ypos_ = defaultRowHeight() * 2;
904 void BufferView::updateLayout(DocumentClass const * const oldlayout)
906 message(_("Converting document to new document class..."));
908 StableDocIterator backcur(d->cursor_);
909 ErrorList & el = buffer_.errorList("Class Switch");
910 cap::switchBetweenClasses(
911 oldlayout, buffer_.params().documentClassPtr(),
912 static_cast<InsetText &>(buffer_.inset()), el);
914 setCursor(backcur.asDocIterator(&buffer_));
916 buffer_.errors("Class Switch");
917 buffer_.updateLabels();
920 /** Return the change status at cursor position, taking in account the
921 * status at each level of the document iterator (a table in a deleted
922 * footnote is deleted).
923 * When \param outer is true, the top slice is not looked at.
925 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
927 size_t const depth = dit.depth() - (outer ? 1 : 0);
929 for (size_t i = 0 ; i < depth ; ++i) {
930 CursorSlice const & slice = dit[i];
931 if (!slice.inset().inMathed()
932 && slice.pos() < slice.paragraph().size()) {
933 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
934 if (ch != Change::UNCHANGED)
938 return Change::UNCHANGED;
942 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
944 // Can we use a readonly buffer?
945 if (buffer_.isReadonly()
946 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
947 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
948 flag.message(from_utf8(N_("Document is read-only")));
949 flag.setEnabled(false);
952 // Are we in a DELETED change-tracking region?
953 if (lookupChangeType(d->cursor_, true) == Change::DELETED
954 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
955 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
956 flag.message(from_utf8(N_("This portion of the document is deleted.")));
957 flag.setEnabled(false);
961 Cursor & cur = d->cursor_;
963 if (cur.getStatus(cmd, flag))
966 switch (cmd.action) {
968 // FIXME: This is a bit problematic because we don't check is this is a
969 // document BufferView or not for these LFUNs. We probably have to
970 // dispatch both to currentBufferView() and, if that fails,
971 // to documentBufferView(); same as we do know for current Buffer and
972 // document Buffer. Ideally those LFUN should go to Buffer as they*
973 // operate on the full Buffer and the cursor is only needed either for
974 // an Undo record or to restore a cursor position. But we don't know
975 // how to do that inside Buffer of course.
976 case LFUN_BUFFER_PARAMS_APPLY:
977 case LFUN_LAYOUT_MODULES_CLEAR:
978 case LFUN_LAYOUT_MODULE_ADD:
979 case LFUN_LAYOUT_RELOAD:
980 case LFUN_TEXTCLASS_APPLY:
981 case LFUN_TEXTCLASS_LOAD:
982 flag.setEnabled(!buffer_.isReadonly());
986 flag.setEnabled(buffer_.undo().hasUndoStack());
989 flag.setEnabled(buffer_.undo().hasRedoStack());
991 case LFUN_FILE_INSERT:
992 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
993 case LFUN_FILE_INSERT_PLAINTEXT:
994 case LFUN_BOOKMARK_SAVE:
995 // FIXME: Actually, these LFUNS should be moved to Text
996 flag.setEnabled(cur.inTexted());
999 case LFUN_FONT_STATE:
1000 case LFUN_LABEL_INSERT:
1001 case LFUN_INFO_INSERT:
1002 case LFUN_INSET_EDIT:
1003 case LFUN_PARAGRAPH_GOTO:
1004 case LFUN_NOTE_NEXT:
1005 case LFUN_REFERENCE_NEXT:
1006 case LFUN_WORD_FIND:
1007 case LFUN_WORD_FIND_FORWARD:
1008 case LFUN_WORD_FIND_BACKWARD:
1009 case LFUN_WORD_FINDADV:
1010 case LFUN_WORD_REPLACE:
1013 case LFUN_MARK_TOGGLE:
1014 case LFUN_SCREEN_RECENTER:
1015 case LFUN_SCREEN_SHOW_CURSOR:
1016 case LFUN_BIBTEX_DATABASE_ADD:
1017 case LFUN_BIBTEX_DATABASE_DEL:
1018 case LFUN_ALL_INSETS_TOGGLE:
1019 case LFUN_STATISTICS:
1020 case LFUN_BRANCH_ADD_INSERT:
1021 case LFUN_KEYMAP_OFF:
1022 case LFUN_KEYMAP_PRIMARY:
1023 case LFUN_KEYMAP_SECONDARY:
1024 case LFUN_KEYMAP_TOGGLE:
1025 flag.setEnabled(true);
1028 case LFUN_REGEXP_MODE:
1029 // FIXME: Test if current WorkArea is the search WorkArea
1030 flag.setEnabled(buffer().isInternal() && !cur.inRegexped() && !dynamic_cast<InsetERT*>(&cur.inset()));
1033 case LFUN_LABEL_COPY_AS_REF: {
1034 // if there is an inset at cursor, see whether it
1036 Inset * inset = cur.nextInset();
1037 if (!inset || !inset->getStatus(cur, cmd, flag))
1038 flag.setEnabled(false);
1042 case LFUN_LABEL_GOTO: {
1043 flag.setEnabled(!cmd.argument().empty()
1044 || getInsetByCode<InsetRef>(cur, REF_CODE));
1048 case LFUN_CHANGES_TRACK:
1049 flag.setEnabled(true);
1050 flag.setOnOff(buffer_.params().trackChanges);
1053 case LFUN_CHANGES_OUTPUT:
1054 flag.setEnabled(true);
1055 flag.setOnOff(buffer_.params().outputChanges);
1058 case LFUN_CHANGES_MERGE:
1059 case LFUN_CHANGE_NEXT:
1060 case LFUN_CHANGE_PREVIOUS:
1061 case LFUN_ALL_CHANGES_ACCEPT:
1062 case LFUN_ALL_CHANGES_REJECT:
1063 // TODO: context-sensitive enabling of LFUNs
1064 // In principle, these command should only be enabled if there
1065 // is a change in the document. However, without proper
1066 // optimizations, this will inevitably result in poor performance.
1067 flag.setEnabled(true);
1070 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1071 flag.setOnOff(buffer_.params().compressed);
1075 case LFUN_SCREEN_UP:
1076 case LFUN_SCREEN_DOWN:
1078 case LFUN_SCREEN_UP_SELECT:
1079 case LFUN_SCREEN_DOWN_SELECT:
1080 case LFUN_INSET_FORALL:
1081 flag.setEnabled(true);
1084 case LFUN_LAYOUT_TABULAR:
1085 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1089 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1092 case LFUN_LAYOUT_PARAGRAPH:
1093 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1096 case LFUN_DIALOG_SHOW_NEW_INSET:
1097 // FIXME: this is wrong, but I do not understand the
1099 if (cur.inset().lyxCode() == CAPTION_CODE)
1100 return cur.inset().getStatus(cur, cmd, flag);
1101 // FIXME we should consider passthru paragraphs too.
1102 flag.setEnabled(!cur.inset().getLayout().isPassThru());
1105 case LFUN_CITATION_INSERT: {
1106 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1107 // FIXME: This could turn in a recursive hell.
1108 // Shouldn't we use Buffer::getStatus() instead?
1109 flag.setEnabled(lyx::getStatus(fr).enabled());
1112 case LFUN_INSET_APPLY: {
1113 string const name = cmd.getArg(0);
1114 Inset * inset = editedInset(name);
1116 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1118 if (!inset->getStatus(cur, fr, fs)) {
1119 // Every inset is supposed to handle this
1120 LASSERT(false, break);
1124 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1125 flag |= lyx::getStatus(fr);
1131 flag.setEnabled(false);
1139 Inset * BufferView::editedInset(string const & name) const
1141 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1142 return it == d->edited_insets_.end() ? 0 : it->second;
1146 void BufferView::editInset(string const & name, Inset * inset)
1148 d->edited_insets_[name] = inset;
1152 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1154 //lyxerr << [ cmd = " << cmd << "]" << endl;
1156 // Make sure that the cached BufferView is correct.
1157 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1158 << " arg[" << to_utf8(cmd.argument()) << ']'
1159 << " x[" << cmd.x << ']'
1160 << " y[" << cmd.y << ']'
1161 << " button[" << cmd.button() << ']');
1163 string const argument = to_utf8(cmd.argument());
1164 Cursor & cur = d->cursor_;
1166 // Don't dispatch function that does not apply to internal buffers.
1167 if (buffer_.isInternal()
1168 && lyxaction.funcHasFlag(cmd.action, LyXAction::NoInternal))
1171 // We'll set this back to false if need be.
1172 bool dispatched = true;
1173 buffer_.undo().beginUndoGroup();
1175 switch (cmd.action) {
1177 case LFUN_BUFFER_PARAMS_APPLY: {
1178 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1179 cur.recordUndoFullDocument();
1180 istringstream ss(to_utf8(cmd.argument()));
1183 int const unknown_tokens = buffer_.readHeader(lex);
1184 if (unknown_tokens != 0) {
1185 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1186 << unknown_tokens << " unknown token"
1187 << (unknown_tokens == 1 ? "" : "s"));
1189 updateLayout(oldClass);
1191 // We are most certainly here because of a change in the document
1192 // It is then better to make sure that all dialogs are in sync with
1193 // current document settings.
1194 dr.update(Update::Force | Update::FitCursor);
1198 case LFUN_LAYOUT_MODULES_CLEAR: {
1199 DocumentClass const * const oldClass =
1200 buffer_.params().documentClassPtr();
1201 cur.recordUndoFullDocument();
1202 buffer_.params().clearLayoutModules();
1203 buffer_.params().makeDocumentClass();
1204 updateLayout(oldClass);
1205 dr.update(Update::Force | Update::FitCursor);
1209 case LFUN_LAYOUT_MODULE_ADD: {
1210 BufferParams const & params = buffer_.params();
1211 if (!params.moduleCanBeAdded(argument)) {
1212 LYXERR0("Module `" << argument <<
1213 "' cannot be added due to failed requirements or "
1214 "conflicts with installed modules.");
1217 DocumentClass const * const oldClass = params.documentClassPtr();
1218 cur.recordUndoFullDocument();
1219 buffer_.params().addLayoutModule(argument);
1220 buffer_.params().makeDocumentClass();
1221 updateLayout(oldClass);
1222 dr.update(Update::Force | Update::FitCursor);
1226 case LFUN_TEXTCLASS_APPLY: {
1227 if (!LayoutFileList::get().load(argument, buffer_.temppath()) &&
1228 !LayoutFileList::get().load(argument, buffer_.filePath()))
1231 LayoutFile const * old_layout = buffer_.params().baseClass();
1232 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1234 if (old_layout == new_layout)
1238 //Save the old, possibly modular, layout for use in conversion.
1239 DocumentClass const * const oldDocClass =
1240 buffer_.params().documentClassPtr();
1241 cur.recordUndoFullDocument();
1242 buffer_.params().setBaseClass(argument);
1243 buffer_.params().makeDocumentClass();
1244 updateLayout(oldDocClass);
1245 dr.update(Update::Force | Update::FitCursor);
1249 case LFUN_TEXTCLASS_LOAD:
1250 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1251 LayoutFileList::get().load(argument, buffer_.filePath());
1254 case LFUN_LAYOUT_RELOAD: {
1255 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1256 LayoutFileIndex bc = buffer_.params().baseClassID();
1257 LayoutFileList::get().reset(bc);
1258 buffer_.params().setBaseClass(bc);
1259 buffer_.params().makeDocumentClass();
1260 updateLayout(oldClass);
1261 dr.update(Update::Force | Update::FitCursor);
1266 dr.setMessage(_("Undo"));
1267 cur.clearSelection();
1268 if (!cur.textUndo())
1269 dr.setMessage(_("No further undo information"));
1271 dr.update(Update::Force | Update::FitCursor);
1275 dr.setMessage(_("Redo"));
1276 cur.clearSelection();
1277 if (!cur.textRedo())
1278 dr.setMessage(_("No further redo information"));
1280 dr.update(Update::Force | Update::FitCursor);
1283 case LFUN_FONT_STATE:
1284 dr.setMessage(cur.currentState());
1287 case LFUN_BOOKMARK_SAVE:
1288 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1291 case LFUN_LABEL_GOTO: {
1292 docstring label = cmd.argument();
1293 if (label.empty()) {
1295 getInsetByCode<InsetRef>(cur, REF_CODE);
1297 label = inset->getParam("reference");
1298 // persistent=false: use temp_bookmark
1307 case LFUN_INSET_EDIT: {
1308 FuncRequest fr(cmd);
1309 // if there is an inset at cursor, see whether it
1311 Inset * inset = cur.nextInset();
1313 inset->dispatch(cur, fr);
1314 // if it did not work, try the underlying inset.
1315 if (!inset || !cur.result().dispatched())
1318 // FIXME I'm adding the last break to solve a crash,
1319 // but that is obviously not right.
1320 if (!cur.result().dispatched())
1321 // It did not work too; no action needed.
1326 case LFUN_PARAGRAPH_GOTO: {
1327 int const id = convert<int>(cmd.getArg(0));
1328 int const pos = convert<int>(cmd.getArg(1));
1330 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1331 b = theBufferList().next(b)) {
1333 DocIterator dit = b->getParFromID(id);
1335 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1339 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1340 << " found in buffer `"
1341 << b->absFileName() << "'.");
1343 if (b == &buffer_) {
1347 dr.update(Update::Force | Update::FitCursor);
1349 // Switch to other buffer view and resend cmd
1350 theLyXFunc().dispatch(FuncRequest(
1351 LFUN_BUFFER_SWITCH, b->absFileName()));
1352 theLyXFunc().dispatch(cmd);
1359 case LFUN_NOTE_NEXT:
1360 gotoInset(this, NOTE_CODE, false);
1363 case LFUN_REFERENCE_NEXT: {
1364 vector<InsetCode> tmp;
1365 tmp.push_back(LABEL_CODE);
1366 tmp.push_back(REF_CODE);
1367 gotoInset(this, tmp, true);
1371 case LFUN_CHANGES_TRACK:
1372 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1375 case LFUN_CHANGES_OUTPUT:
1376 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1377 if (buffer_.params().outputChanges) {
1378 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1379 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1380 LaTeXFeatures::isAvailable("xcolor");
1382 if (!dvipost && !xcolorulem) {
1383 Alert::warning(_("Changes not shown in LaTeX output"),
1384 _("Changes will not be highlighted in LaTeX output, "
1385 "because neither dvipost nor xcolor/ulem are installed.\n"
1386 "Please install these packages or redefine "
1387 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1388 } else if (!xcolorulem) {
1389 Alert::warning(_("Changes not shown in LaTeX output"),
1390 _("Changes will not be highlighted in LaTeX output "
1391 "when using pdflatex, because xcolor and ulem are not installed.\n"
1392 "Please install both packages or redefine "
1393 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1398 case LFUN_CHANGE_NEXT:
1399 findNextChange(this);
1400 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1401 dr.update(Update::Force | Update::FitCursor);
1404 case LFUN_CHANGE_PREVIOUS:
1405 findPreviousChange(this);
1406 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1407 dr.update(Update::Force | Update::FitCursor);
1410 case LFUN_CHANGES_MERGE:
1411 if (findNextChange(this) || findPreviousChange(this)) {
1412 dr.update(Update::Force | Update::FitCursor);
1413 showDialog("changes");
1417 case LFUN_ALL_CHANGES_ACCEPT:
1418 // select complete document
1420 cur.selHandle(true);
1421 buffer_.text().cursorBottom(cur);
1422 // accept everything in a single step to support atomic undo
1423 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1424 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1425 dr.update(Update::Force | Update::FitCursor);
1428 case LFUN_ALL_CHANGES_REJECT:
1429 // select complete document
1431 cur.selHandle(true);
1432 buffer_.text().cursorBottom(cur);
1433 // reject everything in a single step to support atomic undo
1434 // Note: reject does not work recursively; the user may have to repeat the operation
1435 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1436 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1437 dr.update(Update::Force | Update::FitCursor);
1440 case LFUN_WORD_FIND_FORWARD:
1441 case LFUN_WORD_FIND_BACKWARD: {
1442 static docstring last_search;
1443 docstring searched_string;
1445 if (!cmd.argument().empty()) {
1446 last_search = cmd.argument();
1447 searched_string = cmd.argument();
1449 searched_string = last_search;
1452 if (searched_string.empty())
1455 bool const fw = cmd.action == LFUN_WORD_FIND_FORWARD;
1456 docstring const data =
1457 find2string(searched_string, true, false, fw);
1458 find(this, FuncRequest(LFUN_WORD_FIND, data));
1462 case LFUN_WORD_FIND: {
1463 FuncRequest req = cmd;
1464 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1465 req = d->search_request_cache_;
1466 if (req.argument().empty()) {
1467 theLyXFunc().dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1470 if (find(this, req))
1473 message(_("String not found!"));
1474 d->search_request_cache_ = req;
1478 case LFUN_WORD_REPLACE: {
1479 bool has_deleted = false;
1480 if (cur.selection()) {
1481 DocIterator beg = cur.selectionBegin();
1482 DocIterator end = cur.selectionEnd();
1483 if (beg.pit() == end.pit()) {
1484 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1486 && cur.paragraph().isDeleted(p))
1491 replace(this, cmd, has_deleted);
1495 case LFUN_WORD_FINDADV: {
1496 FindAndReplaceOptions opt;
1497 istringstream iss(to_utf8(cmd.argument()));
1499 if (findAdv(this, opt))
1507 cur.clearSelection();
1508 dr.setMessage(from_utf8(N_("Mark off")));
1512 cur.clearSelection();
1514 dr.setMessage(from_utf8(N_("Mark on")));
1517 case LFUN_MARK_TOGGLE:
1518 cur.setSelection(false);
1521 dr.setMessage(from_utf8(N_("Mark removed")));
1524 dr.setMessage(from_utf8(N_("Mark set")));
1529 case LFUN_SCREEN_SHOW_CURSOR:
1533 case LFUN_SCREEN_RECENTER:
1537 case LFUN_BIBTEX_DATABASE_ADD: {
1538 Cursor tmpcur = cur;
1539 findInset(tmpcur, BIBTEX_CODE, false);
1540 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1543 if (inset->addDatabase(cmd.argument()))
1544 buffer_.updateBibfilesCache();
1549 case LFUN_BIBTEX_DATABASE_DEL: {
1550 Cursor tmpcur = cur;
1551 findInset(tmpcur, BIBTEX_CODE, false);
1552 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1555 if (inset->delDatabase(cmd.argument()))
1556 buffer_.updateBibfilesCache();
1561 case LFUN_STATISTICS: {
1562 DocIterator from, to;
1563 if (cur.selection()) {
1564 from = cur.selectionBegin();
1565 to = cur.selectionEnd();
1567 from = doc_iterator_begin(&buffer_);
1568 to = doc_iterator_end(&buffer_);
1570 int const words = countWords(from, to);
1571 int const chars = countChars(from, to, false);
1572 int const chars_blanks = countChars(from, to, true);
1574 if (cur.selection())
1575 message = _("Statistics for the selection:");
1577 message = _("Statistics for the document:");
1580 message += bformat(_("%1$d words"), words);
1582 message += _("One word");
1584 if (chars_blanks != 1)
1585 message += bformat(_("%1$d characters (including blanks)"),
1588 message += _("One character (including blanks)");
1591 message += bformat(_("%1$d characters (excluding blanks)"),
1594 message += _("One character (excluding blanks)");
1596 Alert::information(_("Statistics"), message);
1600 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1601 // turn compression on/off
1602 buffer_.params().compressed = !buffer_.params().compressed;
1605 case LFUN_LABEL_COPY_AS_REF: {
1606 // if there is an inset at cursor, try to copy it
1607 Inset * inset = &cur.inset();
1608 if (!inset || !inset->asInsetMath())
1609 inset = cur.nextInset();
1611 FuncRequest tmpcmd = cmd;
1612 inset->dispatch(cur, tmpcmd);
1614 if (!cur.result().dispatched())
1615 // It did not work too; no action needed.
1617 cur.clearSelection();
1618 dr.update(Update::SinglePar | Update::FitCursor);
1622 case LFUN_SCREEN_UP:
1623 case LFUN_SCREEN_DOWN: {
1624 Point p = getPos(cur, cur.boundary());
1625 // This code has been commented out to enable to scroll down a
1626 // document, even if there are large insets in it (see bug #5465).
1627 /*if (p.y_ < 0 || p.y_ > height_) {
1628 // The cursor is off-screen so recenter before proceeding.
1630 p = getPos(cur, cur.boundary());
1632 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1633 ? -height_ : height_);
1634 if (cmd.action == LFUN_SCREEN_UP && scrolled > -height_)
1636 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1637 p = Point(width_, height_);
1639 bool const in_texted = cur.inTexted();
1641 buffer_.changed(true);
1642 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1643 true, cmd.action == LFUN_SCREEN_UP);
1644 //FIXME: what to do with cur.x_target()?
1645 bool update = in_texted && cur.bv().checkDepm(cur, old);
1648 dr.update(Update::Force | Update::FitCursor);
1656 case LFUN_SCREEN_UP_SELECT: {
1657 cur.selHandle(true);
1658 if (isTopScreen()) {
1659 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1663 int y = getPos(cur, cur.boundary()).y_;
1664 int const ymin = y - height_ + defaultRowHeight();
1665 while (y > ymin && cur.up())
1666 y = getPos(cur, cur.boundary()).y_;
1669 dr.update(Update::SinglePar | Update::FitCursor);
1673 case LFUN_SCREEN_DOWN_SELECT: {
1674 cur.selHandle(true);
1675 if (isBottomScreen()) {
1676 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1680 int y = getPos(cur, cur.boundary()).y_;
1681 int const ymax = y + height_ - defaultRowHeight();
1682 while (y < ymax && cur.down())
1683 y = getPos(cur, cur.boundary()).y_;
1686 dr.update(Update::SinglePar | Update::FitCursor);
1691 // This would be in Buffer class if only Cursor did not
1692 // require a bufferview
1693 case LFUN_INSET_FORALL: {
1694 docstring const name = from_utf8(cmd.getArg(0));
1695 string const commandstr = cmd.getLongArg(1);
1696 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1698 // an arbitrary number to limit number of iterations
1699 const int max_iter = 10000;
1701 Cursor & cur = d->cursor_;
1702 Cursor const savecur = cur;
1704 if (!cur.nextInset())
1706 cur.beginUndoGroup();
1707 while(cur && iterations < max_iter) {
1708 Inset * ins = cur.nextInset();
1711 docstring insname = ins->name();
1712 while (!insname.empty()) {
1713 if (insname == name || name == from_utf8("*")) {
1719 size_t const i = insname.rfind(':');
1720 if (i == string::npos)
1722 insname = insname.substr(0, i);
1729 dr.update(Update::Force);
1731 if (iterations >= max_iter) {
1733 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1735 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1740 case LFUN_ALL_INSETS_TOGGLE: {
1742 string const name = split(to_utf8(cmd.argument()), action, ' ');
1743 InsetCode const inset_code = insetCode(name);
1745 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1747 Inset & inset = cur.buffer()->inset();
1748 InsetIterator it = inset_iterator_begin(inset);
1749 InsetIterator const end = inset_iterator_end(inset);
1750 for (; it != end; ++it) {
1751 if (it->asInsetCollapsable()
1752 && (inset_code == NO_CODE
1753 || inset_code == it->lyxCode())) {
1754 Cursor tmpcur = cur;
1755 tmpcur.pushBackward(*it);
1756 it->dispatch(tmpcur, fr);
1759 dr.update(Update::Force | Update::FitCursor);
1763 case LFUN_BRANCH_ADD_INSERT: {
1764 docstring branch_name = from_utf8(cmd.getArg(0));
1765 if (branch_name.empty())
1766 if (!Alert::askForText(branch_name, _("Branch name")) ||
1767 branch_name.empty())
1770 DispatchResult drtmp;
1771 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1772 if (drtmp.error()) {
1773 Alert::warning(_("Branch already exists"), drtmp.message());
1776 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1780 case LFUN_KEYMAP_OFF:
1781 getIntl().keyMapOn(false);
1784 case LFUN_KEYMAP_PRIMARY:
1785 getIntl().keyMapPrim();
1788 case LFUN_KEYMAP_SECONDARY:
1789 getIntl().keyMapSec();
1792 case LFUN_KEYMAP_TOGGLE:
1793 getIntl().toggleKeyMap();
1796 case LFUN_DIALOG_SHOW_NEW_INSET: {
1797 string const name = cmd.getArg(0);
1798 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1799 if (decodeInsetParam(name, data, buffer_))
1800 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1802 lyxerr << "Inset type '" << name <<
1803 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1807 case LFUN_CITATION_INSERT: {
1808 if (argument.empty()) {
1809 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1812 // we can have one optional argument, delimited by '|'
1813 // citation-insert <key>|<text_before>
1814 // this should be enhanced to also support text_after
1815 // and citation style
1816 string arg = argument;
1818 if (contains(argument, "|")) {
1819 arg = token(argument, '|', 0);
1820 opt1 = token(argument, '|', 1);
1822 InsetCommandParams icp(CITE_CODE);
1823 icp["key"] = from_utf8(arg);
1825 icp["before"] = from_utf8(opt1);
1826 string icstr = InsetCommand::params2string("citation", icp);
1827 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1832 case LFUN_INSET_APPLY: {
1833 string const name = cmd.getArg(0);
1834 Inset * inset = editedInset(name);
1836 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1840 // put cursor in front of inset.
1841 if (!setCursorFromInset(inset)) {
1842 LASSERT(false, break);
1845 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1846 inset->dispatch(cur, fr);
1847 dr.update(Update::SinglePar | Update::FitCursor);
1856 buffer_.undo().endUndoGroup();
1857 dr.dispatched(dispatched);
1862 docstring const BufferView::requestSelection()
1864 Cursor & cur = d->cursor_;
1866 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1867 if (!cur.selection()) {
1868 d->xsel_cache_.set = false;
1872 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1873 if (!d->xsel_cache_.set ||
1874 cur.top() != d->xsel_cache_.cursor ||
1875 cur.anchor_.top() != d->xsel_cache_.anchor)
1877 d->xsel_cache_.cursor = cur.top();
1878 d->xsel_cache_.anchor = cur.anchor_.top();
1879 d->xsel_cache_.set = cur.selection();
1880 return cur.selectionAsString(false);
1886 void BufferView::clearSelection()
1888 d->cursor_.clearSelection();
1889 // Clear the selection buffer. Otherwise a subsequent
1890 // middle-mouse-button paste would use the selection buffer,
1891 // not the more current external selection.
1892 cap::clearSelection();
1893 d->xsel_cache_.set = false;
1894 // The buffer did not really change, but this causes the
1895 // redraw we need because we cleared the selection above.
1896 buffer_.changed(false);
1900 void BufferView::resize(int width, int height)
1902 // Update from work area
1906 // Clear the paragraph height cache.
1907 d->par_height_.clear();
1908 // Redo the metrics.
1913 Inset const * BufferView::getCoveringInset(Text const & text,
1916 TextMetrics & tm = d->text_metrics_[&text];
1917 Inset * inset = tm.checkInsetHit(x, y);
1921 if (!inset->descendable(*this))
1922 // No need to go further down if the inset is not
1926 size_t cell_number = inset->nargs();
1927 // Check all the inner cell.
1928 for (size_t i = 0; i != cell_number; ++i) {
1929 Text const * inner_text = inset->getText(i);
1932 Inset const * inset_deeper =
1933 getCoveringInset(*inner_text, x, y);
1935 return inset_deeper;
1943 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1945 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1947 // This is only called for mouse related events including
1948 // LFUN_FILE_OPEN generated by drag-and-drop.
1949 FuncRequest cmd = cmd0;
1951 Cursor old = cursor();
1953 cur.push(buffer_.inset());
1954 cur.setSelection(d->cursor_.selection());
1956 // Either the inset under the cursor or the
1957 // surrounding Text will handle this event.
1959 // make sure we stay within the screen...
1960 cmd.y = min(max(cmd.y, -1), height_);
1962 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1964 // Get inset under mouse, if there is one.
1965 Inset const * covering_inset =
1966 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1967 if (covering_inset == d->last_inset_)
1968 // Same inset, no need to do anything...
1971 bool need_redraw = false;
1972 // const_cast because of setMouseHover().
1973 Inset * inset = const_cast<Inset *>(covering_inset);
1975 // Remove the hint on the last hovered inset (if any).
1976 need_redraw |= d->last_inset_->setMouseHover(false);
1978 // Highlighted the newly hovered inset (if any).
1979 need_redraw |= inset->setMouseHover(true);
1980 d->last_inset_ = inset;
1984 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1985 << cmd.x << ", " << cmd.y << ")");
1987 d->update_strategy_ = DecorationUpdate;
1989 // This event (moving without mouse click) is not passed further.
1990 // This should be changed if it is further utilized.
1991 buffer_.changed(false);
1995 // Build temporary cursor.
1996 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1998 // Put anchor at the same position.
2001 cur.beginUndoGroup();
2003 // Try to dispatch to an non-editable inset near this position
2004 // via the temp cursor. If the inset wishes to change the real
2005 // cursor it has to do so explicitly by using
2006 // cur.bv().cursor() = cur; (or similar)
2008 inset->dispatch(cur, cmd);
2010 // Now dispatch to the temporary cursor. If the real cursor should
2011 // be modified, the inset's dispatch has to do so explicitly.
2012 if (!inset || !cur.result().dispatched())
2017 // Notify left insets
2020 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
2022 cursor().fixIfBroken();
2025 // Do we have a selection?
2026 theSelection().haveSelection(cursor().selection());
2028 // If the command has been dispatched,
2029 if (cur.result().dispatched() || cur.result().update())
2030 processUpdateFlags(cur.result().update());
2034 void BufferView::lfunScroll(FuncRequest const & cmd)
2036 string const scroll_type = cmd.getArg(0);
2037 int const scroll_step =
2038 (scroll_type == "line") ? d->scrollbarParameters_.single_step
2039 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
2040 if (scroll_step == 0)
2042 string const scroll_quantity = cmd.getArg(1);
2043 if (scroll_quantity == "up")
2044 scrollUp(scroll_step);
2045 else if (scroll_quantity == "down")
2046 scrollDown(scroll_step);
2048 int const scroll_value = convert<int>(scroll_quantity);
2050 scroll(scroll_step * scroll_value);
2052 buffer_.changed(true);
2056 int BufferView::minVisiblePart()
2058 return 2 * defaultRowHeight();
2062 int BufferView::scroll(int y)
2065 return scrollDown(y);
2067 return scrollUp(-y);
2072 int BufferView::scrollDown(int offset)
2074 Text * text = &buffer_.text();
2075 TextMetrics & tm = d->text_metrics_[text];
2076 int const ymax = height_ + offset;
2078 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2079 int bottom_pos = last.second->position() + last.second->descent();
2080 if (lyxrc.scroll_below_document)
2081 bottom_pos += height_ - minVisiblePart();
2082 if (last.first + 1 == int(text->paragraphs().size())) {
2083 if (bottom_pos <= height_)
2085 offset = min(offset, bottom_pos - height_);
2088 if (bottom_pos > ymax)
2090 tm.newParMetricsDown();
2092 d->anchor_ypos_ -= offset;
2097 int BufferView::scrollUp(int offset)
2099 Text * text = &buffer_.text();
2100 TextMetrics & tm = d->text_metrics_[text];
2101 int ymin = - offset;
2103 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2104 int top_pos = first.second->position() - first.second->ascent();
2105 if (first.first == 0) {
2108 offset = min(offset, - top_pos);
2113 tm.newParMetricsUp();
2115 d->anchor_ypos_ += offset;
2120 void BufferView::setCursorFromRow(int row)
2125 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
2129 buffer_.text().setCursor(d->cursor_, 0, 0);
2131 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
2136 bool BufferView::setCursorFromInset(Inset const * inset)
2138 // are we already there?
2139 if (cursor().nextInset() == inset)
2142 // Inset is not at cursor position. Find it in the document.
2145 while (cur && cur.nextInset() != inset)
2156 void BufferView::gotoLabel(docstring const & label)
2158 std::vector<Buffer const *> bufs = buffer().allRelatives();
2159 std::vector<Buffer const *>::iterator it = bufs.begin();
2160 for (; it != bufs.end(); ++it) {
2161 Buffer const * buf = *it;
2164 Toc & toc = buf->tocBackend().toc("label");
2165 TocIterator toc_it = toc.begin();
2166 TocIterator end = toc.end();
2167 for (; toc_it != end; ++toc_it) {
2168 if (label == toc_it->str()) {
2169 lyx::dispatch(toc_it->action());
2177 TextMetrics const & BufferView::textMetrics(Text const * t) const
2179 return const_cast<BufferView *>(this)->textMetrics(t);
2183 TextMetrics & BufferView::textMetrics(Text const * t)
2185 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2186 if (tmc_it == d->text_metrics_.end()) {
2187 tmc_it = d->text_metrics_.insert(
2188 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2190 return tmc_it->second;
2194 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2197 return textMetrics(t).parMetrics(pit);
2201 int BufferView::workHeight() const
2207 void BufferView::setCursor(DocIterator const & dit)
2210 size_t const n = dit.depth();
2211 for (size_t i = 0; i < n; ++i)
2212 dit[i].inset().edit(d->cursor_, true);
2214 d->cursor_.setCursor(dit);
2215 d->cursor_.setSelection(false);
2219 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2221 // Would be wrong to delete anything if we have a selection.
2222 if (cur.selection())
2225 bool need_anchor_change = false;
2226 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2227 need_anchor_change);
2229 if (need_anchor_change)
2237 buffer_.updateLabels();
2238 buffer_.changed(true);
2243 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2245 LASSERT(&cur.bv() == this, /**/);
2248 // this event will clear selection so we save selection for
2249 // persistent selection
2250 cap::saveSelection(cursor());
2252 d->cursor_.macroModeClose();
2254 // Has the cursor just left the inset?
2255 bool leftinset = (&d->cursor_.inset() != &cur.inset());
2257 d->cursor_.fixIfBroken();
2259 // FIXME: shift-mouse selection doesn't work well across insets.
2260 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
2262 // do the dEPM magic if needed
2263 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2264 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2265 // the leftinset bool would not be necessary (badcursor instead).
2266 bool update = leftinset;
2267 if (!do_selection && d->cursor_.inTexted())
2268 update |= checkDepm(cur, d->cursor_);
2271 d->cursor_.resetAnchor();
2272 d->cursor_.setCursor(cur);
2273 d->cursor_.boundary(cur.boundary());
2275 d->cursor_.setSelection();
2277 d->cursor_.clearSelection();
2279 d->cursor_.finishUndo();
2280 d->cursor_.setCurrentFont();
2285 void BufferView::putSelectionAt(DocIterator const & cur,
2286 int length, bool backwards)
2288 d->cursor_.clearSelection();
2294 d->cursor_.pos() += length;
2295 d->cursor_.setSelection(d->cursor_, -length);
2297 d->cursor_.setSelection(d->cursor_, length);
2299 // Ensure a redraw happens in any case because the new selection could
2300 // possibly be on the same screen as the previous selection.
2301 processUpdateFlags(Update::Force | Update::FitCursor);
2305 Cursor & BufferView::cursor()
2311 Cursor const & BufferView::cursor() const
2317 pit_type BufferView::anchor_ref() const
2319 return d->anchor_pit_;
2323 bool BufferView::singleParUpdate()
2325 Text & buftext = buffer_.text();
2326 pit_type const bottom_pit = d->cursor_.bottom().pit();
2327 TextMetrics & tm = textMetrics(&buftext);
2328 int old_height = tm.parMetrics(bottom_pit).height();
2330 // make sure inline completion pointer is ok
2331 if (d->inlineCompletionPos_.fixIfBroken())
2332 d->inlineCompletionPos_ = DocIterator();
2334 // In Single Paragraph mode, rebreak only
2335 // the (main text, not inset!) paragraph containing the cursor.
2336 // (if this paragraph contains insets etc., rebreaking will
2337 // recursively descend)
2338 tm.redoParagraph(bottom_pit);
2339 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2340 if (pm.height() != old_height)
2341 // Paragraph height has changed so we cannot proceed to
2342 // the singlePar optimisation.
2345 d->update_strategy_ = SingleParUpdate;
2347 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2348 << " y2: " << pm.position() + pm.descent()
2349 << " pit: " << bottom_pit
2350 << " singlepar: 1");
2355 void BufferView::updateMetrics()
2357 if (height_ == 0 || width_ == 0)
2360 Text & buftext = buffer_.text();
2361 pit_type const npit = int(buftext.paragraphs().size());
2363 // Clear out the position cache in case of full screen redraw,
2364 d->coord_cache_.clear();
2366 // Clear out paragraph metrics to avoid having invalid metrics
2367 // in the cache from paragraphs not relayouted below
2368 // The complete text metrics will be redone.
2369 d->text_metrics_.clear();
2371 TextMetrics & tm = textMetrics(&buftext);
2373 // make sure inline completion pointer is ok
2374 if (d->inlineCompletionPos_.fixIfBroken())
2375 d->inlineCompletionPos_ = DocIterator();
2377 if (d->anchor_pit_ >= npit)
2378 // The anchor pit must have been deleted...
2379 d->anchor_pit_ = npit - 1;
2381 // Rebreak anchor paragraph.
2382 tm.redoParagraph(d->anchor_pit_);
2383 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2386 if (d->anchor_pit_ == 0) {
2387 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2389 // Complete buffer visible? Then it's easy.
2390 if (scrollRange == 0)
2391 d->anchor_ypos_ = anchor_pm.ascent();
2393 // FIXME: Some clever handling needed to show
2394 // the _first_ paragraph up to the top if the cursor is
2395 // in the first line.
2397 anchor_pm.setPosition(d->anchor_ypos_);
2399 LYXERR(Debug::PAINTING, "metrics: "
2400 << " anchor pit = " << d->anchor_pit_
2401 << " anchor ypos = " << d->anchor_ypos_);
2403 // Redo paragraphs above anchor if necessary.
2404 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2405 // We are now just above the anchor paragraph.
2406 pit_type pit1 = d->anchor_pit_ - 1;
2407 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2408 tm.redoParagraph(pit1);
2409 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2411 // Save the paragraph position in the cache.
2416 // Redo paragraphs below the anchor if necessary.
2417 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2418 // We are now just below the anchor paragraph.
2419 pit_type pit2 = d->anchor_pit_ + 1;
2420 for (; pit2 < npit && y2 <= height_; ++pit2) {
2421 tm.redoParagraph(pit2);
2422 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2424 // Save the paragraph position in the cache.
2429 LYXERR(Debug::PAINTING, "Metrics: "
2430 << " anchor pit = " << d->anchor_pit_
2431 << " anchor ypos = " << d->anchor_ypos_
2434 << " pit1 = " << pit1
2435 << " pit2 = " << pit2);
2437 d->update_strategy_ = FullScreenUpdate;
2439 if (lyxerr.debugging(Debug::WORKAREA)) {
2440 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2441 d->coord_cache_.dump();
2446 void BufferView::insertLyXFile(FileName const & fname)
2448 LASSERT(d->cursor_.inTexted(), /**/);
2450 // Get absolute path of file and add ".lyx"
2451 // to the filename if necessary
2452 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2454 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2455 // emit message signal.
2456 message(bformat(_("Inserting document %1$s..."), disp_fn));
2459 Buffer buf("", false);
2460 if (buf.loadLyXFile(filename)) {
2461 ErrorList & el = buffer_.errorList("Parse");
2462 // Copy the inserted document error list into the current buffer one.
2463 el = buf.errorList("Parse");
2464 buffer_.undo().recordUndo(d->cursor_);
2465 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2466 buf.params().documentClassPtr(), el);
2467 res = _("Document %1$s inserted.");
2469 res = _("Could not insert document %1$s");
2472 buffer_.changed(true);
2473 // emit message signal.
2474 message(bformat(res, disp_fn));
2475 buffer_.errors("Parse");
2479 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2485 // Addup contribution of nested insets, from inside to outside,
2486 // keeping the outer paragraph for a special handling below
2487 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2488 CursorSlice const & sl = dit[i];
2492 // get relative position inside sl.inset()
2493 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2495 // Make relative position inside of the edited inset relative to sl.inset()
2499 // In case of an RTL inset, the edited inset will be positioned to the left
2502 bool boundary_i = boundary && i + 1 == dit.depth();
2503 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2508 // remember width for the case that sl.inset() is positioned in an RTL inset
2509 if (i && dit[i - 1].text()) {
2510 // If this Inset is inside a Text Inset, retrieve the Dimension
2511 // from the containing text instead of using Inset::dimension() which
2512 // might not be implemented.
2513 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2514 // elimination of Inset::dim_ cache. This coordOffset() method needs
2515 // to be rewritten in light of the new design.
2516 Dimension const & dim = parMetrics(dit[i - 1].text(),
2517 dit[i - 1].pit()).insetDimension(&sl.inset());
2520 Dimension const dim = sl.inset().dimension(*this);
2524 //lyxerr << "Cursor::getPos, i: "
2525 // << i << " x: " << xx << " y: " << y << endl;
2528 // Add contribution of initial rows of outermost paragraph
2529 CursorSlice const & sl = dit[0];
2530 TextMetrics const & tm = textMetrics(sl.text());
2531 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2532 LASSERT(!pm.rows().empty(), /**/);
2533 y -= pm.rows()[0].ascent();
2535 // FIXME: document this mess
2537 if (sl.pos() > 0 && dit.depth() == 1) {
2539 if (pos && boundary)
2541 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2542 rend = pm.pos2row(pos);
2544 rend = pm.pos2row(sl.pos());
2546 size_t rend = pm.pos2row(sl.pos());
2548 for (size_t rit = 0; rit != rend; ++rit)
2549 y += pm.rows()[rit].height();
2550 y += pm.rows()[rend].ascent();
2552 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2554 // Make relative position from the nested inset now bufferview absolute.
2555 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2558 // In the RTL case place the nested inset at the left of the cursor in
2559 // the outer paragraph
2560 bool boundary_1 = boundary && 1 == dit.depth();
2561 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2569 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2571 if (!paragraphVisible(dit))
2572 return Point(-1, -1);
2574 CursorSlice const & bot = dit.bottom();
2575 TextMetrics const & tm = textMetrics(bot.text());
2577 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2578 p.y_ += tm.parMetrics(bot.pit()).position();
2583 bool BufferView::paragraphVisible(DocIterator const & dit) const
2585 CursorSlice const & bot = dit.bottom();
2586 TextMetrics const & tm = textMetrics(bot.text());
2588 return tm.contains(bot.pit());
2592 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2594 Cursor const & cur = cursor();
2595 Font const font = cur.getFont();
2596 frontend::FontMetrics const & fm = theFontMetrics(font);
2597 int const asc = fm.maxAscent();
2598 int const des = fm.maxDescent();
2600 p = getPos(cur, cur.boundary());
2605 bool BufferView::cursorInView(Point const & p, int h) const
2607 Cursor const & cur = cursor();
2608 // does the cursor touch the screen ?
2609 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2615 void BufferView::draw(frontend::Painter & pain)
2617 if (height_ == 0 || width_ == 0)
2619 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2621 Text & text = buffer_.text();
2622 TextMetrics const & tm = d->text_metrics_[&text];
2623 int const y = tm.first().second->position();
2624 PainterInfo pi(this, pain);
2626 switch (d->update_strategy_) {
2628 case NoScreenUpdate:
2629 // If no screen painting is actually needed, only some the different
2630 // coordinates of insets and paragraphs needs to be updated.
2631 pi.full_repaint = true;
2632 pi.pain.setDrawingEnabled(false);
2636 case SingleParUpdate:
2637 pi.full_repaint = false;
2638 // In general, only the current row of the outermost paragraph
2639 // will be redrawn. Particular cases where selection spans
2640 // multiple paragraph are correctly detected in TextMetrics.
2644 case DecorationUpdate:
2645 // FIXME: We should also distinguish DecorationUpdate to avoid text
2646 // drawing if possible. This is not possible to do easily right now
2647 // because of the single backing pixmap.
2649 case FullScreenUpdate:
2650 // The whole screen, including insets, will be refreshed.
2651 pi.full_repaint = true;
2653 // Clear background.
2654 pain.fillRectangle(0, 0, width_, height_,
2655 pi.backgroundColor(&buffer_.inset()));
2660 // and possibly grey out below
2661 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2662 int const y2 = lastpm.second->position() + lastpm.second->descent();
2665 Color color = buffer().isInternal()
2666 ? Color_background : Color_bottomarea;
2667 pain.fillRectangle(0, y2, width_, height_ - y2, color);
2671 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2673 // The scrollbar needs an update.
2676 // Normalize anchor for next time
2677 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2678 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2679 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2680 ParagraphMetrics const & pm = tm.parMetrics(pit);
2681 if (pm.position() + pm.descent() > 0) {
2682 d->anchor_pit_ = pit;
2683 d->anchor_ypos_ = pm.position();
2687 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2688 << " anchor ypos = " << d->anchor_ypos_);
2692 void BufferView::message(docstring const & msg)
2695 d->gui_->message(msg);
2699 void BufferView::showDialog(string const & name)
2702 d->gui_->showDialog(name, string());
2706 void BufferView::showDialog(string const & name,
2707 string const & data, Inset * inset)
2710 d->gui_->showDialog(name, data, inset);
2714 void BufferView::updateDialog(string const & name, string const & data)
2717 d->gui_->updateDialog(name, data);
2721 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2727 // FIXME: Move this out of BufferView again
2728 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2730 if (!fname.isReadableFile()) {
2731 docstring const error = from_ascii(strerror(errno));
2732 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2733 docstring const text =
2734 bformat(_("Could not read the specified document\n"
2735 "%1$s\ndue to the error: %2$s"), file, error);
2736 Alert::error(_("Could not read file"), text);
2740 if (!fname.isReadableFile()) {
2741 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2742 docstring const text =
2743 bformat(_("%1$s\n is not readable."), file);
2744 Alert::error(_("Could not open file"), text);
2748 // FIXME UNICODE: We don't know the encoding of the file
2749 docstring file_content = fname.fileContents("UTF-8");
2750 if (file_content.empty()) {
2751 Alert::error(_("Reading not UTF-8 encoded file"),
2752 _("The file is not UTF-8 encoded.\n"
2753 "It will be read as local 8Bit-encoded.\n"
2754 "If this does not give the correct result\n"
2755 "then please change the encoding of the file\n"
2756 "to UTF-8 with a program other than LyX.\n"));
2757 file_content = fname.fileContents("local8bit");
2760 return normalize_c(file_content);
2764 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2766 docstring const tmpstr = contentsOfPlaintextFile(f);
2771 Cursor & cur = cursor();
2772 cap::replaceSelection(cur);
2773 buffer_.undo().recordUndo(cur);
2775 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2777 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2779 buffer_.changed(true);
2783 docstring const & BufferView::inlineCompletion() const
2785 return d->inlineCompletion_;
2789 size_t const & BufferView::inlineCompletionUniqueChars() const
2791 return d->inlineCompletionUniqueChars_;
2795 DocIterator const & BufferView::inlineCompletionPos() const
2797 return d->inlineCompletionPos_;
2801 bool samePar(DocIterator const & a, DocIterator const & b)
2803 if (a.empty() && b.empty())
2805 if (a.empty() || b.empty())
2807 if (a.depth() != b.depth())
2809 return &a.innerParagraph() == &b.innerParagraph();
2813 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2814 docstring const & completion, size_t uniqueChars)
2816 uniqueChars = min(completion.size(), uniqueChars);
2817 bool changed = d->inlineCompletion_ != completion
2818 || d->inlineCompletionUniqueChars_ != uniqueChars;
2819 bool singlePar = true;
2820 d->inlineCompletion_ = completion;
2821 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2823 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2826 DocIterator const & old = d->inlineCompletionPos_;
2828 //lyxerr << "inlineCompletionPos changed" << std::endl;
2829 // old or pos are in another paragraph?
2830 if ((!samePar(cur, pos) && !pos.empty())
2831 || (!samePar(cur, old) && !old.empty())) {
2833 //lyxerr << "different paragraph" << std::endl;
2835 d->inlineCompletionPos_ = pos;
2840 if (singlePar && !(cur.disp_.update() & Update::Force))
2841 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2843 cur.updateFlags(cur.disp_.update() | Update::Force);