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/InsetRef.h"
62 #include "insets/InsetText.h"
63 #include "insets/InsetNote.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 "graphics/Previews.h"
74 #include "support/convert.h"
75 #include "support/debug.h"
76 #include "support/ExceptionMessage.h"
77 #include "support/filetools.h"
78 #include "support/gettext.h"
79 #include "support/lstrings.h"
80 #include "support/Package.h"
81 #include "support/types.h"
91 using namespace lyx::support;
95 namespace Alert = frontend::Alert;
99 /// Return an inset of this class if it exists at the current cursor position
101 T * getInsetByCode(Cursor const & cur, InsetCode code)
103 DocIterator it = cur;
104 Inset * inset = it.nextInset();
105 if (inset && inset->lyxCode() == code)
106 return static_cast<T*>(inset);
111 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
114 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
115 docstring const & contents)
117 DocIterator tmpdit = dit;
120 Inset const * inset = tmpdit.nextInset();
122 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
123 && (contents.empty() ||
124 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
128 tmpdit.forwardInset();
135 /// Looks for next inset with one of the given codes.
136 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
140 DocIterator tmpdit = dit;
141 tmpdit.forwardInset();
146 Inset const * inset = tmpdit.nextInset();
148 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
149 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
153 if (!findNextInset(tmpdit, codes, contents)) {
154 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
155 Inset * inset = &tmpdit.bottom().inset();
156 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
157 if (!findNextInset(tmpdit, codes, contents))
169 /// Looks for next inset with the given code
170 void findInset(DocIterator & dit, InsetCode code, bool same_content)
172 findInset(dit, vector<InsetCode>(1, code), same_content);
176 /// Moves cursor to the next inset with one of the given codes.
177 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
180 Cursor tmpcur = bv->cursor();
181 if (!findInset(tmpcur, codes, same_content)) {
182 bv->cursor().message(_("No more insets"));
186 tmpcur.clearSelection();
187 bv->setCursor(tmpcur);
192 /// Moves cursor to the next inset with given code.
193 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
195 gotoInset(bv, vector<InsetCode>(1, code), same_content);
199 /// A map from a Text to the associated text metrics
200 typedef map<Text const *, TextMetrics> TextMetricsCache;
202 enum ScreenUpdateStrategy {
212 /////////////////////////////////////////////////////////////////////
216 /////////////////////////////////////////////////////////////////////
218 struct BufferView::Private
220 Private(BufferView & bv): wh_(0), cursor_(bv),
221 anchor_pit_(0), anchor_ypos_(0),
222 inlineCompletionUniqueChars_(0),
223 last_inset_(0), bookmark_edit_position_(0), gui_(0)
227 ScrollbarParameters scrollbarParameters_;
229 ScreenUpdateStrategy update_strategy_;
231 CoordCache coord_cache_;
233 /// Estimated average par height for scrollbar.
235 /// this is used to handle XSelection events in the right manner.
244 pit_type anchor_pit_;
248 vector<int> par_height_;
251 DocIterator inlineCompletionPos_;
253 docstring inlineCompletion_;
255 size_t inlineCompletionUniqueChars_;
257 /// keyboard mapping object.
260 /// last visited inset.
261 /** kept to send setMouseHover(false).
262 * Not owned, so don't delete.
266 // cache for id of the paragraph which was edited the last time
267 int bookmark_edit_position_;
269 mutable TextMetricsCache text_metrics_;
272 /** Not owned, so don't delete.
274 frontend::GuiBufferViewDelegate * gui_;
276 /// Cache for Find Next
277 FuncRequest search_request_cache_;
280 map<string, Inset *> edited_insets_;
284 BufferView::BufferView(Buffer & buf)
285 : width_(0), height_(0), full_screen_(false), buffer_(buf),
286 d(new Private(*this))
288 d->xsel_cache_.set = false;
289 d->intl_.initKeyMapper(lyxrc.use_kbmap);
291 d->cursor_.setBuffer(&buf);
292 d->cursor_.push(buffer_.inset());
293 d->cursor_.resetAnchor();
294 d->cursor_.setCurrentFont();
296 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
297 thePreviews().generateBufferPreviews(buffer_);
301 BufferView::~BufferView()
303 // current buffer is going to be switched-off, save cursor pos
304 // Ideally, the whole cursor stack should be saved, but session
305 // currently can only handle bottom (whole document) level pit and pos.
306 // That is to say, if a cursor is in a nested inset, it will be
307 // restore to the left of the top level inset.
308 LastFilePosSection::FilePos fp;
309 fp.pit = d->cursor_.bottom().pit();
310 fp.pos = d->cursor_.bottom().pos();
311 theSession().lastFilePos().save(buffer_.fileName(), fp);
317 int BufferView::rightMargin() const
319 // The additional test for the case the outliner is opened.
321 !lyxrc.full_screen_limit ||
322 width_ < lyxrc.full_screen_width + 20)
325 return (width_ - lyxrc.full_screen_width) / 2;
329 int BufferView::leftMargin() const
331 return rightMargin();
335 bool BufferView::isTopScreen() const
337 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
341 bool BufferView::isBottomScreen() const
343 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
347 Intl & BufferView::getIntl()
353 Intl const & BufferView::getIntl() const
359 CoordCache & BufferView::coordCache()
361 return d->coord_cache_;
365 CoordCache const & BufferView::coordCache() const
367 return d->coord_cache_;
371 Buffer & BufferView::buffer()
377 Buffer const & BufferView::buffer() const
383 bool BufferView::fitCursor()
385 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
386 frontend::FontMetrics const & fm =
387 theFontMetrics(d->cursor_.getFont().fontInfo());
388 int const asc = fm.maxAscent();
389 int const des = fm.maxDescent();
390 Point const p = getPos(d->cursor_, d->cursor_.boundary());
391 if (p.y_ - asc >= 0 && p.y_ + des < height_)
398 void BufferView::processUpdateFlags(Update::flags flags)
400 // last_inset_ points to the last visited inset. This pointer may become
401 // invalid because of keyboard editing. Since all such operations
402 // causes screen update(), I reset last_inset_ to avoid such a problem.
404 // This is close to a hot-path.
405 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
406 << "[fitcursor = " << (flags & Update::FitCursor)
407 << ", forceupdate = " << (flags & Update::Force)
408 << ", singlepar = " << (flags & Update::SinglePar)
409 << "] buffer: " << &buffer_);
411 buffer_.updateMacros();
413 // Now do the first drawing step if needed. This consists on updating
414 // the CoordCache in updateMetrics().
415 // The second drawing step is done in WorkArea::redraw() if needed.
417 // Case when no explicit update is requested.
419 // no need to redraw anything.
420 d->update_strategy_ = NoScreenUpdate;
424 if (flags == Update::Decoration) {
425 d->update_strategy_ = DecorationUpdate;
426 buffer_.changed(false);
430 if (flags == Update::FitCursor
431 || flags == (Update::Decoration | Update::FitCursor)) {
432 // tell the frontend to update the screen if needed.
437 if (flags & Update::Decoration) {
438 d->update_strategy_ = DecorationUpdate;
439 buffer_.changed(false);
442 // no screen update is needed.
443 d->update_strategy_ = NoScreenUpdate;
447 bool const full_metrics = flags & Update::Force || !singleParUpdate();
450 // We have to update the full screen metrics.
453 if (!(flags & Update::FitCursor)) {
454 // Nothing to do anymore. Trigger a redraw and return
455 buffer_.changed(false);
459 // updateMetrics() does not update paragraph position
460 // This is done at draw() time. So we need a redraw!
461 buffer_.changed(false);
464 // The cursor is off screen so ensure it is visible.
471 void BufferView::updateScrollbar()
473 if (height_ == 0 && width_ == 0)
476 // We prefer fixed size line scrolling.
477 d->scrollbarParameters_.single_step = defaultRowHeight();
478 // We prefer full screen page scrolling.
479 d->scrollbarParameters_.page_step = height_;
481 Text & t = buffer_.text();
482 TextMetrics & tm = d->text_metrics_[&t];
484 LYXERR(Debug::GUI, " Updating scrollbar: height: "
485 << t.paragraphs().size()
486 << " curr par: " << d->cursor_.bottom().pit()
487 << " default height " << defaultRowHeight());
489 size_t const parsize = t.paragraphs().size();
490 if (d->par_height_.size() != parsize) {
491 d->par_height_.clear();
492 // FIXME: We assume a default paragraph height of 2 rows. This
493 // should probably be pondered with the screen width.
494 d->par_height_.resize(parsize, defaultRowHeight() * 2);
497 // Look at paragraph heights on-screen
498 pair<pit_type, ParagraphMetrics const *> first = tm.first();
499 pair<pit_type, ParagraphMetrics const *> last = tm.last();
500 for (pit_type pit = first.first; pit <= last.first; ++pit) {
501 d->par_height_[pit] = tm.parMetrics(pit).height();
502 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
503 << d->par_height_[pit]);
506 int top_pos = first.second->position() - first.second->ascent();
507 int bottom_pos = last.second->position() + last.second->descent();
508 bool first_visible = first.first == 0 && top_pos >= 0;
509 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
510 if (first_visible && last_visible) {
511 d->scrollbarParameters_.min = 0;
512 d->scrollbarParameters_.max = 0;
516 d->scrollbarParameters_.min = top_pos;
517 for (size_t i = 0; i != size_t(first.first); ++i)
518 d->scrollbarParameters_.min -= d->par_height_[i];
519 d->scrollbarParameters_.max = bottom_pos;
520 for (size_t i = last.first + 1; i != parsize; ++i)
521 d->scrollbarParameters_.max += d->par_height_[i];
523 d->scrollbarParameters_.position = 0;
524 // The reference is the top position so we remove one page.
525 if (lyxrc.scroll_below_document)
526 d->scrollbarParameters_.max -= minVisiblePart();
528 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
532 ScrollbarParameters const & BufferView::scrollbarParameters() const
534 return d->scrollbarParameters_;
538 docstring BufferView::toolTip(int x, int y) const
540 // Get inset under mouse, if there is one.
541 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
543 // No inset, no tooltip...
545 return covering_inset->toolTip(*this, x, y);
549 docstring BufferView::contextMenu(int x, int y) const
551 //If there is a selection, return the containing inset menu
552 if (d->cursor_.selection())
553 return d->cursor_.inset().contextMenu(*this, x, y);
555 // Get inset under mouse, if there is one.
556 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
558 return covering_inset->contextMenu(*this, x, y);
560 return buffer_.inset().contextMenu(*this, x, y);
564 void BufferView::scrollDocView(int value)
566 int const offset = value - d->scrollbarParameters_.position;
568 // No scrolling at all? No need to redraw anything
572 // If the offset is less than 2 screen height, prefer to scroll instead.
573 if (abs(offset) <= 2 * height_) {
574 d->anchor_ypos_ -= offset;
575 buffer_.changed(true);
579 // cut off at the top
580 if (value <= d->scrollbarParameters_.min) {
581 DocIterator dit = doc_iterator_begin(&buffer_);
583 LYXERR(Debug::SCROLLING, "scroll to top");
587 // cut off at the bottom
588 if (value >= d->scrollbarParameters_.max) {
589 DocIterator dit = doc_iterator_end(&buffer_);
592 LYXERR(Debug::SCROLLING, "scroll to bottom");
596 // find paragraph at target position
597 int par_pos = d->scrollbarParameters_.min;
599 for (; i != int(d->par_height_.size()); ++i) {
600 par_pos += d->par_height_[i];
601 if (par_pos >= value)
605 if (par_pos < value) {
606 // It seems we didn't find the correct pit so stay on the safe side and
608 LYXERR0("scrolling position not found!");
609 scrollDocView(d->scrollbarParameters_.max);
613 DocIterator dit = doc_iterator_begin(&buffer_);
615 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
620 // FIXME: this method is not working well.
621 void BufferView::setCursorFromScrollbar()
623 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
625 int const height = 2 * defaultRowHeight();
626 int const first = height;
627 int const last = height_ - height;
629 Cursor const & oldcur = d->cursor_;
631 switch (cursorStatus(oldcur)) {
639 int const y = getPos(oldcur, oldcur.boundary()).y_;
640 newy = min(last, max(y, first));
644 // We reset the cursor because cursorStatus() does not
645 // work when the cursor is within mathed.
648 tm.setCursorFromCoordinates(cur, 0, newy);
650 // update the bufferview cursor and notify insets
651 // FIXME: Care about the d->cursor_ flags to redraw if needed
652 Cursor old = d->cursor_;
654 bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
656 d->cursor_.fixIfBroken();
660 Change const BufferView::getCurrentChange() const
662 if (!d->cursor_.selection())
663 return Change(Change::UNCHANGED);
665 DocIterator dit = d->cursor_.selectionBegin();
666 return dit.paragraph().lookupChange(dit.pos());
670 // this could be used elsewhere as well?
671 // FIXME: This does not work within mathed!
672 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
674 Point const p = getPos(dit, dit.boundary());
677 if (p.y_ > workHeight())
683 void BufferView::bookmarkEditPosition()
685 // Don't eat cpu time for each keystroke
686 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
689 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
693 void BufferView::saveBookmark(unsigned int idx)
695 // tentatively save bookmark, id and pos will be used to
696 // acturately locate a bookmark in a 'live' lyx session.
697 // pit and pos will be updated with bottom level pit/pos
699 theSession().bookmarks().save(
701 d->cursor_.bottom().pit(),
702 d->cursor_.bottom().pos(),
703 d->cursor_.paragraph().id(),
708 // emit message signal.
709 message(_("Save bookmark"));
713 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
714 int top_id, pos_type top_pos)
716 bool success = false;
719 d->cursor_.clearSelection();
721 // if a valid par_id is given, try it first
722 // This is the case for a 'live' bookmark when unique paragraph ID
723 // is used to track bookmarks.
725 dit = buffer_.getParFromID(top_id);
727 dit.pos() = min(dit.paragraph().size(), top_pos);
728 // Some slices of the iterator may not be
729 // reachable (e.g. closed collapsable inset)
730 // so the dociterator may need to be
731 // shortened. Otherwise, setCursor may crash
732 // lyx when the cursor can not be set to these
734 size_t const n = dit.depth();
735 for (size_t i = 0; i < n; ++i)
736 if (!dit[i].inset().editable()) {
744 // if top_id == 0, or searching through top_id failed
745 // This is the case for a 'restored' bookmark when only bottom
746 // (document level) pit was saved. Because of this, bookmark
747 // restoration is inaccurate. If a bookmark was within an inset,
748 // it will be restored to the left of the outmost inset that contains
750 if (bottom_pit < int(buffer_.paragraphs().size())) {
751 dit = doc_iterator_begin(&buffer_);
753 dit.pit() = bottom_pit;
754 dit.pos() = min(bottom_pos, dit.paragraph().size());
759 // Note: only bottom (document) level pit is set.
761 // set the current font.
762 d->cursor_.setCurrentFont();
763 // To center the screen on this new position we need the
764 // paragraph position which is computed at draw() time.
765 // So we need a redraw!
766 buffer_.changed(false);
775 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
777 if (lyxrc.rtl_support) {
778 if (d->cursor_.real_current_font.isRightToLeft()) {
779 if (d->intl_.keymap == Intl::PRIMARY)
780 d->intl_.keyMapSec();
782 if (d->intl_.keymap == Intl::SECONDARY)
783 d->intl_.keyMapPrim();
787 d->intl_.getTransManager().translateAndInsert(c, t, cur);
791 int BufferView::workWidth() const
797 void BufferView::recenter()
799 showCursor(d->cursor_, true);
803 void BufferView::showCursor()
805 showCursor(d->cursor_, false);
809 void BufferView::showCursor(DocIterator const & dit, bool recenter)
811 if (scrollToCursor(dit, recenter))
812 buffer_.changed(false);
816 void BufferView::scrollToCursor()
818 scrollToCursor(d->cursor_, false);
822 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
824 // We are not properly started yet, delay until resizing is
829 LYXERR(Debug::SCROLLING, "recentering!");
831 CursorSlice const & bot = dit.bottom();
832 TextMetrics & tm = d->text_metrics_[bot.text()];
834 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
835 int bot_pit = bot.pit();
836 if (bot_pit > max_pit) {
837 // FIXME: Why does this happen?
838 LYXERR0("bottom pit is greater that max pit: "
839 << bot_pit << " > " << max_pit);
843 if (bot_pit == tm.first().first - 1)
844 tm.newParMetricsUp();
845 else if (bot_pit == tm.last().first + 1)
846 tm.newParMetricsDown();
848 if (tm.contains(bot_pit)) {
849 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
850 LASSERT(!pm.rows().empty(), /**/);
851 // FIXME: smooth scrolling doesn't work in mathed.
852 CursorSlice const & cs = dit.innerTextSlice();
853 int offset = coordOffset(dit, dit.boundary()).y_;
854 int ypos = pm.position() + offset;
855 Dimension const & row_dim =
856 pm.getRow(cs.pos(), dit.boundary()).dimension();
859 scrolled = scroll(ypos - height_/2);
860 else if (ypos - row_dim.ascent() < 0)
861 scrolled = scrollUp(- ypos + row_dim.ascent());
862 else if (ypos + row_dim.descent() > height_)
863 scrolled = scrollDown(ypos - height_ + defaultRowHeight() );
865 // else, nothing to do, the cursor is already visible so we just return.
873 // fix inline completion position
874 if (d->inlineCompletionPos_.fixIfBroken())
875 d->inlineCompletionPos_ = DocIterator();
877 tm.redoParagraph(bot_pit);
878 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
879 int offset = coordOffset(dit, dit.boundary()).y_;
881 d->anchor_pit_ = bot_pit;
882 CursorSlice const & cs = dit.innerTextSlice();
883 Dimension const & row_dim =
884 pm.getRow(cs.pos(), dit.boundary()).dimension();
887 d->anchor_ypos_ = height_/2;
888 else if (d->anchor_pit_ == 0)
889 d->anchor_ypos_ = offset + pm.ascent();
890 else if (d->anchor_pit_ == max_pit)
891 d->anchor_ypos_ = height_ - offset - row_dim.descent();
892 else if (offset > height_)
893 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
895 d->anchor_ypos_ = defaultRowHeight() * 2;
902 void BufferView::updateLayout(DocumentClass const * const oldlayout)
904 message(_("Converting document to new document class..."));
906 StableDocIterator backcur(d->cursor_);
907 ErrorList & el = buffer_.errorList("Class Switch");
908 cap::switchBetweenClasses(
909 oldlayout, buffer_.params().documentClassPtr(),
910 static_cast<InsetText &>(buffer_.inset()), el);
912 setCursor(backcur.asDocIterator(&buffer_));
914 buffer_.errors("Class Switch");
915 buffer_.updateLabels();
918 /** Return the change status at cursor position, taking in account the
919 * status at each level of the document iterator (a table in a deleted
920 * footnote is deleted).
921 * When \param outer is true, the top slice is not looked at.
923 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
925 size_t const depth = dit.depth() - (outer ? 1 : 0);
927 for (size_t i = 0 ; i < depth ; ++i) {
928 CursorSlice const & slice = dit[i];
929 if (!slice.inset().inMathed()
930 && slice.pos() < slice.paragraph().size()) {
931 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
932 if (ch != Change::UNCHANGED)
936 return Change::UNCHANGED;
940 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
942 // Can we use a readonly buffer?
943 if (buffer_.isReadonly()
944 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
945 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
946 flag.message(from_utf8(N_("Document is read-only")));
947 flag.setEnabled(false);
950 // Are we in a DELETED change-tracking region?
951 if (lookupChangeType(d->cursor_, true) == Change::DELETED
952 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
953 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
954 flag.message(from_utf8(N_("This portion of the document is deleted.")));
955 flag.setEnabled(false);
959 Cursor & cur = d->cursor_;
961 if (cur.getStatus(cmd, flag))
964 switch (cmd.action) {
966 // FIXME: This is a bit problematic because we don't check is this is a
967 // document BufferView or not for these LFUNs. We probably have to
968 // dispatch both to currentBufferView() and, if that fails,
969 // to documentBufferView(); same as we do know for current Buffer and
970 // document Buffer. Ideally those LFUN should go to Buffer as they*
971 // operate on the full Buffer and the cursor is only needed either for
972 // an Undo record or to restore a cursor position. But we don't know
973 // how to do that inside Buffer of course.
974 case LFUN_BUFFER_PARAMS_APPLY:
975 case LFUN_LAYOUT_MODULES_CLEAR:
976 case LFUN_LAYOUT_MODULE_ADD:
977 case LFUN_LAYOUT_RELOAD:
978 case LFUN_TEXTCLASS_APPLY:
979 case LFUN_TEXTCLASS_LOAD:
980 flag.setEnabled(!buffer_.isReadonly());
984 flag.setEnabled(buffer_.undo().hasUndoStack());
987 flag.setEnabled(buffer_.undo().hasRedoStack());
989 case LFUN_FILE_INSERT:
990 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
991 case LFUN_FILE_INSERT_PLAINTEXT:
992 case LFUN_BOOKMARK_SAVE:
993 // FIXME: Actually, these LFUNS should be moved to Text
994 flag.setEnabled(cur.inTexted());
997 case LFUN_FONT_STATE:
998 case LFUN_LABEL_INSERT:
999 case LFUN_INFO_INSERT:
1000 case LFUN_INSET_EDIT:
1001 case LFUN_PARAGRAPH_GOTO:
1002 case LFUN_NOTE_NEXT:
1003 case LFUN_REFERENCE_NEXT:
1004 case LFUN_WORD_FIND:
1005 case LFUN_WORD_FIND_FORWARD:
1006 case LFUN_WORD_FIND_BACKWARD:
1007 case LFUN_WORD_FINDADV:
1008 case LFUN_WORD_REPLACE:
1011 case LFUN_MARK_TOGGLE:
1012 case LFUN_SCREEN_RECENTER:
1013 case LFUN_SCREEN_SHOW_CURSOR:
1014 case LFUN_BIBTEX_DATABASE_ADD:
1015 case LFUN_BIBTEX_DATABASE_DEL:
1016 case LFUN_ALL_INSETS_TOGGLE:
1017 case LFUN_STATISTICS:
1018 case LFUN_BRANCH_ADD_INSERT:
1019 case LFUN_KEYMAP_OFF:
1020 case LFUN_KEYMAP_PRIMARY:
1021 case LFUN_KEYMAP_SECONDARY:
1022 case LFUN_KEYMAP_TOGGLE:
1023 flag.setEnabled(true);
1026 case LFUN_LABEL_COPY_AS_REF: {
1027 // if there is an inset at cursor, see whether it
1029 Inset * inset = cur.nextInset();
1030 if (!inset || !inset->getStatus(cur, cmd, flag))
1031 flag.setEnabled(false);
1035 case LFUN_LABEL_GOTO: {
1036 flag.setEnabled(!cmd.argument().empty()
1037 || getInsetByCode<InsetRef>(cur, REF_CODE));
1041 case LFUN_CHANGES_TRACK:
1042 flag.setEnabled(true);
1043 flag.setOnOff(buffer_.params().trackChanges);
1046 case LFUN_CHANGES_OUTPUT:
1047 flag.setEnabled(true);
1048 flag.setOnOff(buffer_.params().outputChanges);
1051 case LFUN_CHANGES_MERGE:
1052 case LFUN_CHANGE_NEXT:
1053 case LFUN_CHANGE_PREVIOUS:
1054 case LFUN_ALL_CHANGES_ACCEPT:
1055 case LFUN_ALL_CHANGES_REJECT:
1056 // TODO: context-sensitive enabling of LFUNs
1057 // In principle, these command should only be enabled if there
1058 // is a change in the document. However, without proper
1059 // optimizations, this will inevitably result in poor performance.
1060 flag.setEnabled(true);
1063 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1064 flag.setOnOff(buffer_.params().compressed);
1068 case LFUN_SCREEN_UP:
1069 case LFUN_SCREEN_DOWN:
1071 case LFUN_SCREEN_UP_SELECT:
1072 case LFUN_SCREEN_DOWN_SELECT:
1073 case LFUN_INSET_FORALL:
1074 flag.setEnabled(true);
1077 case LFUN_LAYOUT_TABULAR:
1078 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1082 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1085 case LFUN_LAYOUT_PARAGRAPH:
1086 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1089 case LFUN_DIALOG_SHOW_NEW_INSET:
1090 // FIXME: this is wrong, but I do not understand the
1092 if (cur.inset().lyxCode() == CAPTION_CODE)
1093 return cur.inset().getStatus(cur, cmd, flag);
1094 // FIXME we should consider passthru paragraphs too.
1095 flag.setEnabled(!cur.inset().getLayout().isPassThru());
1098 case LFUN_CITATION_INSERT: {
1099 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1100 // FIXME: This could turn in a recursive hell.
1101 // Shouldn't we use Buffer::getStatus() instead?
1102 flag.setEnabled(lyx::getStatus(fr).enabled());
1105 case LFUN_INSET_APPLY: {
1106 string const name = cmd.getArg(0);
1107 Inset * inset = editedInset(name);
1109 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1111 if (!inset->getStatus(cur, fr, fs)) {
1112 // Every inset is supposed to handle this
1113 LASSERT(false, break);
1117 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1118 flag |= lyx::getStatus(fr);
1124 flag.setEnabled(false);
1132 Inset * BufferView::editedInset(string const & name) const
1134 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1135 return it == d->edited_insets_.end() ? 0 : it->second;
1139 void BufferView::editInset(string const & name, Inset * inset)
1141 d->edited_insets_[name] = inset;
1145 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1147 //lyxerr << [ cmd = " << cmd << "]" << endl;
1149 // Make sure that the cached BufferView is correct.
1150 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1151 << " arg[" << to_utf8(cmd.argument()) << ']'
1152 << " x[" << cmd.x << ']'
1153 << " y[" << cmd.y << ']'
1154 << " button[" << cmd.button() << ']');
1156 string const argument = to_utf8(cmd.argument());
1157 Cursor & cur = d->cursor_;
1159 // Don't dispatch function that does not apply to internal buffers.
1160 if (buffer_.isInternal()
1161 && lyxaction.funcHasFlag(cmd.action, LyXAction::NoInternal))
1164 // We'll set this back to false if need be.
1165 bool dispatched = true;
1166 buffer_.undo().beginUndoGroup();
1168 switch (cmd.action) {
1170 case LFUN_BUFFER_PARAMS_APPLY: {
1171 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1172 cur.recordUndoFullDocument();
1173 istringstream ss(to_utf8(cmd.argument()));
1176 int const unknown_tokens = buffer_.readHeader(lex);
1177 if (unknown_tokens != 0) {
1178 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1179 << unknown_tokens << " unknown token"
1180 << (unknown_tokens == 1 ? "" : "s"));
1182 updateLayout(oldClass);
1184 // We are most certainly here because of a change in the document
1185 // It is then better to make sure that all dialogs are in sync with
1186 // current document settings.
1187 dr.update(Update::Force | Update::FitCursor);
1191 case LFUN_LAYOUT_MODULES_CLEAR: {
1192 DocumentClass const * const oldClass =
1193 buffer_.params().documentClassPtr();
1194 cur.recordUndoFullDocument();
1195 buffer_.params().clearLayoutModules();
1196 buffer_.params().makeDocumentClass();
1197 updateLayout(oldClass);
1198 dr.update(Update::Force | Update::FitCursor);
1202 case LFUN_LAYOUT_MODULE_ADD: {
1203 BufferParams const & params = buffer_.params();
1204 if (!params.moduleCanBeAdded(argument)) {
1205 LYXERR0("Module `" << argument <<
1206 "' cannot be added due to failed requirements or "
1207 "conflicts with installed modules.");
1210 DocumentClass const * const oldClass = params.documentClassPtr();
1211 cur.recordUndoFullDocument();
1212 buffer_.params().addLayoutModule(argument);
1213 buffer_.params().makeDocumentClass();
1214 updateLayout(oldClass);
1215 dr.update(Update::Force | Update::FitCursor);
1219 case LFUN_TEXTCLASS_APPLY: {
1220 if (!LayoutFileList::get().load(argument, buffer_.temppath()) &&
1221 !LayoutFileList::get().load(argument, buffer_.filePath()))
1224 LayoutFile const * old_layout = buffer_.params().baseClass();
1225 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1227 if (old_layout == new_layout)
1231 //Save the old, possibly modular, layout for use in conversion.
1232 DocumentClass const * const oldDocClass =
1233 buffer_.params().documentClassPtr();
1234 cur.recordUndoFullDocument();
1235 buffer_.params().setBaseClass(argument);
1236 buffer_.params().makeDocumentClass();
1237 updateLayout(oldDocClass);
1238 dr.update(Update::Force | Update::FitCursor);
1242 case LFUN_TEXTCLASS_LOAD:
1243 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1244 LayoutFileList::get().load(argument, buffer_.filePath());
1247 case LFUN_LAYOUT_RELOAD: {
1248 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1249 LayoutFileIndex bc = buffer_.params().baseClassID();
1250 LayoutFileList::get().reset(bc);
1251 buffer_.params().setBaseClass(bc);
1252 buffer_.params().makeDocumentClass();
1253 updateLayout(oldClass);
1254 dr.update(Update::Force | Update::FitCursor);
1259 dr.setMessage(_("Undo"));
1260 cur.clearSelection();
1261 if (!cur.textUndo())
1262 dr.setMessage(_("No further undo information"));
1264 dr.update(Update::Force | Update::FitCursor);
1268 dr.setMessage(_("Redo"));
1269 cur.clearSelection();
1270 if (!cur.textRedo())
1271 dr.setMessage(_("No further redo information"));
1273 dr.update(Update::Force | Update::FitCursor);
1276 case LFUN_FONT_STATE:
1277 dr.setMessage(cur.currentState());
1280 case LFUN_BOOKMARK_SAVE:
1281 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1284 case LFUN_LABEL_GOTO: {
1285 docstring label = cmd.argument();
1286 if (label.empty()) {
1288 getInsetByCode<InsetRef>(cur, REF_CODE);
1290 label = inset->getParam("reference");
1291 // persistent=false: use temp_bookmark
1300 case LFUN_INSET_EDIT: {
1301 FuncRequest fr(cmd);
1302 // if there is an inset at cursor, see whether it
1304 Inset * inset = cur.nextInset();
1306 inset->dispatch(cur, fr);
1307 // if it did not work, try the underlying inset.
1308 if (!inset || !cur.result().dispatched())
1311 // FIXME I'm adding the last break to solve a crash,
1312 // but that is obviously not right.
1313 if (!cur.result().dispatched())
1314 // It did not work too; no action needed.
1319 case LFUN_PARAGRAPH_GOTO: {
1320 int const id = convert<int>(cmd.getArg(0));
1321 int const pos = convert<int>(cmd.getArg(1));
1323 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1324 b = theBufferList().next(b)) {
1326 DocIterator dit = b->getParFromID(id);
1328 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1332 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1333 << " found in buffer `"
1334 << b->absFileName() << "'.");
1336 if (b == &buffer_) {
1340 dr.update(Update::Force | Update::FitCursor);
1342 // Switch to other buffer view and resend cmd
1343 lyx::dispatch(FuncRequest(
1344 LFUN_BUFFER_SWITCH, b->absFileName()));
1352 case LFUN_NOTE_NEXT:
1353 gotoInset(this, NOTE_CODE, false);
1356 case LFUN_REFERENCE_NEXT: {
1357 vector<InsetCode> tmp;
1358 tmp.push_back(LABEL_CODE);
1359 tmp.push_back(REF_CODE);
1360 gotoInset(this, tmp, true);
1364 case LFUN_CHANGES_TRACK:
1365 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1368 case LFUN_CHANGES_OUTPUT:
1369 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1370 if (buffer_.params().outputChanges) {
1371 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1372 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1373 LaTeXFeatures::isAvailable("xcolor");
1375 if (!dvipost && !xcolorulem) {
1376 Alert::warning(_("Changes not shown in LaTeX output"),
1377 _("Changes will not be highlighted in LaTeX output, "
1378 "because neither dvipost nor xcolor/ulem are installed.\n"
1379 "Please install these packages or redefine "
1380 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1381 } else if (!xcolorulem) {
1382 Alert::warning(_("Changes not shown in LaTeX output"),
1383 _("Changes will not be highlighted in LaTeX output "
1384 "when using pdflatex, because xcolor and ulem are not installed.\n"
1385 "Please install both packages or redefine "
1386 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1391 case LFUN_CHANGE_NEXT:
1392 findNextChange(this);
1393 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1394 dr.update(Update::Force | Update::FitCursor);
1397 case LFUN_CHANGE_PREVIOUS:
1398 findPreviousChange(this);
1399 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1400 dr.update(Update::Force | Update::FitCursor);
1403 case LFUN_CHANGES_MERGE:
1404 if (findNextChange(this) || findPreviousChange(this)) {
1405 dr.update(Update::Force | Update::FitCursor);
1406 showDialog("changes");
1410 case LFUN_ALL_CHANGES_ACCEPT:
1411 // select complete document
1413 cur.selHandle(true);
1414 buffer_.text().cursorBottom(cur);
1415 // accept everything in a single step to support atomic undo
1416 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1417 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1418 dr.update(Update::Force | Update::FitCursor);
1421 case LFUN_ALL_CHANGES_REJECT:
1422 // select complete document
1424 cur.selHandle(true);
1425 buffer_.text().cursorBottom(cur);
1426 // reject everything in a single step to support atomic undo
1427 // Note: reject does not work recursively; the user may have to repeat the operation
1428 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1429 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1430 dr.update(Update::Force | Update::FitCursor);
1433 case LFUN_WORD_FIND_FORWARD:
1434 case LFUN_WORD_FIND_BACKWARD: {
1435 static docstring last_search;
1436 docstring searched_string;
1438 if (!cmd.argument().empty()) {
1439 last_search = cmd.argument();
1440 searched_string = cmd.argument();
1442 searched_string = last_search;
1445 if (searched_string.empty())
1448 bool const fw = cmd.action == LFUN_WORD_FIND_FORWARD;
1449 docstring const data =
1450 find2string(searched_string, true, false, fw);
1451 find(this, FuncRequest(LFUN_WORD_FIND, data));
1455 case LFUN_WORD_FIND: {
1456 FuncRequest req = cmd;
1457 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1458 req = d->search_request_cache_;
1459 if (req.argument().empty()) {
1460 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1463 if (find(this, req))
1466 message(_("String not found!"));
1467 d->search_request_cache_ = req;
1471 case LFUN_WORD_REPLACE: {
1472 bool has_deleted = false;
1473 if (cur.selection()) {
1474 DocIterator beg = cur.selectionBegin();
1475 DocIterator end = cur.selectionEnd();
1476 if (beg.pit() == end.pit()) {
1477 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1479 && cur.paragraph().isDeleted(p))
1484 replace(this, cmd, has_deleted);
1488 case LFUN_WORD_FINDADV: {
1489 FindAndReplaceOptions opt;
1490 istringstream iss(to_utf8(cmd.argument()));
1492 if (findAdv(this, opt))
1500 cur.clearSelection();
1501 dr.setMessage(from_utf8(N_("Mark off")));
1505 cur.clearSelection();
1507 dr.setMessage(from_utf8(N_("Mark on")));
1510 case LFUN_MARK_TOGGLE:
1511 cur.setSelection(false);
1514 dr.setMessage(from_utf8(N_("Mark removed")));
1517 dr.setMessage(from_utf8(N_("Mark set")));
1522 case LFUN_SCREEN_SHOW_CURSOR:
1526 case LFUN_SCREEN_RECENTER:
1530 case LFUN_BIBTEX_DATABASE_ADD: {
1531 Cursor tmpcur = cur;
1532 findInset(tmpcur, BIBTEX_CODE, false);
1533 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1536 if (inset->addDatabase(cmd.argument()))
1537 buffer_.updateBibfilesCache();
1542 case LFUN_BIBTEX_DATABASE_DEL: {
1543 Cursor tmpcur = cur;
1544 findInset(tmpcur, BIBTEX_CODE, false);
1545 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1548 if (inset->delDatabase(cmd.argument()))
1549 buffer_.updateBibfilesCache();
1554 case LFUN_STATISTICS: {
1555 DocIterator from, to;
1556 if (cur.selection()) {
1557 from = cur.selectionBegin();
1558 to = cur.selectionEnd();
1560 from = doc_iterator_begin(&buffer_);
1561 to = doc_iterator_end(&buffer_);
1563 int const words = countWords(from, to);
1564 int const chars = countChars(from, to, false);
1565 int const chars_blanks = countChars(from, to, true);
1567 if (cur.selection())
1568 message = _("Statistics for the selection:");
1570 message = _("Statistics for the document:");
1573 message += bformat(_("%1$d words"), words);
1575 message += _("One word");
1577 if (chars_blanks != 1)
1578 message += bformat(_("%1$d characters (including blanks)"),
1581 message += _("One character (including blanks)");
1584 message += bformat(_("%1$d characters (excluding blanks)"),
1587 message += _("One character (excluding blanks)");
1589 Alert::information(_("Statistics"), message);
1593 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1594 // turn compression on/off
1595 buffer_.params().compressed = !buffer_.params().compressed;
1598 case LFUN_LABEL_COPY_AS_REF: {
1599 // if there is an inset at cursor, try to copy it
1600 Inset * inset = &cur.inset();
1601 if (!inset || !inset->asInsetMath())
1602 inset = cur.nextInset();
1604 FuncRequest tmpcmd = cmd;
1605 inset->dispatch(cur, tmpcmd);
1607 if (!cur.result().dispatched())
1608 // It did not work too; no action needed.
1610 cur.clearSelection();
1611 dr.update(Update::SinglePar | Update::FitCursor);
1615 case LFUN_SCREEN_UP:
1616 case LFUN_SCREEN_DOWN: {
1617 Point p = getPos(cur, cur.boundary());
1618 // This code has been commented out to enable to scroll down a
1619 // document, even if there are large insets in it (see bug #5465).
1620 /*if (p.y_ < 0 || p.y_ > height_) {
1621 // The cursor is off-screen so recenter before proceeding.
1623 p = getPos(cur, cur.boundary());
1625 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1626 ? -height_ : height_);
1627 if (cmd.action == LFUN_SCREEN_UP && scrolled > -height_)
1629 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1630 p = Point(width_, height_);
1632 bool const in_texted = cur.inTexted();
1634 buffer_.changed(true);
1635 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1636 true, cmd.action == LFUN_SCREEN_UP);
1637 //FIXME: what to do with cur.x_target()?
1638 bool update = in_texted && cur.bv().checkDepm(cur, old);
1641 dr.update(Update::Force | Update::FitCursor);
1649 case LFUN_SCREEN_UP_SELECT: {
1650 cur.selHandle(true);
1651 if (isTopScreen()) {
1652 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1656 int y = getPos(cur, cur.boundary()).y_;
1657 int const ymin = y - height_ + defaultRowHeight();
1658 while (y > ymin && cur.up())
1659 y = getPos(cur, cur.boundary()).y_;
1662 dr.update(Update::SinglePar | Update::FitCursor);
1666 case LFUN_SCREEN_DOWN_SELECT: {
1667 cur.selHandle(true);
1668 if (isBottomScreen()) {
1669 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1673 int y = getPos(cur, cur.boundary()).y_;
1674 int const ymax = y + height_ - defaultRowHeight();
1675 while (y < ymax && cur.down())
1676 y = getPos(cur, cur.boundary()).y_;
1679 dr.update(Update::SinglePar | Update::FitCursor);
1684 // This would be in Buffer class if only Cursor did not
1685 // require a bufferview
1686 case LFUN_INSET_FORALL: {
1687 docstring const name = from_utf8(cmd.getArg(0));
1688 string const commandstr = cmd.getLongArg(1);
1689 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1691 // an arbitrary number to limit number of iterations
1692 const int max_iter = 10000;
1694 Cursor & cur = d->cursor_;
1695 Cursor const savecur = cur;
1697 if (!cur.nextInset())
1699 cur.beginUndoGroup();
1700 while(cur && iterations < max_iter) {
1701 Inset * ins = cur.nextInset();
1704 docstring insname = ins->name();
1705 while (!insname.empty()) {
1706 if (insname == name || name == from_utf8("*")) {
1712 size_t const i = insname.rfind(':');
1713 if (i == string::npos)
1715 insname = insname.substr(0, i);
1722 dr.update(Update::Force);
1724 if (iterations >= max_iter) {
1726 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1728 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1733 case LFUN_ALL_INSETS_TOGGLE: {
1735 string const name = split(to_utf8(cmd.argument()), action, ' ');
1736 InsetCode const inset_code = insetCode(name);
1738 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1740 Inset & inset = cur.buffer()->inset();
1741 InsetIterator it = inset_iterator_begin(inset);
1742 InsetIterator const end = inset_iterator_end(inset);
1743 for (; it != end; ++it) {
1744 if (it->asInsetCollapsable()
1745 && (inset_code == NO_CODE
1746 || inset_code == it->lyxCode())) {
1747 Cursor tmpcur = cur;
1748 tmpcur.pushBackward(*it);
1749 it->dispatch(tmpcur, fr);
1752 dr.update(Update::Force | Update::FitCursor);
1756 case LFUN_BRANCH_ADD_INSERT: {
1757 docstring branch_name = from_utf8(cmd.getArg(0));
1758 if (branch_name.empty())
1759 if (!Alert::askForText(branch_name, _("Branch name")) ||
1760 branch_name.empty())
1763 DispatchResult drtmp;
1764 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1765 if (drtmp.error()) {
1766 Alert::warning(_("Branch already exists"), drtmp.message());
1769 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1773 case LFUN_KEYMAP_OFF:
1774 getIntl().keyMapOn(false);
1777 case LFUN_KEYMAP_PRIMARY:
1778 getIntl().keyMapPrim();
1781 case LFUN_KEYMAP_SECONDARY:
1782 getIntl().keyMapSec();
1785 case LFUN_KEYMAP_TOGGLE:
1786 getIntl().toggleKeyMap();
1789 case LFUN_DIALOG_SHOW_NEW_INSET: {
1790 string const name = cmd.getArg(0);
1791 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1792 if (decodeInsetParam(name, data, buffer_))
1793 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1795 lyxerr << "Inset type '" << name <<
1796 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1800 case LFUN_CITATION_INSERT: {
1801 if (argument.empty()) {
1802 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1805 // we can have one optional argument, delimited by '|'
1806 // citation-insert <key>|<text_before>
1807 // this should be enhanced to also support text_after
1808 // and citation style
1809 string arg = argument;
1811 if (contains(argument, "|")) {
1812 arg = token(argument, '|', 0);
1813 opt1 = token(argument, '|', 1);
1815 InsetCommandParams icp(CITE_CODE);
1816 icp["key"] = from_utf8(arg);
1818 icp["before"] = from_utf8(opt1);
1819 string icstr = InsetCommand::params2string("citation", icp);
1820 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1825 case LFUN_INSET_APPLY: {
1826 string const name = cmd.getArg(0);
1827 Inset * inset = editedInset(name);
1829 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1833 // put cursor in front of inset.
1834 if (!setCursorFromInset(inset)) {
1835 LASSERT(false, break);
1838 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1839 inset->dispatch(cur, fr);
1840 dr.update(Update::SinglePar | Update::FitCursor);
1849 buffer_.undo().endUndoGroup();
1850 dr.dispatched(dispatched);
1855 docstring const BufferView::requestSelection()
1857 Cursor & cur = d->cursor_;
1859 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1860 if (!cur.selection()) {
1861 d->xsel_cache_.set = false;
1865 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1866 if (!d->xsel_cache_.set ||
1867 cur.top() != d->xsel_cache_.cursor ||
1868 cur.anchor_.top() != d->xsel_cache_.anchor)
1870 d->xsel_cache_.cursor = cur.top();
1871 d->xsel_cache_.anchor = cur.anchor_.top();
1872 d->xsel_cache_.set = cur.selection();
1873 return cur.selectionAsString(false);
1879 void BufferView::clearSelection()
1881 d->cursor_.clearSelection();
1882 // Clear the selection buffer. Otherwise a subsequent
1883 // middle-mouse-button paste would use the selection buffer,
1884 // not the more current external selection.
1885 cap::clearSelection();
1886 d->xsel_cache_.set = false;
1887 // The buffer did not really change, but this causes the
1888 // redraw we need because we cleared the selection above.
1889 buffer_.changed(false);
1893 void BufferView::resize(int width, int height)
1895 // Update from work area
1899 // Clear the paragraph height cache.
1900 d->par_height_.clear();
1901 // Redo the metrics.
1906 Inset const * BufferView::getCoveringInset(Text const & text,
1909 TextMetrics & tm = d->text_metrics_[&text];
1910 Inset * inset = tm.checkInsetHit(x, y);
1914 if (!inset->descendable(*this))
1915 // No need to go further down if the inset is not
1919 size_t cell_number = inset->nargs();
1920 // Check all the inner cell.
1921 for (size_t i = 0; i != cell_number; ++i) {
1922 Text const * inner_text = inset->getText(i);
1925 Inset const * inset_deeper =
1926 getCoveringInset(*inner_text, x, y);
1928 return inset_deeper;
1936 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1938 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1940 // This is only called for mouse related events including
1941 // LFUN_FILE_OPEN generated by drag-and-drop.
1942 FuncRequest cmd = cmd0;
1944 Cursor old = cursor();
1946 cur.push(buffer_.inset());
1947 cur.setSelection(d->cursor_.selection());
1949 // Either the inset under the cursor or the
1950 // surrounding Text will handle this event.
1952 // make sure we stay within the screen...
1953 cmd.y = min(max(cmd.y, -1), height_);
1955 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1957 // Get inset under mouse, if there is one.
1958 Inset const * covering_inset =
1959 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1960 if (covering_inset == d->last_inset_)
1961 // Same inset, no need to do anything...
1964 bool need_redraw = false;
1965 // const_cast because of setMouseHover().
1966 Inset * inset = const_cast<Inset *>(covering_inset);
1968 // Remove the hint on the last hovered inset (if any).
1969 need_redraw |= d->last_inset_->setMouseHover(false);
1971 // Highlighted the newly hovered inset (if any).
1972 need_redraw |= inset->setMouseHover(true);
1973 d->last_inset_ = inset;
1977 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1978 << cmd.x << ", " << cmd.y << ")");
1980 d->update_strategy_ = DecorationUpdate;
1982 // This event (moving without mouse click) is not passed further.
1983 // This should be changed if it is further utilized.
1984 buffer_.changed(false);
1988 // Build temporary cursor.
1989 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1991 // Put anchor at the same position.
1994 cur.beginUndoGroup();
1996 // Try to dispatch to an non-editable inset near this position
1997 // via the temp cursor. If the inset wishes to change the real
1998 // cursor it has to do so explicitly by using
1999 // cur.bv().cursor() = cur; (or similar)
2001 inset->dispatch(cur, cmd);
2003 // Now dispatch to the temporary cursor. If the real cursor should
2004 // be modified, the inset's dispatch has to do so explicitly.
2005 if (!inset || !cur.result().dispatched())
2010 // Notify left insets
2013 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
2015 cursor().fixIfBroken();
2018 // Do we have a selection?
2019 theSelection().haveSelection(cursor().selection());
2021 // If the command has been dispatched,
2022 if (cur.result().dispatched() || cur.result().update())
2023 processUpdateFlags(cur.result().update());
2027 void BufferView::lfunScroll(FuncRequest const & cmd)
2029 string const scroll_type = cmd.getArg(0);
2030 int const scroll_step =
2031 (scroll_type == "line") ? d->scrollbarParameters_.single_step
2032 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
2033 if (scroll_step == 0)
2035 string const scroll_quantity = cmd.getArg(1);
2036 if (scroll_quantity == "up")
2037 scrollUp(scroll_step);
2038 else if (scroll_quantity == "down")
2039 scrollDown(scroll_step);
2041 int const scroll_value = convert<int>(scroll_quantity);
2043 scroll(scroll_step * scroll_value);
2045 buffer_.changed(true);
2049 int BufferView::minVisiblePart()
2051 return 2 * defaultRowHeight();
2055 int BufferView::scroll(int y)
2058 return scrollDown(y);
2060 return scrollUp(-y);
2065 int BufferView::scrollDown(int offset)
2067 Text * text = &buffer_.text();
2068 TextMetrics & tm = d->text_metrics_[text];
2069 int const ymax = height_ + offset;
2071 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2072 int bottom_pos = last.second->position() + last.second->descent();
2073 if (lyxrc.scroll_below_document)
2074 bottom_pos += height_ - minVisiblePart();
2075 if (last.first + 1 == int(text->paragraphs().size())) {
2076 if (bottom_pos <= height_)
2078 offset = min(offset, bottom_pos - height_);
2081 if (bottom_pos > ymax)
2083 tm.newParMetricsDown();
2085 d->anchor_ypos_ -= offset;
2090 int BufferView::scrollUp(int offset)
2092 Text * text = &buffer_.text();
2093 TextMetrics & tm = d->text_metrics_[text];
2094 int ymin = - offset;
2096 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2097 int top_pos = first.second->position() - first.second->ascent();
2098 if (first.first == 0) {
2101 offset = min(offset, - top_pos);
2106 tm.newParMetricsUp();
2108 d->anchor_ypos_ += offset;
2113 void BufferView::setCursorFromRow(int row)
2118 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
2122 buffer_.text().setCursor(d->cursor_, 0, 0);
2124 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
2129 bool BufferView::setCursorFromInset(Inset const * inset)
2131 // are we already there?
2132 if (cursor().nextInset() == inset)
2135 // Inset is not at cursor position. Find it in the document.
2138 while (cur && cur.nextInset() != inset)
2149 void BufferView::gotoLabel(docstring const & label)
2151 std::vector<Buffer const *> bufs = buffer().allRelatives();
2152 std::vector<Buffer const *>::iterator it = bufs.begin();
2153 for (; it != bufs.end(); ++it) {
2154 Buffer const * buf = *it;
2157 Toc & toc = buf->tocBackend().toc("label");
2158 TocIterator toc_it = toc.begin();
2159 TocIterator end = toc.end();
2160 for (; toc_it != end; ++toc_it) {
2161 if (label == toc_it->str()) {
2162 lyx::dispatch(toc_it->action());
2170 TextMetrics const & BufferView::textMetrics(Text const * t) const
2172 return const_cast<BufferView *>(this)->textMetrics(t);
2176 TextMetrics & BufferView::textMetrics(Text const * t)
2178 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2179 if (tmc_it == d->text_metrics_.end()) {
2180 tmc_it = d->text_metrics_.insert(
2181 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2183 return tmc_it->second;
2187 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2190 return textMetrics(t).parMetrics(pit);
2194 int BufferView::workHeight() const
2200 void BufferView::setCursor(DocIterator const & dit)
2203 size_t const n = dit.depth();
2204 for (size_t i = 0; i < n; ++i)
2205 dit[i].inset().edit(d->cursor_, true);
2207 d->cursor_.setCursor(dit);
2208 d->cursor_.setSelection(false);
2212 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2214 // Would be wrong to delete anything if we have a selection.
2215 if (cur.selection())
2218 bool need_anchor_change = false;
2219 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2220 need_anchor_change);
2222 if (need_anchor_change)
2230 buffer_.updateLabels();
2231 buffer_.changed(true);
2236 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2238 LASSERT(&cur.bv() == this, /**/);
2241 // this event will clear selection so we save selection for
2242 // persistent selection
2243 cap::saveSelection(cursor());
2245 d->cursor_.macroModeClose();
2247 // Has the cursor just left the inset?
2248 bool leftinset = (&d->cursor_.inset() != &cur.inset());
2250 d->cursor_.fixIfBroken();
2252 // FIXME: shift-mouse selection doesn't work well across insets.
2253 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
2255 // do the dEPM magic if needed
2256 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2257 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2258 // the leftinset bool would not be necessary (badcursor instead).
2259 bool update = leftinset;
2260 if (!do_selection && d->cursor_.inTexted())
2261 update |= checkDepm(cur, d->cursor_);
2264 d->cursor_.resetAnchor();
2265 d->cursor_.setCursor(cur);
2266 d->cursor_.boundary(cur.boundary());
2268 d->cursor_.setSelection();
2270 d->cursor_.clearSelection();
2272 d->cursor_.finishUndo();
2273 d->cursor_.setCurrentFont();
2278 void BufferView::putSelectionAt(DocIterator const & cur,
2279 int length, bool backwards)
2281 d->cursor_.clearSelection();
2287 d->cursor_.pos() += length;
2288 d->cursor_.setSelection(d->cursor_, -length);
2290 d->cursor_.setSelection(d->cursor_, length);
2292 // Ensure a redraw happens in any case because the new selection could
2293 // possibly be on the same screen as the previous selection.
2294 processUpdateFlags(Update::Force | Update::FitCursor);
2298 Cursor & BufferView::cursor()
2304 Cursor const & BufferView::cursor() const
2310 pit_type BufferView::anchor_ref() const
2312 return d->anchor_pit_;
2316 bool BufferView::singleParUpdate()
2318 Text & buftext = buffer_.text();
2319 pit_type const bottom_pit = d->cursor_.bottom().pit();
2320 TextMetrics & tm = textMetrics(&buftext);
2321 int old_height = tm.parMetrics(bottom_pit).height();
2323 // make sure inline completion pointer is ok
2324 if (d->inlineCompletionPos_.fixIfBroken())
2325 d->inlineCompletionPos_ = DocIterator();
2327 // In Single Paragraph mode, rebreak only
2328 // the (main text, not inset!) paragraph containing the cursor.
2329 // (if this paragraph contains insets etc., rebreaking will
2330 // recursively descend)
2331 tm.redoParagraph(bottom_pit);
2332 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2333 if (pm.height() != old_height)
2334 // Paragraph height has changed so we cannot proceed to
2335 // the singlePar optimisation.
2338 d->update_strategy_ = SingleParUpdate;
2340 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2341 << " y2: " << pm.position() + pm.descent()
2342 << " pit: " << bottom_pit
2343 << " singlepar: 1");
2348 void BufferView::updateMetrics()
2350 if (height_ == 0 || width_ == 0)
2353 Text & buftext = buffer_.text();
2354 pit_type const npit = int(buftext.paragraphs().size());
2356 // Clear out the position cache in case of full screen redraw,
2357 d->coord_cache_.clear();
2359 // Clear out paragraph metrics to avoid having invalid metrics
2360 // in the cache from paragraphs not relayouted below
2361 // The complete text metrics will be redone.
2362 d->text_metrics_.clear();
2364 TextMetrics & tm = textMetrics(&buftext);
2366 // make sure inline completion pointer is ok
2367 if (d->inlineCompletionPos_.fixIfBroken())
2368 d->inlineCompletionPos_ = DocIterator();
2370 if (d->anchor_pit_ >= npit)
2371 // The anchor pit must have been deleted...
2372 d->anchor_pit_ = npit - 1;
2374 // Rebreak anchor paragraph.
2375 tm.redoParagraph(d->anchor_pit_);
2376 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2379 if (d->anchor_pit_ == 0) {
2380 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2382 // Complete buffer visible? Then it's easy.
2383 if (scrollRange == 0)
2384 d->anchor_ypos_ = anchor_pm.ascent();
2386 // FIXME: Some clever handling needed to show
2387 // the _first_ paragraph up to the top if the cursor is
2388 // in the first line.
2390 anchor_pm.setPosition(d->anchor_ypos_);
2392 LYXERR(Debug::PAINTING, "metrics: "
2393 << " anchor pit = " << d->anchor_pit_
2394 << " anchor ypos = " << d->anchor_ypos_);
2396 // Redo paragraphs above anchor if necessary.
2397 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2398 // We are now just above the anchor paragraph.
2399 pit_type pit1 = d->anchor_pit_ - 1;
2400 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2401 tm.redoParagraph(pit1);
2402 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2404 // Save the paragraph position in the cache.
2409 // Redo paragraphs below the anchor if necessary.
2410 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2411 // We are now just below the anchor paragraph.
2412 pit_type pit2 = d->anchor_pit_ + 1;
2413 for (; pit2 < npit && y2 <= height_; ++pit2) {
2414 tm.redoParagraph(pit2);
2415 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2417 // Save the paragraph position in the cache.
2422 LYXERR(Debug::PAINTING, "Metrics: "
2423 << " anchor pit = " << d->anchor_pit_
2424 << " anchor ypos = " << d->anchor_ypos_
2427 << " pit1 = " << pit1
2428 << " pit2 = " << pit2);
2430 d->update_strategy_ = FullScreenUpdate;
2432 if (lyxerr.debugging(Debug::WORKAREA)) {
2433 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2434 d->coord_cache_.dump();
2439 void BufferView::insertLyXFile(FileName const & fname)
2441 LASSERT(d->cursor_.inTexted(), /**/);
2443 // Get absolute path of file and add ".lyx"
2444 // to the filename if necessary
2445 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2447 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2448 // emit message signal.
2449 message(bformat(_("Inserting document %1$s..."), disp_fn));
2452 Buffer buf("", false);
2453 if (buf.loadLyXFile(filename)) {
2454 ErrorList & el = buffer_.errorList("Parse");
2455 // Copy the inserted document error list into the current buffer one.
2456 el = buf.errorList("Parse");
2457 buffer_.undo().recordUndo(d->cursor_);
2458 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2459 buf.params().documentClassPtr(), el);
2460 res = _("Document %1$s inserted.");
2462 res = _("Could not insert document %1$s");
2465 buffer_.changed(true);
2466 // emit message signal.
2467 message(bformat(res, disp_fn));
2468 buffer_.errors("Parse");
2472 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2478 // Addup contribution of nested insets, from inside to outside,
2479 // keeping the outer paragraph for a special handling below
2480 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2481 CursorSlice const & sl = dit[i];
2485 // get relative position inside sl.inset()
2486 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2488 // Make relative position inside of the edited inset relative to sl.inset()
2492 // In case of an RTL inset, the edited inset will be positioned to the left
2495 bool boundary_i = boundary && i + 1 == dit.depth();
2496 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2501 // remember width for the case that sl.inset() is positioned in an RTL inset
2502 if (i && dit[i - 1].text()) {
2503 // If this Inset is inside a Text Inset, retrieve the Dimension
2504 // from the containing text instead of using Inset::dimension() which
2505 // might not be implemented.
2506 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2507 // elimination of Inset::dim_ cache. This coordOffset() method needs
2508 // to be rewritten in light of the new design.
2509 Dimension const & dim = parMetrics(dit[i - 1].text(),
2510 dit[i - 1].pit()).insetDimension(&sl.inset());
2513 Dimension const dim = sl.inset().dimension(*this);
2517 //lyxerr << "Cursor::getPos, i: "
2518 // << i << " x: " << xx << " y: " << y << endl;
2521 // Add contribution of initial rows of outermost paragraph
2522 CursorSlice const & sl = dit[0];
2523 TextMetrics const & tm = textMetrics(sl.text());
2524 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2525 LASSERT(!pm.rows().empty(), /**/);
2526 y -= pm.rows()[0].ascent();
2528 // FIXME: document this mess
2530 if (sl.pos() > 0 && dit.depth() == 1) {
2532 if (pos && boundary)
2534 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2535 rend = pm.pos2row(pos);
2537 rend = pm.pos2row(sl.pos());
2539 size_t rend = pm.pos2row(sl.pos());
2541 for (size_t rit = 0; rit != rend; ++rit)
2542 y += pm.rows()[rit].height();
2543 y += pm.rows()[rend].ascent();
2545 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2547 // Make relative position from the nested inset now bufferview absolute.
2548 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2551 // In the RTL case place the nested inset at the left of the cursor in
2552 // the outer paragraph
2553 bool boundary_1 = boundary && 1 == dit.depth();
2554 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2562 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2564 if (!paragraphVisible(dit))
2565 return Point(-1, -1);
2567 CursorSlice const & bot = dit.bottom();
2568 TextMetrics const & tm = textMetrics(bot.text());
2570 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2571 p.y_ += tm.parMetrics(bot.pit()).position();
2576 bool BufferView::paragraphVisible(DocIterator const & dit) const
2578 CursorSlice const & bot = dit.bottom();
2579 TextMetrics const & tm = textMetrics(bot.text());
2581 return tm.contains(bot.pit());
2585 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2587 Cursor const & cur = cursor();
2588 Font const font = cur.getFont();
2589 frontend::FontMetrics const & fm = theFontMetrics(font);
2590 int const asc = fm.maxAscent();
2591 int const des = fm.maxDescent();
2593 p = getPos(cur, cur.boundary());
2598 bool BufferView::cursorInView(Point const & p, int h) const
2600 Cursor const & cur = cursor();
2601 // does the cursor touch the screen ?
2602 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2608 void BufferView::draw(frontend::Painter & pain)
2610 if (height_ == 0 || width_ == 0)
2612 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2614 Text & text = buffer_.text();
2615 TextMetrics const & tm = d->text_metrics_[&text];
2616 int const y = tm.first().second->position();
2617 PainterInfo pi(this, pain);
2619 switch (d->update_strategy_) {
2621 case NoScreenUpdate:
2622 // If no screen painting is actually needed, only some the different
2623 // coordinates of insets and paragraphs needs to be updated.
2624 pi.full_repaint = true;
2625 pi.pain.setDrawingEnabled(false);
2629 case SingleParUpdate:
2630 pi.full_repaint = false;
2631 // In general, only the current row of the outermost paragraph
2632 // will be redrawn. Particular cases where selection spans
2633 // multiple paragraph are correctly detected in TextMetrics.
2637 case DecorationUpdate:
2638 // FIXME: We should also distinguish DecorationUpdate to avoid text
2639 // drawing if possible. This is not possible to do easily right now
2640 // because of the single backing pixmap.
2642 case FullScreenUpdate:
2643 // The whole screen, including insets, will be refreshed.
2644 pi.full_repaint = true;
2646 // Clear background.
2647 pain.fillRectangle(0, 0, width_, height_,
2648 pi.backgroundColor(&buffer_.inset()));
2653 // and possibly grey out below
2654 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2655 int const y2 = lastpm.second->position() + lastpm.second->descent();
2658 Color color = buffer().isInternal()
2659 ? Color_background : Color_bottomarea;
2660 pain.fillRectangle(0, y2, width_, height_ - y2, color);
2664 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2666 // The scrollbar needs an update.
2669 // Normalize anchor for next time
2670 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2671 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2672 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2673 ParagraphMetrics const & pm = tm.parMetrics(pit);
2674 if (pm.position() + pm.descent() > 0) {
2675 d->anchor_pit_ = pit;
2676 d->anchor_ypos_ = pm.position();
2680 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2681 << " anchor ypos = " << d->anchor_ypos_);
2685 void BufferView::message(docstring const & msg)
2688 d->gui_->message(msg);
2692 void BufferView::showDialog(string const & name)
2695 d->gui_->showDialog(name, string());
2699 void BufferView::showDialog(string const & name,
2700 string const & data, Inset * inset)
2703 d->gui_->showDialog(name, data, inset);
2707 void BufferView::updateDialog(string const & name, string const & data)
2710 d->gui_->updateDialog(name, data);
2714 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2720 // FIXME: Move this out of BufferView again
2721 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2723 if (!fname.isReadableFile()) {
2724 docstring const error = from_ascii(strerror(errno));
2725 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2726 docstring const text =
2727 bformat(_("Could not read the specified document\n"
2728 "%1$s\ndue to the error: %2$s"), file, error);
2729 Alert::error(_("Could not read file"), text);
2733 if (!fname.isReadableFile()) {
2734 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2735 docstring const text =
2736 bformat(_("%1$s\n is not readable."), file);
2737 Alert::error(_("Could not open file"), text);
2741 // FIXME UNICODE: We don't know the encoding of the file
2742 docstring file_content = fname.fileContents("UTF-8");
2743 if (file_content.empty()) {
2744 Alert::error(_("Reading not UTF-8 encoded file"),
2745 _("The file is not UTF-8 encoded.\n"
2746 "It will be read as local 8Bit-encoded.\n"
2747 "If this does not give the correct result\n"
2748 "then please change the encoding of the file\n"
2749 "to UTF-8 with a program other than LyX.\n"));
2750 file_content = fname.fileContents("local8bit");
2753 return normalize_c(file_content);
2757 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2759 docstring const tmpstr = contentsOfPlaintextFile(f);
2764 Cursor & cur = cursor();
2765 cap::replaceSelection(cur);
2766 buffer_.undo().recordUndo(cur);
2768 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2770 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2772 buffer_.changed(true);
2776 docstring const & BufferView::inlineCompletion() const
2778 return d->inlineCompletion_;
2782 size_t const & BufferView::inlineCompletionUniqueChars() const
2784 return d->inlineCompletionUniqueChars_;
2788 DocIterator const & BufferView::inlineCompletionPos() const
2790 return d->inlineCompletionPos_;
2794 bool samePar(DocIterator const & a, DocIterator const & b)
2796 if (a.empty() && b.empty())
2798 if (a.empty() || b.empty())
2800 if (a.depth() != b.depth())
2802 return &a.innerParagraph() == &b.innerParagraph();
2806 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2807 docstring const & completion, size_t uniqueChars)
2809 uniqueChars = min(completion.size(), uniqueChars);
2810 bool changed = d->inlineCompletion_ != completion
2811 || d->inlineCompletionUniqueChars_ != uniqueChars;
2812 bool singlePar = true;
2813 d->inlineCompletion_ = completion;
2814 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2816 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2819 DocIterator const & old = d->inlineCompletionPos_;
2821 //lyxerr << "inlineCompletionPos changed" << std::endl;
2822 // old or pos are in another paragraph?
2823 if ((!samePar(cur, pos) && !pos.empty())
2824 || (!samePar(cur, old) && !old.empty())) {
2826 //lyxerr << "different paragraph" << std::endl;
2828 d->inlineCompletionPos_ = pos;
2833 if (singlePar && !(cur.disp_.update() & Update::Force))
2834 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2836 cur.updateFlags(cur.disp_.update() | Update::Force);