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"
66 #include "frontends/alert.h"
67 #include "frontends/Application.h"
68 #include "frontends/Delegates.h"
69 #include "frontends/FontMetrics.h"
70 #include "frontends/Painter.h"
71 #include "frontends/Selection.h"
73 #include "graphics/Previews.h"
75 #include "support/convert.h"
76 #include "support/debug.h"
77 #include "support/ExceptionMessage.h"
78 #include "support/filetools.h"
79 #include "support/gettext.h"
80 #include "support/lstrings.h"
81 #include "support/Package.h"
82 #include "support/types.h"
92 using namespace lyx::support;
96 namespace Alert = frontend::Alert;
100 /// Return an inset of this class if it exists at the current cursor position
102 T * getInsetByCode(Cursor const & cur, InsetCode code)
104 DocIterator it = cur;
105 Inset * inset = it.nextInset();
106 if (inset && inset->lyxCode() == code)
107 return static_cast<T*>(inset);
112 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
115 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
116 docstring const & contents)
118 DocIterator tmpdit = dit;
121 Inset const * inset = tmpdit.nextInset();
123 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
124 && (contents.empty() ||
125 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
129 tmpdit.forwardInset();
136 /// Looks for next inset with one of the given codes.
137 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
141 DocIterator tmpdit = dit;
142 tmpdit.forwardInset();
147 Inset const * inset = tmpdit.nextInset();
149 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
150 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
154 if (!findNextInset(tmpdit, codes, contents)) {
155 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
156 Inset * inset = &tmpdit.bottom().inset();
157 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
158 if (!findNextInset(tmpdit, codes, contents))
170 /// Looks for next inset with the given code
171 void findInset(DocIterator & dit, InsetCode code, bool same_content)
173 findInset(dit, vector<InsetCode>(1, code), same_content);
177 /// Moves cursor to the next inset with one of the given codes.
178 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
181 Cursor tmpcur = bv->cursor();
182 if (!findInset(tmpcur, codes, same_content)) {
183 bv->cursor().message(_("No more insets"));
187 tmpcur.clearSelection();
188 bv->setCursor(tmpcur);
193 /// Moves cursor to the next inset with given code.
194 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
196 gotoInset(bv, vector<InsetCode>(1, code), same_content);
200 /// A map from a Text to the associated text metrics
201 typedef map<Text const *, TextMetrics> TextMetricsCache;
203 enum ScreenUpdateStrategy {
213 /////////////////////////////////////////////////////////////////////
217 /////////////////////////////////////////////////////////////////////
219 struct BufferView::Private
221 Private(BufferView & bv): wh_(0), cursor_(bv),
222 anchor_pit_(0), anchor_ypos_(0),
223 inlineCompletionUniqueChars_(0),
224 last_inset_(0), bookmark_edit_position_(0), gui_(0)
228 ScrollbarParameters scrollbarParameters_;
230 ScreenUpdateStrategy update_strategy_;
232 CoordCache coord_cache_;
234 /// Estimated average par height for scrollbar.
236 /// this is used to handle XSelection events in the right manner.
245 pit_type anchor_pit_;
249 vector<int> par_height_;
252 DocIterator inlineCompletionPos_;
254 docstring inlineCompletion_;
256 size_t inlineCompletionUniqueChars_;
258 /// keyboard mapping object.
261 /// last visited inset.
262 /** kept to send setMouseHover(false).
263 * Not owned, so don't delete.
267 // cache for id of the paragraph which was edited the last time
268 int bookmark_edit_position_;
270 mutable TextMetricsCache text_metrics_;
273 /** Not owned, so don't delete.
275 frontend::GuiBufferViewDelegate * gui_;
277 /// Cache for Find Next
278 FuncRequest search_request_cache_;
281 map<string, Inset *> edited_insets_;
285 BufferView::BufferView(Buffer & buf)
286 : width_(0), height_(0), full_screen_(false), buffer_(buf),
287 d(new Private(*this))
289 d->xsel_cache_.set = false;
290 d->intl_.initKeyMapper(lyxrc.use_kbmap);
292 d->cursor_.setBuffer(&buf);
293 d->cursor_.push(buffer_.inset());
294 d->cursor_.resetAnchor();
295 d->cursor_.setCurrentFont();
297 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
298 thePreviews().generateBufferPreviews(buffer_);
302 BufferView::~BufferView()
304 // current buffer is going to be switched-off, save cursor pos
305 // Ideally, the whole cursor stack should be saved, but session
306 // currently can only handle bottom (whole document) level pit and pos.
307 // That is to say, if a cursor is in a nested inset, it will be
308 // restore to the left of the top level inset.
309 LastFilePosSection::FilePos fp;
310 fp.pit = d->cursor_.bottom().pit();
311 fp.pos = d->cursor_.bottom().pos();
312 theSession().lastFilePos().save(buffer_.fileName(), fp);
318 int BufferView::rightMargin() const
320 // The additional test for the case the outliner is opened.
322 !lyxrc.full_screen_limit ||
323 width_ < lyxrc.full_screen_width + 20)
326 return (width_ - lyxrc.full_screen_width) / 2;
330 int BufferView::leftMargin() const
332 return rightMargin();
336 bool BufferView::isTopScreen() const
338 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
342 bool BufferView::isBottomScreen() const
344 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
348 Intl & BufferView::getIntl()
354 Intl const & BufferView::getIntl() const
360 CoordCache & BufferView::coordCache()
362 return d->coord_cache_;
366 CoordCache const & BufferView::coordCache() const
368 return d->coord_cache_;
372 Buffer & BufferView::buffer()
378 Buffer const & BufferView::buffer() const
384 bool BufferView::fitCursor()
386 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
387 frontend::FontMetrics const & fm =
388 theFontMetrics(d->cursor_.getFont().fontInfo());
389 int const asc = fm.maxAscent();
390 int const des = fm.maxDescent();
391 Point const p = getPos(d->cursor_, d->cursor_.boundary());
392 if (p.y_ - asc >= 0 && p.y_ + des < height_)
399 void BufferView::processUpdateFlags(Update::flags flags)
401 // last_inset_ points to the last visited inset. This pointer may become
402 // invalid because of keyboard editing. Since all such operations
403 // causes screen update(), I reset last_inset_ to avoid such a problem.
405 // This is close to a hot-path.
406 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
407 << "[fitcursor = " << (flags & Update::FitCursor)
408 << ", forceupdate = " << (flags & Update::Force)
409 << ", singlepar = " << (flags & Update::SinglePar)
410 << "] buffer: " << &buffer_);
412 buffer_.updateMacros();
414 // Now do the first drawing step if needed. This consists on updating
415 // the CoordCache in updateMetrics().
416 // The second drawing step is done in WorkArea::redraw() if needed.
418 // Case when no explicit update is requested.
420 // no need to redraw anything.
421 d->update_strategy_ = NoScreenUpdate;
425 if (flags == Update::Decoration) {
426 d->update_strategy_ = DecorationUpdate;
427 buffer_.changed(false);
431 if (flags == Update::FitCursor
432 || flags == (Update::Decoration | Update::FitCursor)) {
433 // tell the frontend to update the screen if needed.
438 if (flags & Update::Decoration) {
439 d->update_strategy_ = DecorationUpdate;
440 buffer_.changed(false);
443 // no screen update is needed.
444 d->update_strategy_ = NoScreenUpdate;
448 bool const full_metrics = flags & Update::Force || !singleParUpdate();
451 // We have to update the full screen metrics.
454 if (!(flags & Update::FitCursor)) {
455 // Nothing to do anymore. Trigger a redraw and return
456 buffer_.changed(false);
460 // updateMetrics() does not update paragraph position
461 // This is done at draw() time. So we need a redraw!
462 buffer_.changed(false);
465 // The cursor is off screen so ensure it is visible.
472 void BufferView::updateScrollbar()
474 if (height_ == 0 && width_ == 0)
477 // We prefer fixed size line scrolling.
478 d->scrollbarParameters_.single_step = defaultRowHeight();
479 // We prefer full screen page scrolling.
480 d->scrollbarParameters_.page_step = height_;
482 Text & t = buffer_.text();
483 TextMetrics & tm = d->text_metrics_[&t];
485 LYXERR(Debug::GUI, " Updating scrollbar: height: "
486 << t.paragraphs().size()
487 << " curr par: " << d->cursor_.bottom().pit()
488 << " default height " << defaultRowHeight());
490 size_t const parsize = t.paragraphs().size();
491 if (d->par_height_.size() != parsize) {
492 d->par_height_.clear();
493 // FIXME: We assume a default paragraph height of 2 rows. This
494 // should probably be pondered with the screen width.
495 d->par_height_.resize(parsize, defaultRowHeight() * 2);
498 // Look at paragraph heights on-screen
499 pair<pit_type, ParagraphMetrics const *> first = tm.first();
500 pair<pit_type, ParagraphMetrics const *> last = tm.last();
501 for (pit_type pit = first.first; pit <= last.first; ++pit) {
502 d->par_height_[pit] = tm.parMetrics(pit).height();
503 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
504 << d->par_height_[pit]);
507 int top_pos = first.second->position() - first.second->ascent();
508 int bottom_pos = last.second->position() + last.second->descent();
509 bool first_visible = first.first == 0 && top_pos >= 0;
510 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
511 if (first_visible && last_visible) {
512 d->scrollbarParameters_.min = 0;
513 d->scrollbarParameters_.max = 0;
517 d->scrollbarParameters_.min = top_pos;
518 for (size_t i = 0; i != size_t(first.first); ++i)
519 d->scrollbarParameters_.min -= d->par_height_[i];
520 d->scrollbarParameters_.max = bottom_pos;
521 for (size_t i = last.first + 1; i != parsize; ++i)
522 d->scrollbarParameters_.max += d->par_height_[i];
524 d->scrollbarParameters_.position = 0;
525 // The reference is the top position so we remove one page.
526 if (lyxrc.scroll_below_document)
527 d->scrollbarParameters_.max -= minVisiblePart();
529 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
533 ScrollbarParameters const & BufferView::scrollbarParameters() const
535 return d->scrollbarParameters_;
539 docstring BufferView::toolTip(int x, int y) const
541 // Get inset under mouse, if there is one.
542 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
544 // No inset, no tooltip...
546 return covering_inset->toolTip(*this, x, y);
550 docstring BufferView::contextMenu(int x, int y) const
552 //If there is a selection, return the containing inset menu
553 if (d->cursor_.selection())
554 return d->cursor_.inset().contextMenu(*this, x, y);
556 // Get inset under mouse, if there is one.
557 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
559 return covering_inset->contextMenu(*this, x, y);
561 return buffer_.inset().contextMenu(*this, x, y);
565 void BufferView::scrollDocView(int value)
567 int const offset = value - d->scrollbarParameters_.position;
569 // No scrolling at all? No need to redraw anything
573 // If the offset is less than 2 screen height, prefer to scroll instead.
574 if (abs(offset) <= 2 * height_) {
575 d->anchor_ypos_ -= offset;
576 buffer_.changed(true);
580 // cut off at the top
581 if (value <= d->scrollbarParameters_.min) {
582 DocIterator dit = doc_iterator_begin(&buffer_);
584 LYXERR(Debug::SCROLLING, "scroll to top");
588 // cut off at the bottom
589 if (value >= d->scrollbarParameters_.max) {
590 DocIterator dit = doc_iterator_end(&buffer_);
593 LYXERR(Debug::SCROLLING, "scroll to bottom");
597 // find paragraph at target position
598 int par_pos = d->scrollbarParameters_.min;
600 for (; i != int(d->par_height_.size()); ++i) {
601 par_pos += d->par_height_[i];
602 if (par_pos >= value)
606 if (par_pos < value) {
607 // It seems we didn't find the correct pit so stay on the safe side and
609 LYXERR0("scrolling position not found!");
610 scrollDocView(d->scrollbarParameters_.max);
614 DocIterator dit = doc_iterator_begin(&buffer_);
616 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
621 // FIXME: this method is not working well.
622 void BufferView::setCursorFromScrollbar()
624 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
626 int const height = 2 * defaultRowHeight();
627 int const first = height;
628 int const last = height_ - height;
630 Cursor const & oldcur = d->cursor_;
632 switch (cursorStatus(oldcur)) {
640 int const y = getPos(oldcur, oldcur.boundary()).y_;
641 newy = min(last, max(y, first));
645 // We reset the cursor because cursorStatus() does not
646 // work when the cursor is within mathed.
649 tm.setCursorFromCoordinates(cur, 0, newy);
651 // update the bufferview cursor and notify insets
652 // FIXME: Care about the d->cursor_ flags to redraw if needed
653 Cursor old = d->cursor_;
655 bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
657 d->cursor_.fixIfBroken();
661 Change const BufferView::getCurrentChange() const
663 if (!d->cursor_.selection())
664 return Change(Change::UNCHANGED);
666 DocIterator dit = d->cursor_.selectionBegin();
667 return dit.paragraph().lookupChange(dit.pos());
671 // this could be used elsewhere as well?
672 // FIXME: This does not work within mathed!
673 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
675 Point const p = getPos(dit, dit.boundary());
678 if (p.y_ > workHeight())
684 void BufferView::bookmarkEditPosition()
686 // Don't eat cpu time for each keystroke
687 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
690 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
694 void BufferView::saveBookmark(unsigned int idx)
696 // tentatively save bookmark, id and pos will be used to
697 // acturately locate a bookmark in a 'live' lyx session.
698 // pit and pos will be updated with bottom level pit/pos
700 theSession().bookmarks().save(
702 d->cursor_.bottom().pit(),
703 d->cursor_.bottom().pos(),
704 d->cursor_.paragraph().id(),
709 // emit message signal.
710 message(_("Save bookmark"));
714 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
715 int top_id, pos_type top_pos)
717 bool success = false;
720 d->cursor_.clearSelection();
722 // if a valid par_id is given, try it first
723 // This is the case for a 'live' bookmark when unique paragraph ID
724 // is used to track bookmarks.
726 dit = buffer_.getParFromID(top_id);
728 dit.pos() = min(dit.paragraph().size(), top_pos);
729 // Some slices of the iterator may not be
730 // reachable (e.g. closed collapsable inset)
731 // so the dociterator may need to be
732 // shortened. Otherwise, setCursor may crash
733 // lyx when the cursor can not be set to these
735 size_t const n = dit.depth();
736 for (size_t i = 0; i < n; ++i)
737 if (!dit[i].inset().editable()) {
745 // if top_id == 0, or searching through top_id failed
746 // This is the case for a 'restored' bookmark when only bottom
747 // (document level) pit was saved. Because of this, bookmark
748 // restoration is inaccurate. If a bookmark was within an inset,
749 // it will be restored to the left of the outmost inset that contains
751 if (bottom_pit < int(buffer_.paragraphs().size())) {
752 dit = doc_iterator_begin(&buffer_);
754 dit.pit() = bottom_pit;
755 dit.pos() = min(bottom_pos, dit.paragraph().size());
760 // Note: only bottom (document) level pit is set.
762 // set the current font.
763 d->cursor_.setCurrentFont();
764 // To center the screen on this new position we need the
765 // paragraph position which is computed at draw() time.
766 // So we need a redraw!
767 buffer_.changed(false);
776 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
778 if (lyxrc.rtl_support) {
779 if (d->cursor_.real_current_font.isRightToLeft()) {
780 if (d->intl_.keymap == Intl::PRIMARY)
781 d->intl_.keyMapSec();
783 if (d->intl_.keymap == Intl::SECONDARY)
784 d->intl_.keyMapPrim();
788 d->intl_.getTransManager().translateAndInsert(c, t, cur);
792 int BufferView::workWidth() const
798 void BufferView::recenter()
800 showCursor(d->cursor_, true);
804 void BufferView::showCursor()
806 showCursor(d->cursor_, false);
810 void BufferView::showCursor(DocIterator const & dit, bool recenter)
812 if (scrollToCursor(dit, recenter))
813 buffer_.changed(false);
817 void BufferView::scrollToCursor()
819 scrollToCursor(d->cursor_, false);
823 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
825 // We are not properly started yet, delay until resizing is
830 LYXERR(Debug::SCROLLING, "recentering!");
832 CursorSlice const & bot = dit.bottom();
833 TextMetrics & tm = d->text_metrics_[bot.text()];
835 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
836 int bot_pit = bot.pit();
837 if (bot_pit > max_pit) {
838 // FIXME: Why does this happen?
839 LYXERR0("bottom pit is greater that max pit: "
840 << bot_pit << " > " << max_pit);
844 if (bot_pit == tm.first().first - 1)
845 tm.newParMetricsUp();
846 else if (bot_pit == tm.last().first + 1)
847 tm.newParMetricsDown();
849 if (tm.contains(bot_pit)) {
850 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
851 LASSERT(!pm.rows().empty(), /**/);
852 // FIXME: smooth scrolling doesn't work in mathed.
853 CursorSlice const & cs = dit.innerTextSlice();
854 int offset = coordOffset(dit, dit.boundary()).y_;
855 int ypos = pm.position() + offset;
856 Dimension const & row_dim =
857 pm.getRow(cs.pos(), dit.boundary()).dimension();
860 scrolled = scroll(ypos - height_/2);
861 else if (ypos - row_dim.ascent() < 0)
862 scrolled = scrollUp(- ypos + row_dim.ascent());
863 else if (ypos + row_dim.descent() > height_)
864 scrolled = scrollDown(ypos - height_ + defaultRowHeight() );
866 // else, nothing to do, the cursor is already visible so we just return.
874 // fix inline completion position
875 if (d->inlineCompletionPos_.fixIfBroken())
876 d->inlineCompletionPos_ = DocIterator();
878 tm.redoParagraph(bot_pit);
879 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
880 int offset = coordOffset(dit, dit.boundary()).y_;
882 d->anchor_pit_ = bot_pit;
883 CursorSlice const & cs = dit.innerTextSlice();
884 Dimension const & row_dim =
885 pm.getRow(cs.pos(), dit.boundary()).dimension();
888 d->anchor_ypos_ = height_/2;
889 else if (d->anchor_pit_ == 0)
890 d->anchor_ypos_ = offset + pm.ascent();
891 else if (d->anchor_pit_ == max_pit)
892 d->anchor_ypos_ = height_ - offset - row_dim.descent();
893 else if (offset > height_)
894 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
896 d->anchor_ypos_ = defaultRowHeight() * 2;
903 void BufferView::updateLayout(DocumentClass const * const oldlayout)
905 message(_("Converting document to new document class..."));
907 StableDocIterator backcur(d->cursor_);
908 ErrorList & el = buffer_.errorList("Class Switch");
909 cap::switchBetweenClasses(
910 oldlayout, buffer_.params().documentClassPtr(),
911 static_cast<InsetText &>(buffer_.inset()), el);
913 setCursor(backcur.asDocIterator(&buffer_));
915 buffer_.errors("Class Switch");
916 buffer_.updateLabels();
919 /** Return the change status at cursor position, taking in account the
920 * status at each level of the document iterator (a table in a deleted
921 * footnote is deleted).
922 * When \param outer is true, the top slice is not looked at.
924 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
926 size_t const depth = dit.depth() - (outer ? 1 : 0);
928 for (size_t i = 0 ; i < depth ; ++i) {
929 CursorSlice const & slice = dit[i];
930 if (!slice.inset().inMathed()
931 && slice.pos() < slice.paragraph().size()) {
932 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
933 if (ch != Change::UNCHANGED)
937 return Change::UNCHANGED;
941 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
943 // Can we use a readonly buffer?
944 if (buffer_.isReadonly()
945 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
946 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
947 flag.message(from_utf8(N_("Document is read-only")));
948 flag.setEnabled(false);
951 // Are we in a DELETED change-tracking region?
952 if (lookupChangeType(d->cursor_, true) == Change::DELETED
953 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
954 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
955 flag.message(from_utf8(N_("This portion of the document is deleted.")));
956 flag.setEnabled(false);
960 Cursor & cur = d->cursor_;
962 if (cur.getStatus(cmd, flag))
965 switch (cmd.action) {
967 // FIXME: This is a bit problematic because we don't check is this is a
968 // document BufferView or not for these LFUNs. We probably have to
969 // dispatch both to currentBufferView() and, if that fails,
970 // to documentBufferView(); same as we do know for current Buffer and
971 // document Buffer. Ideally those LFUN should go to Buffer as they*
972 // operate on the full Buffer and the cursor is only needed either for
973 // an Undo record or to restore a cursor position. But we don't know
974 // how to do that inside Buffer of course.
975 case LFUN_BUFFER_PARAMS_APPLY:
976 case LFUN_LAYOUT_MODULES_CLEAR:
977 case LFUN_LAYOUT_MODULE_ADD:
978 case LFUN_LAYOUT_RELOAD:
979 case LFUN_TEXTCLASS_APPLY:
980 case LFUN_TEXTCLASS_LOAD:
981 flag.setEnabled(!buffer_.isReadonly());
985 flag.setEnabled(buffer_.undo().hasUndoStack());
988 flag.setEnabled(buffer_.undo().hasRedoStack());
990 case LFUN_FILE_INSERT:
991 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
992 case LFUN_FILE_INSERT_PLAINTEXT:
993 case LFUN_BOOKMARK_SAVE:
994 // FIXME: Actually, these LFUNS should be moved to Text
995 flag.setEnabled(cur.inTexted());
998 case LFUN_FONT_STATE:
999 case LFUN_LABEL_INSERT:
1000 case LFUN_INFO_INSERT:
1001 case LFUN_INSET_EDIT:
1002 case LFUN_PARAGRAPH_GOTO:
1003 case LFUN_NOTE_NEXT:
1004 case LFUN_REFERENCE_NEXT:
1005 case LFUN_WORD_FIND:
1006 case LFUN_WORD_FIND_FORWARD:
1007 case LFUN_WORD_FIND_BACKWARD:
1008 case LFUN_WORD_FINDADV:
1009 case LFUN_WORD_REPLACE:
1012 case LFUN_MARK_TOGGLE:
1013 case LFUN_SCREEN_RECENTER:
1014 case LFUN_SCREEN_SHOW_CURSOR:
1015 case LFUN_BIBTEX_DATABASE_ADD:
1016 case LFUN_BIBTEX_DATABASE_DEL:
1017 case LFUN_ALL_INSETS_TOGGLE:
1018 case LFUN_STATISTICS:
1019 case LFUN_BRANCH_ADD_INSERT:
1020 case LFUN_KEYMAP_OFF:
1021 case LFUN_KEYMAP_PRIMARY:
1022 case LFUN_KEYMAP_SECONDARY:
1023 case LFUN_KEYMAP_TOGGLE:
1024 flag.setEnabled(true);
1027 case LFUN_LABEL_COPY_AS_REF: {
1028 // if there is an inset at cursor, see whether it
1030 Inset * inset = cur.nextInset();
1031 if (!inset || !inset->getStatus(cur, cmd, flag))
1032 flag.setEnabled(false);
1036 case LFUN_LABEL_GOTO: {
1037 flag.setEnabled(!cmd.argument().empty()
1038 || getInsetByCode<InsetRef>(cur, REF_CODE));
1042 case LFUN_CHANGES_TRACK:
1043 flag.setEnabled(true);
1044 flag.setOnOff(buffer_.params().trackChanges);
1047 case LFUN_CHANGES_OUTPUT:
1048 flag.setEnabled(true);
1049 flag.setOnOff(buffer_.params().outputChanges);
1052 case LFUN_CHANGES_MERGE:
1053 case LFUN_CHANGE_NEXT:
1054 case LFUN_CHANGE_PREVIOUS:
1055 case LFUN_ALL_CHANGES_ACCEPT:
1056 case LFUN_ALL_CHANGES_REJECT:
1057 // TODO: context-sensitive enabling of LFUNs
1058 // In principle, these command should only be enabled if there
1059 // is a change in the document. However, without proper
1060 // optimizations, this will inevitably result in poor performance.
1061 flag.setEnabled(true);
1064 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1065 flag.setOnOff(buffer_.params().compressed);
1069 case LFUN_SCREEN_UP:
1070 case LFUN_SCREEN_DOWN:
1072 case LFUN_SCREEN_UP_SELECT:
1073 case LFUN_SCREEN_DOWN_SELECT:
1074 case LFUN_INSET_FORALL:
1075 flag.setEnabled(true);
1078 case LFUN_LAYOUT_TABULAR:
1079 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1083 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1086 case LFUN_LAYOUT_PARAGRAPH:
1087 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1090 case LFUN_DIALOG_SHOW_NEW_INSET:
1091 // FIXME: this is wrong, but I do not understand the
1093 if (cur.inset().lyxCode() == CAPTION_CODE)
1094 return cur.inset().getStatus(cur, cmd, flag);
1095 // FIXME we should consider passthru paragraphs too.
1096 flag.setEnabled(!cur.inset().getLayout().isPassThru());
1099 case LFUN_CITATION_INSERT: {
1100 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1101 // FIXME: This could turn in a recursive hell.
1102 // Shouldn't we use Buffer::getStatus() instead?
1103 flag.setEnabled(lyx::getStatus(fr).enabled());
1106 case LFUN_INSET_APPLY: {
1107 string const name = cmd.getArg(0);
1108 Inset * inset = editedInset(name);
1110 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1112 if (!inset->getStatus(cur, fr, fs)) {
1113 // Every inset is supposed to handle this
1114 LASSERT(false, break);
1118 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1119 flag |= lyx::getStatus(fr);
1125 flag.setEnabled(false);
1133 Inset * BufferView::editedInset(string const & name) const
1135 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1136 return it == d->edited_insets_.end() ? 0 : it->second;
1140 void BufferView::editInset(string const & name, Inset * inset)
1142 d->edited_insets_[name] = inset;
1146 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1148 //lyxerr << [ cmd = " << cmd << "]" << endl;
1150 // Make sure that the cached BufferView is correct.
1151 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1152 << " arg[" << to_utf8(cmd.argument()) << ']'
1153 << " x[" << cmd.x << ']'
1154 << " y[" << cmd.y << ']'
1155 << " button[" << cmd.button() << ']');
1157 string const argument = to_utf8(cmd.argument());
1158 Cursor & cur = d->cursor_;
1160 // Don't dispatch function that does not apply to internal buffers.
1161 if (buffer_.isInternal()
1162 && lyxaction.funcHasFlag(cmd.action, LyXAction::NoInternal))
1165 // We'll set this back to false if need be.
1166 bool dispatched = true;
1167 buffer_.undo().beginUndoGroup();
1169 switch (cmd.action) {
1171 case LFUN_BUFFER_PARAMS_APPLY: {
1172 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1173 cur.recordUndoFullDocument();
1174 istringstream ss(to_utf8(cmd.argument()));
1177 int const unknown_tokens = buffer_.readHeader(lex);
1178 if (unknown_tokens != 0) {
1179 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1180 << unknown_tokens << " unknown token"
1181 << (unknown_tokens == 1 ? "" : "s"));
1183 updateLayout(oldClass);
1185 // We are most certainly here because of a change in the document
1186 // It is then better to make sure that all dialogs are in sync with
1187 // current document settings.
1188 dr.update(Update::Force | Update::FitCursor);
1192 case LFUN_LAYOUT_MODULES_CLEAR: {
1193 DocumentClass const * const oldClass =
1194 buffer_.params().documentClassPtr();
1195 cur.recordUndoFullDocument();
1196 buffer_.params().clearLayoutModules();
1197 buffer_.params().makeDocumentClass();
1198 updateLayout(oldClass);
1199 dr.update(Update::Force | Update::FitCursor);
1203 case LFUN_LAYOUT_MODULE_ADD: {
1204 BufferParams const & params = buffer_.params();
1205 if (!params.moduleCanBeAdded(argument)) {
1206 LYXERR0("Module `" << argument <<
1207 "' cannot be added due to failed requirements or "
1208 "conflicts with installed modules.");
1211 DocumentClass const * const oldClass = params.documentClassPtr();
1212 cur.recordUndoFullDocument();
1213 buffer_.params().addLayoutModule(argument);
1214 buffer_.params().makeDocumentClass();
1215 updateLayout(oldClass);
1216 dr.update(Update::Force | Update::FitCursor);
1220 case LFUN_TEXTCLASS_APPLY: {
1221 if (!LayoutFileList::get().load(argument, buffer_.temppath()) &&
1222 !LayoutFileList::get().load(argument, buffer_.filePath()))
1225 LayoutFile const * old_layout = buffer_.params().baseClass();
1226 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1228 if (old_layout == new_layout)
1232 //Save the old, possibly modular, layout for use in conversion.
1233 DocumentClass const * const oldDocClass =
1234 buffer_.params().documentClassPtr();
1235 cur.recordUndoFullDocument();
1236 buffer_.params().setBaseClass(argument);
1237 buffer_.params().makeDocumentClass();
1238 updateLayout(oldDocClass);
1239 dr.update(Update::Force | Update::FitCursor);
1243 case LFUN_TEXTCLASS_LOAD:
1244 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1245 LayoutFileList::get().load(argument, buffer_.filePath());
1248 case LFUN_LAYOUT_RELOAD: {
1249 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1250 LayoutFileIndex bc = buffer_.params().baseClassID();
1251 LayoutFileList::get().reset(bc);
1252 buffer_.params().setBaseClass(bc);
1253 buffer_.params().makeDocumentClass();
1254 updateLayout(oldClass);
1255 dr.update(Update::Force | Update::FitCursor);
1260 dr.setMessage(_("Undo"));
1261 cur.clearSelection();
1262 if (!cur.textUndo())
1263 dr.setMessage(_("No further undo information"));
1265 dr.update(Update::Force | Update::FitCursor);
1269 dr.setMessage(_("Redo"));
1270 cur.clearSelection();
1271 if (!cur.textRedo())
1272 dr.setMessage(_("No further redo information"));
1274 dr.update(Update::Force | Update::FitCursor);
1277 case LFUN_FONT_STATE:
1278 dr.setMessage(cur.currentState());
1281 case LFUN_BOOKMARK_SAVE:
1282 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1285 case LFUN_LABEL_GOTO: {
1286 docstring label = cmd.argument();
1287 if (label.empty()) {
1289 getInsetByCode<InsetRef>(cur, REF_CODE);
1291 label = inset->getParam("reference");
1292 // persistent=false: use temp_bookmark
1301 case LFUN_INSET_EDIT: {
1302 FuncRequest fr(cmd);
1303 // if there is an inset at cursor, see whether it
1305 Inset * inset = cur.nextInset();
1307 inset->dispatch(cur, fr);
1308 // if it did not work, try the underlying inset.
1309 if (!inset || !cur.result().dispatched())
1312 // FIXME I'm adding the last break to solve a crash,
1313 // but that is obviously not right.
1314 if (!cur.result().dispatched())
1315 // It did not work too; no action needed.
1320 case LFUN_PARAGRAPH_GOTO: {
1321 int const id = convert<int>(cmd.getArg(0));
1322 int const pos = convert<int>(cmd.getArg(1));
1324 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1325 b = theBufferList().next(b)) {
1327 DocIterator dit = b->getParFromID(id);
1329 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1333 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1334 << " found in buffer `"
1335 << b->absFileName() << "'.");
1337 if (b == &buffer_) {
1341 dr.update(Update::Force | Update::FitCursor);
1343 // Switch to other buffer view and resend cmd
1344 theLyXFunc().dispatch(FuncRequest(
1345 LFUN_BUFFER_SWITCH, b->absFileName()));
1346 theLyXFunc().dispatch(cmd);
1353 case LFUN_NOTE_NEXT:
1354 gotoInset(this, NOTE_CODE, false);
1357 case LFUN_REFERENCE_NEXT: {
1358 vector<InsetCode> tmp;
1359 tmp.push_back(LABEL_CODE);
1360 tmp.push_back(REF_CODE);
1361 gotoInset(this, tmp, true);
1365 case LFUN_CHANGES_TRACK:
1366 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1369 case LFUN_CHANGES_OUTPUT:
1370 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1371 if (buffer_.params().outputChanges) {
1372 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1373 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1374 LaTeXFeatures::isAvailable("xcolor");
1376 if (!dvipost && !xcolorulem) {
1377 Alert::warning(_("Changes not shown in LaTeX output"),
1378 _("Changes will not be highlighted in LaTeX output, "
1379 "because neither dvipost nor xcolor/ulem are installed.\n"
1380 "Please install these packages or redefine "
1381 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1382 } else if (!xcolorulem) {
1383 Alert::warning(_("Changes not shown in LaTeX output"),
1384 _("Changes will not be highlighted in LaTeX output "
1385 "when using pdflatex, because xcolor and ulem are not installed.\n"
1386 "Please install both packages or redefine "
1387 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1392 case LFUN_CHANGE_NEXT:
1393 findNextChange(this);
1394 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1395 dr.update(Update::Force | Update::FitCursor);
1398 case LFUN_CHANGE_PREVIOUS:
1399 findPreviousChange(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_CHANGES_MERGE:
1405 if (findNextChange(this) || findPreviousChange(this)) {
1406 dr.update(Update::Force | Update::FitCursor);
1407 showDialog("changes");
1411 case LFUN_ALL_CHANGES_ACCEPT:
1412 // select complete document
1414 cur.selHandle(true);
1415 buffer_.text().cursorBottom(cur);
1416 // accept everything in a single step to support atomic undo
1417 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1418 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1419 dr.update(Update::Force | Update::FitCursor);
1422 case LFUN_ALL_CHANGES_REJECT:
1423 // select complete document
1425 cur.selHandle(true);
1426 buffer_.text().cursorBottom(cur);
1427 // reject everything in a single step to support atomic undo
1428 // Note: reject does not work recursively; the user may have to repeat the operation
1429 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1430 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1431 dr.update(Update::Force | Update::FitCursor);
1434 case LFUN_WORD_FIND_FORWARD:
1435 case LFUN_WORD_FIND_BACKWARD: {
1436 static docstring last_search;
1437 docstring searched_string;
1439 if (!cmd.argument().empty()) {
1440 last_search = cmd.argument();
1441 searched_string = cmd.argument();
1443 searched_string = last_search;
1446 if (searched_string.empty())
1449 bool const fw = cmd.action == LFUN_WORD_FIND_FORWARD;
1450 docstring const data =
1451 find2string(searched_string, true, false, fw);
1452 find(this, FuncRequest(LFUN_WORD_FIND, data));
1456 case LFUN_WORD_FIND: {
1457 FuncRequest req = cmd;
1458 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1459 req = d->search_request_cache_;
1460 if (req.argument().empty()) {
1461 theLyXFunc().dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1464 if (find(this, req))
1467 message(_("String not found!"));
1468 d->search_request_cache_ = req;
1472 case LFUN_WORD_REPLACE: {
1473 bool has_deleted = false;
1474 if (cur.selection()) {
1475 DocIterator beg = cur.selectionBegin();
1476 DocIterator end = cur.selectionEnd();
1477 if (beg.pit() == end.pit()) {
1478 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1480 && cur.paragraph().isDeleted(p))
1485 replace(this, cmd, has_deleted);
1489 case LFUN_WORD_FINDADV: {
1490 FindAndReplaceOptions opt;
1491 istringstream iss(to_utf8(cmd.argument()));
1493 if (findAdv(this, opt))
1501 cur.clearSelection();
1502 dr.setMessage(from_utf8(N_("Mark off")));
1506 cur.clearSelection();
1508 dr.setMessage(from_utf8(N_("Mark on")));
1511 case LFUN_MARK_TOGGLE:
1512 cur.setSelection(false);
1515 dr.setMessage(from_utf8(N_("Mark removed")));
1518 dr.setMessage(from_utf8(N_("Mark set")));
1523 case LFUN_SCREEN_SHOW_CURSOR:
1527 case LFUN_SCREEN_RECENTER:
1531 case LFUN_BIBTEX_DATABASE_ADD: {
1532 Cursor tmpcur = cur;
1533 findInset(tmpcur, BIBTEX_CODE, false);
1534 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1537 if (inset->addDatabase(cmd.argument()))
1538 buffer_.updateBibfilesCache();
1543 case LFUN_BIBTEX_DATABASE_DEL: {
1544 Cursor tmpcur = cur;
1545 findInset(tmpcur, BIBTEX_CODE, false);
1546 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1549 if (inset->delDatabase(cmd.argument()))
1550 buffer_.updateBibfilesCache();
1555 case LFUN_STATISTICS: {
1556 DocIterator from, to;
1557 if (cur.selection()) {
1558 from = cur.selectionBegin();
1559 to = cur.selectionEnd();
1561 from = doc_iterator_begin(&buffer_);
1562 to = doc_iterator_end(&buffer_);
1564 int const words = countWords(from, to);
1565 int const chars = countChars(from, to, false);
1566 int const chars_blanks = countChars(from, to, true);
1568 if (cur.selection())
1569 message = _("Statistics for the selection:");
1571 message = _("Statistics for the document:");
1574 message += bformat(_("%1$d words"), words);
1576 message += _("One word");
1578 if (chars_blanks != 1)
1579 message += bformat(_("%1$d characters (including blanks)"),
1582 message += _("One character (including blanks)");
1585 message += bformat(_("%1$d characters (excluding blanks)"),
1588 message += _("One character (excluding blanks)");
1590 Alert::information(_("Statistics"), message);
1594 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1595 // turn compression on/off
1596 buffer_.params().compressed = !buffer_.params().compressed;
1599 case LFUN_LABEL_COPY_AS_REF: {
1600 // if there is an inset at cursor, try to copy it
1601 Inset * inset = &cur.inset();
1602 if (!inset || !inset->asInsetMath())
1603 inset = cur.nextInset();
1605 FuncRequest tmpcmd = cmd;
1606 inset->dispatch(cur, tmpcmd);
1608 if (!cur.result().dispatched())
1609 // It did not work too; no action needed.
1611 cur.clearSelection();
1612 dr.update(Update::SinglePar | Update::FitCursor);
1616 case LFUN_SCREEN_UP:
1617 case LFUN_SCREEN_DOWN: {
1618 Point p = getPos(cur, cur.boundary());
1619 // This code has been commented out to enable to scroll down a
1620 // document, even if there are large insets in it (see bug #5465).
1621 /*if (p.y_ < 0 || p.y_ > height_) {
1622 // The cursor is off-screen so recenter before proceeding.
1624 p = getPos(cur, cur.boundary());
1626 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1627 ? -height_ : height_);
1628 if (cmd.action == LFUN_SCREEN_UP && scrolled > -height_)
1630 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1631 p = Point(width_, height_);
1633 bool const in_texted = cur.inTexted();
1635 buffer_.changed(true);
1636 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1637 true, cmd.action == LFUN_SCREEN_UP);
1638 //FIXME: what to do with cur.x_target()?
1639 bool update = in_texted && cur.bv().checkDepm(cur, old);
1642 dr.update(Update::Force | Update::FitCursor);
1650 case LFUN_SCREEN_UP_SELECT: {
1651 cur.selHandle(true);
1652 if (isTopScreen()) {
1653 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1657 int y = getPos(cur, cur.boundary()).y_;
1658 int const ymin = y - height_ + defaultRowHeight();
1659 while (y > ymin && cur.up())
1660 y = getPos(cur, cur.boundary()).y_;
1663 dr.update(Update::SinglePar | Update::FitCursor);
1667 case LFUN_SCREEN_DOWN_SELECT: {
1668 cur.selHandle(true);
1669 if (isBottomScreen()) {
1670 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1674 int y = getPos(cur, cur.boundary()).y_;
1675 int const ymax = y + height_ - defaultRowHeight();
1676 while (y < ymax && cur.down())
1677 y = getPos(cur, cur.boundary()).y_;
1680 dr.update(Update::SinglePar | Update::FitCursor);
1685 // This would be in Buffer class if only Cursor did not
1686 // require a bufferview
1687 case LFUN_INSET_FORALL: {
1688 docstring const name = from_utf8(cmd.getArg(0));
1689 string const commandstr = cmd.getLongArg(1);
1690 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1692 // an arbitrary number to limit number of iterations
1693 const int max_iter = 10000;
1695 Cursor & cur = d->cursor_;
1696 Cursor const savecur = cur;
1698 if (!cur.nextInset())
1700 cur.beginUndoGroup();
1701 while(cur && iterations < max_iter) {
1702 Inset * ins = cur.nextInset();
1705 docstring insname = ins->name();
1706 while (!insname.empty()) {
1707 if (insname == name || name == from_utf8("*")) {
1713 size_t const i = insname.rfind(':');
1714 if (i == string::npos)
1716 insname = insname.substr(0, i);
1723 dr.update(Update::Force);
1725 if (iterations >= max_iter) {
1727 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1729 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1734 case LFUN_ALL_INSETS_TOGGLE: {
1736 string const name = split(to_utf8(cmd.argument()), action, ' ');
1737 InsetCode const inset_code = insetCode(name);
1739 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1741 Inset & inset = cur.buffer()->inset();
1742 InsetIterator it = inset_iterator_begin(inset);
1743 InsetIterator const end = inset_iterator_end(inset);
1744 for (; it != end; ++it) {
1745 if (it->asInsetCollapsable()
1746 && (inset_code == NO_CODE
1747 || inset_code == it->lyxCode())) {
1748 Cursor tmpcur = cur;
1749 tmpcur.pushBackward(*it);
1750 it->dispatch(tmpcur, fr);
1753 dr.update(Update::Force | Update::FitCursor);
1757 case LFUN_BRANCH_ADD_INSERT: {
1758 docstring branch_name = from_utf8(cmd.getArg(0));
1759 if (branch_name.empty())
1760 if (!Alert::askForText(branch_name, _("Branch name")) ||
1761 branch_name.empty())
1764 DispatchResult drtmp;
1765 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1766 if (drtmp.error()) {
1767 Alert::warning(_("Branch already exists"), drtmp.message());
1770 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1774 case LFUN_KEYMAP_OFF:
1775 getIntl().keyMapOn(false);
1778 case LFUN_KEYMAP_PRIMARY:
1779 getIntl().keyMapPrim();
1782 case LFUN_KEYMAP_SECONDARY:
1783 getIntl().keyMapSec();
1786 case LFUN_KEYMAP_TOGGLE:
1787 getIntl().toggleKeyMap();
1790 case LFUN_DIALOG_SHOW_NEW_INSET: {
1791 string const name = cmd.getArg(0);
1792 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1793 if (decodeInsetParam(name, data, buffer_))
1794 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1796 lyxerr << "Inset type '" << name <<
1797 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1801 case LFUN_CITATION_INSERT: {
1802 if (argument.empty()) {
1803 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1806 // we can have one optional argument, delimited by '|'
1807 // citation-insert <key>|<text_before>
1808 // this should be enhanced to also support text_after
1809 // and citation style
1810 string arg = argument;
1812 if (contains(argument, "|")) {
1813 arg = token(argument, '|', 0);
1814 opt1 = token(argument, '|', 1);
1816 InsetCommandParams icp(CITE_CODE);
1817 icp["key"] = from_utf8(arg);
1819 icp["before"] = from_utf8(opt1);
1820 string icstr = InsetCommand::params2string("citation", icp);
1821 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1826 case LFUN_INSET_APPLY: {
1827 string const name = cmd.getArg(0);
1828 Inset * inset = editedInset(name);
1830 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1834 // put cursor in front of inset.
1835 if (!setCursorFromInset(inset)) {
1836 LASSERT(false, break);
1839 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1840 inset->dispatch(cur, fr);
1841 dr.update(Update::SinglePar | Update::FitCursor);
1850 buffer_.undo().endUndoGroup();
1851 dr.dispatched(dispatched);
1856 docstring const BufferView::requestSelection()
1858 Cursor & cur = d->cursor_;
1860 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1861 if (!cur.selection()) {
1862 d->xsel_cache_.set = false;
1866 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1867 if (!d->xsel_cache_.set ||
1868 cur.top() != d->xsel_cache_.cursor ||
1869 cur.anchor_.top() != d->xsel_cache_.anchor)
1871 d->xsel_cache_.cursor = cur.top();
1872 d->xsel_cache_.anchor = cur.anchor_.top();
1873 d->xsel_cache_.set = cur.selection();
1874 return cur.selectionAsString(false);
1880 void BufferView::clearSelection()
1882 d->cursor_.clearSelection();
1883 // Clear the selection buffer. Otherwise a subsequent
1884 // middle-mouse-button paste would use the selection buffer,
1885 // not the more current external selection.
1886 cap::clearSelection();
1887 d->xsel_cache_.set = false;
1888 // The buffer did not really change, but this causes the
1889 // redraw we need because we cleared the selection above.
1890 buffer_.changed(false);
1894 void BufferView::resize(int width, int height)
1896 // Update from work area
1900 // Clear the paragraph height cache.
1901 d->par_height_.clear();
1902 // Redo the metrics.
1907 Inset const * BufferView::getCoveringInset(Text const & text,
1910 TextMetrics & tm = d->text_metrics_[&text];
1911 Inset * inset = tm.checkInsetHit(x, y);
1915 if (!inset->descendable(*this))
1916 // No need to go further down if the inset is not
1920 size_t cell_number = inset->nargs();
1921 // Check all the inner cell.
1922 for (size_t i = 0; i != cell_number; ++i) {
1923 Text const * inner_text = inset->getText(i);
1926 Inset const * inset_deeper =
1927 getCoveringInset(*inner_text, x, y);
1929 return inset_deeper;
1937 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1939 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1941 // This is only called for mouse related events including
1942 // LFUN_FILE_OPEN generated by drag-and-drop.
1943 FuncRequest cmd = cmd0;
1945 Cursor old = cursor();
1947 cur.push(buffer_.inset());
1948 cur.setSelection(d->cursor_.selection());
1950 // Either the inset under the cursor or the
1951 // surrounding Text will handle this event.
1953 // make sure we stay within the screen...
1954 cmd.y = min(max(cmd.y, -1), height_);
1956 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1958 // Get inset under mouse, if there is one.
1959 Inset const * covering_inset =
1960 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1961 if (covering_inset == d->last_inset_)
1962 // Same inset, no need to do anything...
1965 bool need_redraw = false;
1966 // const_cast because of setMouseHover().
1967 Inset * inset = const_cast<Inset *>(covering_inset);
1969 // Remove the hint on the last hovered inset (if any).
1970 need_redraw |= d->last_inset_->setMouseHover(false);
1972 // Highlighted the newly hovered inset (if any).
1973 need_redraw |= inset->setMouseHover(true);
1974 d->last_inset_ = inset;
1978 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1979 << cmd.x << ", " << cmd.y << ")");
1981 d->update_strategy_ = DecorationUpdate;
1983 // This event (moving without mouse click) is not passed further.
1984 // This should be changed if it is further utilized.
1985 buffer_.changed(false);
1989 // Build temporary cursor.
1990 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1992 // Put anchor at the same position.
1995 cur.beginUndoGroup();
1997 // Try to dispatch to an non-editable inset near this position
1998 // via the temp cursor. If the inset wishes to change the real
1999 // cursor it has to do so explicitly by using
2000 // cur.bv().cursor() = cur; (or similar)
2002 inset->dispatch(cur, cmd);
2004 // Now dispatch to the temporary cursor. If the real cursor should
2005 // be modified, the inset's dispatch has to do so explicitly.
2006 if (!inset || !cur.result().dispatched())
2011 // Notify left insets
2014 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
2016 cursor().fixIfBroken();
2019 // Do we have a selection?
2020 theSelection().haveSelection(cursor().selection());
2022 // If the command has been dispatched,
2023 if (cur.result().dispatched() || cur.result().update())
2024 processUpdateFlags(cur.result().update());
2028 void BufferView::lfunScroll(FuncRequest const & cmd)
2030 string const scroll_type = cmd.getArg(0);
2031 int const scroll_step =
2032 (scroll_type == "line") ? d->scrollbarParameters_.single_step
2033 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
2034 if (scroll_step == 0)
2036 string const scroll_quantity = cmd.getArg(1);
2037 if (scroll_quantity == "up")
2038 scrollUp(scroll_step);
2039 else if (scroll_quantity == "down")
2040 scrollDown(scroll_step);
2042 int const scroll_value = convert<int>(scroll_quantity);
2044 scroll(scroll_step * scroll_value);
2046 buffer_.changed(true);
2050 int BufferView::minVisiblePart()
2052 return 2 * defaultRowHeight();
2056 int BufferView::scroll(int y)
2059 return scrollDown(y);
2061 return scrollUp(-y);
2066 int BufferView::scrollDown(int offset)
2068 Text * text = &buffer_.text();
2069 TextMetrics & tm = d->text_metrics_[text];
2070 int const ymax = height_ + offset;
2072 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2073 int bottom_pos = last.second->position() + last.second->descent();
2074 if (lyxrc.scroll_below_document)
2075 bottom_pos += height_ - minVisiblePart();
2076 if (last.first + 1 == int(text->paragraphs().size())) {
2077 if (bottom_pos <= height_)
2079 offset = min(offset, bottom_pos - height_);
2082 if (bottom_pos > ymax)
2084 tm.newParMetricsDown();
2086 d->anchor_ypos_ -= offset;
2091 int BufferView::scrollUp(int offset)
2093 Text * text = &buffer_.text();
2094 TextMetrics & tm = d->text_metrics_[text];
2095 int ymin = - offset;
2097 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2098 int top_pos = first.second->position() - first.second->ascent();
2099 if (first.first == 0) {
2102 offset = min(offset, - top_pos);
2107 tm.newParMetricsUp();
2109 d->anchor_ypos_ += offset;
2114 void BufferView::setCursorFromRow(int row)
2119 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
2123 buffer_.text().setCursor(d->cursor_, 0, 0);
2125 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
2130 bool BufferView::setCursorFromInset(Inset const * inset)
2132 // are we already there?
2133 if (cursor().nextInset() == inset)
2136 // Inset is not at cursor position. Find it in the document.
2139 while (cur && cur.nextInset() != inset)
2150 void BufferView::gotoLabel(docstring const & label)
2152 std::vector<Buffer const *> bufs = buffer().allRelatives();
2153 std::vector<Buffer const *>::iterator it = bufs.begin();
2154 for (; it != bufs.end(); ++it) {
2155 Buffer const * buf = *it;
2158 Toc & toc = buf->tocBackend().toc("label");
2159 TocIterator toc_it = toc.begin();
2160 TocIterator end = toc.end();
2161 for (; toc_it != end; ++toc_it) {
2162 if (label == toc_it->str()) {
2163 lyx::dispatch(toc_it->action());
2171 TextMetrics const & BufferView::textMetrics(Text const * t) const
2173 return const_cast<BufferView *>(this)->textMetrics(t);
2177 TextMetrics & BufferView::textMetrics(Text const * t)
2179 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2180 if (tmc_it == d->text_metrics_.end()) {
2181 tmc_it = d->text_metrics_.insert(
2182 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2184 return tmc_it->second;
2188 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2191 return textMetrics(t).parMetrics(pit);
2195 int BufferView::workHeight() const
2201 void BufferView::setCursor(DocIterator const & dit)
2204 size_t const n = dit.depth();
2205 for (size_t i = 0; i < n; ++i)
2206 dit[i].inset().edit(d->cursor_, true);
2208 d->cursor_.setCursor(dit);
2209 d->cursor_.setSelection(false);
2213 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2215 // Would be wrong to delete anything if we have a selection.
2216 if (cur.selection())
2219 bool need_anchor_change = false;
2220 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2221 need_anchor_change);
2223 if (need_anchor_change)
2231 buffer_.updateLabels();
2232 buffer_.changed(true);
2237 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2239 LASSERT(&cur.bv() == this, /**/);
2242 // this event will clear selection so we save selection for
2243 // persistent selection
2244 cap::saveSelection(cursor());
2246 d->cursor_.macroModeClose();
2248 // Has the cursor just left the inset?
2249 bool leftinset = (&d->cursor_.inset() != &cur.inset());
2251 d->cursor_.fixIfBroken();
2253 // FIXME: shift-mouse selection doesn't work well across insets.
2254 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
2256 // do the dEPM magic if needed
2257 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2258 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2259 // the leftinset bool would not be necessary (badcursor instead).
2260 bool update = leftinset;
2261 if (!do_selection && d->cursor_.inTexted())
2262 update |= checkDepm(cur, d->cursor_);
2265 d->cursor_.resetAnchor();
2266 d->cursor_.setCursor(cur);
2267 d->cursor_.boundary(cur.boundary());
2269 d->cursor_.setSelection();
2271 d->cursor_.clearSelection();
2273 d->cursor_.finishUndo();
2274 d->cursor_.setCurrentFont();
2279 void BufferView::putSelectionAt(DocIterator const & cur,
2280 int length, bool backwards)
2282 d->cursor_.clearSelection();
2288 d->cursor_.pos() += length;
2289 d->cursor_.setSelection(d->cursor_, -length);
2291 d->cursor_.setSelection(d->cursor_, length);
2293 // Ensure a redraw happens in any case because the new selection could
2294 // possibly be on the same screen as the previous selection.
2295 processUpdateFlags(Update::Force | Update::FitCursor);
2299 Cursor & BufferView::cursor()
2305 Cursor const & BufferView::cursor() const
2311 pit_type BufferView::anchor_ref() const
2313 return d->anchor_pit_;
2317 bool BufferView::singleParUpdate()
2319 Text & buftext = buffer_.text();
2320 pit_type const bottom_pit = d->cursor_.bottom().pit();
2321 TextMetrics & tm = textMetrics(&buftext);
2322 int old_height = tm.parMetrics(bottom_pit).height();
2324 // make sure inline completion pointer is ok
2325 if (d->inlineCompletionPos_.fixIfBroken())
2326 d->inlineCompletionPos_ = DocIterator();
2328 // In Single Paragraph mode, rebreak only
2329 // the (main text, not inset!) paragraph containing the cursor.
2330 // (if this paragraph contains insets etc., rebreaking will
2331 // recursively descend)
2332 tm.redoParagraph(bottom_pit);
2333 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2334 if (pm.height() != old_height)
2335 // Paragraph height has changed so we cannot proceed to
2336 // the singlePar optimisation.
2339 d->update_strategy_ = SingleParUpdate;
2341 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2342 << " y2: " << pm.position() + pm.descent()
2343 << " pit: " << bottom_pit
2344 << " singlepar: 1");
2349 void BufferView::updateMetrics()
2351 if (height_ == 0 || width_ == 0)
2354 Text & buftext = buffer_.text();
2355 pit_type const npit = int(buftext.paragraphs().size());
2357 // Clear out the position cache in case of full screen redraw,
2358 d->coord_cache_.clear();
2360 // Clear out paragraph metrics to avoid having invalid metrics
2361 // in the cache from paragraphs not relayouted below
2362 // The complete text metrics will be redone.
2363 d->text_metrics_.clear();
2365 TextMetrics & tm = textMetrics(&buftext);
2367 // make sure inline completion pointer is ok
2368 if (d->inlineCompletionPos_.fixIfBroken())
2369 d->inlineCompletionPos_ = DocIterator();
2371 if (d->anchor_pit_ >= npit)
2372 // The anchor pit must have been deleted...
2373 d->anchor_pit_ = npit - 1;
2375 // Rebreak anchor paragraph.
2376 tm.redoParagraph(d->anchor_pit_);
2377 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2380 if (d->anchor_pit_ == 0) {
2381 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2383 // Complete buffer visible? Then it's easy.
2384 if (scrollRange == 0)
2385 d->anchor_ypos_ = anchor_pm.ascent();
2387 // FIXME: Some clever handling needed to show
2388 // the _first_ paragraph up to the top if the cursor is
2389 // in the first line.
2391 anchor_pm.setPosition(d->anchor_ypos_);
2393 LYXERR(Debug::PAINTING, "metrics: "
2394 << " anchor pit = " << d->anchor_pit_
2395 << " anchor ypos = " << d->anchor_ypos_);
2397 // Redo paragraphs above anchor if necessary.
2398 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2399 // We are now just above the anchor paragraph.
2400 pit_type pit1 = d->anchor_pit_ - 1;
2401 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2402 tm.redoParagraph(pit1);
2403 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2405 // Save the paragraph position in the cache.
2410 // Redo paragraphs below the anchor if necessary.
2411 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2412 // We are now just below the anchor paragraph.
2413 pit_type pit2 = d->anchor_pit_ + 1;
2414 for (; pit2 < npit && y2 <= height_; ++pit2) {
2415 tm.redoParagraph(pit2);
2416 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2418 // Save the paragraph position in the cache.
2423 LYXERR(Debug::PAINTING, "Metrics: "
2424 << " anchor pit = " << d->anchor_pit_
2425 << " anchor ypos = " << d->anchor_ypos_
2428 << " pit1 = " << pit1
2429 << " pit2 = " << pit2);
2431 d->update_strategy_ = FullScreenUpdate;
2433 if (lyxerr.debugging(Debug::WORKAREA)) {
2434 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2435 d->coord_cache_.dump();
2440 void BufferView::insertLyXFile(FileName const & fname)
2442 LASSERT(d->cursor_.inTexted(), /**/);
2444 // Get absolute path of file and add ".lyx"
2445 // to the filename if necessary
2446 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2448 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2449 // emit message signal.
2450 message(bformat(_("Inserting document %1$s..."), disp_fn));
2453 Buffer buf("", false);
2454 if (buf.loadLyXFile(filename)) {
2455 ErrorList & el = buffer_.errorList("Parse");
2456 // Copy the inserted document error list into the current buffer one.
2457 el = buf.errorList("Parse");
2458 buffer_.undo().recordUndo(d->cursor_);
2459 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2460 buf.params().documentClassPtr(), el);
2461 res = _("Document %1$s inserted.");
2463 res = _("Could not insert document %1$s");
2466 buffer_.changed(true);
2467 // emit message signal.
2468 message(bformat(res, disp_fn));
2469 buffer_.errors("Parse");
2473 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2479 // Addup contribution of nested insets, from inside to outside,
2480 // keeping the outer paragraph for a special handling below
2481 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2482 CursorSlice const & sl = dit[i];
2486 // get relative position inside sl.inset()
2487 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2489 // Make relative position inside of the edited inset relative to sl.inset()
2493 // In case of an RTL inset, the edited inset will be positioned to the left
2496 bool boundary_i = boundary && i + 1 == dit.depth();
2497 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2502 // remember width for the case that sl.inset() is positioned in an RTL inset
2503 if (i && dit[i - 1].text()) {
2504 // If this Inset is inside a Text Inset, retrieve the Dimension
2505 // from the containing text instead of using Inset::dimension() which
2506 // might not be implemented.
2507 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2508 // elimination of Inset::dim_ cache. This coordOffset() method needs
2509 // to be rewritten in light of the new design.
2510 Dimension const & dim = parMetrics(dit[i - 1].text(),
2511 dit[i - 1].pit()).insetDimension(&sl.inset());
2514 Dimension const dim = sl.inset().dimension(*this);
2518 //lyxerr << "Cursor::getPos, i: "
2519 // << i << " x: " << xx << " y: " << y << endl;
2522 // Add contribution of initial rows of outermost paragraph
2523 CursorSlice const & sl = dit[0];
2524 TextMetrics const & tm = textMetrics(sl.text());
2525 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2526 LASSERT(!pm.rows().empty(), /**/);
2527 y -= pm.rows()[0].ascent();
2529 // FIXME: document this mess
2531 if (sl.pos() > 0 && dit.depth() == 1) {
2533 if (pos && boundary)
2535 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2536 rend = pm.pos2row(pos);
2538 rend = pm.pos2row(sl.pos());
2540 size_t rend = pm.pos2row(sl.pos());
2542 for (size_t rit = 0; rit != rend; ++rit)
2543 y += pm.rows()[rit].height();
2544 y += pm.rows()[rend].ascent();
2546 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2548 // Make relative position from the nested inset now bufferview absolute.
2549 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2552 // In the RTL case place the nested inset at the left of the cursor in
2553 // the outer paragraph
2554 bool boundary_1 = boundary && 1 == dit.depth();
2555 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2563 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2565 if (!paragraphVisible(dit))
2566 return Point(-1, -1);
2568 CursorSlice const & bot = dit.bottom();
2569 TextMetrics const & tm = textMetrics(bot.text());
2571 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2572 p.y_ += tm.parMetrics(bot.pit()).position();
2577 bool BufferView::paragraphVisible(DocIterator const & dit) const
2579 CursorSlice const & bot = dit.bottom();
2580 TextMetrics const & tm = textMetrics(bot.text());
2582 return tm.contains(bot.pit());
2586 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2588 Cursor const & cur = cursor();
2589 Font const font = cur.getFont();
2590 frontend::FontMetrics const & fm = theFontMetrics(font);
2591 int const asc = fm.maxAscent();
2592 int const des = fm.maxDescent();
2594 p = getPos(cur, cur.boundary());
2599 bool BufferView::cursorInView(Point const & p, int h) const
2601 Cursor const & cur = cursor();
2602 // does the cursor touch the screen ?
2603 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2609 void BufferView::draw(frontend::Painter & pain)
2611 if (height_ == 0 || width_ == 0)
2613 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2615 Text & text = buffer_.text();
2616 TextMetrics const & tm = d->text_metrics_[&text];
2617 int const y = tm.first().second->position();
2618 PainterInfo pi(this, pain);
2620 switch (d->update_strategy_) {
2622 case NoScreenUpdate:
2623 // If no screen painting is actually needed, only some the different
2624 // coordinates of insets and paragraphs needs to be updated.
2625 pi.full_repaint = true;
2626 pi.pain.setDrawingEnabled(false);
2630 case SingleParUpdate:
2631 pi.full_repaint = false;
2632 // In general, only the current row of the outermost paragraph
2633 // will be redrawn. Particular cases where selection spans
2634 // multiple paragraph are correctly detected in TextMetrics.
2638 case DecorationUpdate:
2639 // FIXME: We should also distinguish DecorationUpdate to avoid text
2640 // drawing if possible. This is not possible to do easily right now
2641 // because of the single backing pixmap.
2643 case FullScreenUpdate:
2644 // The whole screen, including insets, will be refreshed.
2645 pi.full_repaint = true;
2647 // Clear background.
2648 pain.fillRectangle(0, 0, width_, height_,
2649 pi.backgroundColor(&buffer_.inset()));
2654 // and possibly grey out below
2655 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2656 int const y2 = lastpm.second->position() + lastpm.second->descent();
2659 Color color = buffer().isInternal()
2660 ? Color_background : Color_bottomarea;
2661 pain.fillRectangle(0, y2, width_, height_ - y2, color);
2665 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2667 // The scrollbar needs an update.
2670 // Normalize anchor for next time
2671 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2672 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2673 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2674 ParagraphMetrics const & pm = tm.parMetrics(pit);
2675 if (pm.position() + pm.descent() > 0) {
2676 d->anchor_pit_ = pit;
2677 d->anchor_ypos_ = pm.position();
2681 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2682 << " anchor ypos = " << d->anchor_ypos_);
2686 void BufferView::message(docstring const & msg)
2689 d->gui_->message(msg);
2693 void BufferView::showDialog(string const & name)
2696 d->gui_->showDialog(name, string());
2700 void BufferView::showDialog(string const & name,
2701 string const & data, Inset * inset)
2704 d->gui_->showDialog(name, data, inset);
2708 void BufferView::updateDialog(string const & name, string const & data)
2711 d->gui_->updateDialog(name, data);
2715 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2721 // FIXME: Move this out of BufferView again
2722 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2724 if (!fname.isReadableFile()) {
2725 docstring const error = from_ascii(strerror(errno));
2726 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2727 docstring const text =
2728 bformat(_("Could not read the specified document\n"
2729 "%1$s\ndue to the error: %2$s"), file, error);
2730 Alert::error(_("Could not read file"), text);
2734 if (!fname.isReadableFile()) {
2735 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2736 docstring const text =
2737 bformat(_("%1$s\n is not readable."), file);
2738 Alert::error(_("Could not open file"), text);
2742 // FIXME UNICODE: We don't know the encoding of the file
2743 docstring file_content = fname.fileContents("UTF-8");
2744 if (file_content.empty()) {
2745 Alert::error(_("Reading not UTF-8 encoded file"),
2746 _("The file is not UTF-8 encoded.\n"
2747 "It will be read as local 8Bit-encoded.\n"
2748 "If this does not give the correct result\n"
2749 "then please change the encoding of the file\n"
2750 "to UTF-8 with a program other than LyX.\n"));
2751 file_content = fname.fileContents("local8bit");
2754 return normalize_c(file_content);
2758 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2760 docstring const tmpstr = contentsOfPlaintextFile(f);
2765 Cursor & cur = cursor();
2766 cap::replaceSelection(cur);
2767 buffer_.undo().recordUndo(cur);
2769 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2771 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2773 buffer_.changed(true);
2777 docstring const & BufferView::inlineCompletion() const
2779 return d->inlineCompletion_;
2783 size_t const & BufferView::inlineCompletionUniqueChars() const
2785 return d->inlineCompletionUniqueChars_;
2789 DocIterator const & BufferView::inlineCompletionPos() const
2791 return d->inlineCompletionPos_;
2795 bool samePar(DocIterator const & a, DocIterator const & b)
2797 if (a.empty() && b.empty())
2799 if (a.empty() || b.empty())
2801 if (a.depth() != b.depth())
2803 return &a.innerParagraph() == &b.innerParagraph();
2807 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2808 docstring const & completion, size_t uniqueChars)
2810 uniqueChars = min(completion.size(), uniqueChars);
2811 bool changed = d->inlineCompletion_ != completion
2812 || d->inlineCompletionUniqueChars_ != uniqueChars;
2813 bool singlePar = true;
2814 d->inlineCompletion_ = completion;
2815 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2817 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2820 DocIterator const & old = d->inlineCompletionPos_;
2822 //lyxerr << "inlineCompletionPos changed" << std::endl;
2823 // old or pos are in another paragraph?
2824 if ((!samePar(cur, pos) && !pos.empty())
2825 || (!samePar(cur, old) && !old.empty())) {
2827 //lyxerr << "different paragraph" << std::endl;
2829 d->inlineCompletionPos_ = pos;
2834 if (singlePar && !(cur.disp_.update() & Update::Force))
2835 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2837 cur.updateFlags(cur.disp_.update() | Update::Force);