3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
19 #include "BranchList.h"
21 #include "buffer_funcs.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "CoordCache.h"
26 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
34 #include "InsetIterator.h"
36 #include "LaTeXFeatures.h"
42 #include "MetricsInfo.h"
43 #include "Paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
49 #include "TextClass.h"
50 #include "TextMetrics.h"
52 #include "TocBackend.h"
54 #include "WordLangTuple.h"
56 #include "insets/InsetBibtex.h"
57 #include "insets/InsetCommand.h" // ChangeRefs
58 #include "insets/InsetExternal.h"
59 #include "insets/InsetGraphics.h"
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
62 #include "insets/InsetNote.h"
64 #include "frontends/alert.h"
65 #include "frontends/Application.h"
66 #include "frontends/Delegates.h"
67 #include "frontends/FontMetrics.h"
68 #include "frontends/Painter.h"
69 #include "frontends/Selection.h"
71 #include "graphics/Previews.h"
73 #include "support/convert.h"
74 #include "support/debug.h"
75 #include "support/ExceptionMessage.h"
76 #include "support/filetools.h"
77 #include "support/gettext.h"
78 #include "support/lstrings.h"
79 #include "support/Package.h"
80 #include "support/types.h"
89 using namespace lyx::support;
93 namespace Alert = frontend::Alert;
97 /// Return an inset of this class if it exists at the current cursor position
99 T * getInsetByCode(Cursor const & cur, InsetCode code)
101 DocIterator it = cur;
102 Inset * inset = it.nextInset();
103 if (inset && inset->lyxCode() == code)
104 return static_cast<T*>(inset);
109 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
112 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
113 docstring const & contents)
115 DocIterator tmpdit = dit;
118 Inset const * inset = tmpdit.nextInset();
120 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
121 && (contents.empty() ||
122 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
126 tmpdit.forwardInset();
133 /// Looks for next inset with one of the given codes.
134 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
138 DocIterator tmpdit = dit;
139 tmpdit.forwardInset();
144 Inset const * inset = tmpdit.nextInset();
146 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
147 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
151 if (!findNextInset(tmpdit, codes, contents)) {
152 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
153 Inset * inset = &tmpdit.bottom().inset();
154 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
155 if (!findNextInset(tmpdit, codes, contents))
167 /// Looks for next inset with the given code
168 void findInset(DocIterator & dit, InsetCode code, bool same_content)
170 findInset(dit, vector<InsetCode>(1, code), same_content);
174 /// Moves cursor to the next inset with one of the given codes.
175 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
178 Cursor tmpcur = bv->cursor();
179 if (!findInset(tmpcur, codes, same_content)) {
180 bv->cursor().message(_("No more insets"));
184 tmpcur.clearSelection();
185 bv->setCursor(tmpcur);
190 /// Moves cursor to the next inset with given code.
191 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
193 gotoInset(bv, vector<InsetCode>(1, code), same_content);
197 /// A map from a Text to the associated text metrics
198 typedef map<Text const *, TextMetrics> TextMetricsCache;
200 enum ScreenUpdateStrategy {
210 /////////////////////////////////////////////////////////////////////
214 /////////////////////////////////////////////////////////////////////
216 struct BufferView::Private
218 Private(BufferView & bv): wh_(0), cursor_(bv),
219 anchor_pit_(0), anchor_ypos_(0),
220 inlineCompletionUniqueChars_(0),
221 last_inset_(0), bookmark_edit_position_(0), gui_(0)
225 ScrollbarParameters scrollbarParameters_;
227 ScreenUpdateStrategy update_strategy_;
229 CoordCache coord_cache_;
231 /// Estimated average par height for scrollbar.
233 /// this is used to handle XSelection events in the right manner.
242 pit_type anchor_pit_;
246 vector<int> par_height_;
249 DocIterator inlineCompletionPos_;
251 docstring inlineCompletion_;
253 size_t inlineCompletionUniqueChars_;
255 /// keyboard mapping object.
258 /// last visited inset.
259 /** kept to send setMouseHover(false).
260 * Not owned, so don't delete.
264 // cache for id of the paragraph which was edited the last time
265 int bookmark_edit_position_;
267 mutable TextMetricsCache text_metrics_;
270 /** Not owned, so don't delete.
272 frontend::GuiBufferViewDelegate * gui_;
274 /// Cache for Find Next
275 FuncRequest search_request_cache_;
279 BufferView::BufferView(Buffer & buf)
280 : width_(0), height_(0), full_screen_(false), buffer_(buf),
281 d(new Private(*this))
283 d->xsel_cache_.set = false;
284 d->intl_.initKeyMapper(lyxrc.use_kbmap);
286 d->cursor_.setBuffer(&buf);
287 d->cursor_.push(buffer_.inset());
288 d->cursor_.resetAnchor();
289 d->cursor_.setCurrentFont();
291 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
292 thePreviews().generateBufferPreviews(buffer_);
296 BufferView::~BufferView()
298 // current buffer is going to be switched-off, save cursor pos
299 // Ideally, the whole cursor stack should be saved, but session
300 // currently can only handle bottom (whole document) level pit and pos.
301 // That is to say, if a cursor is in a nested inset, it will be
302 // restore to the left of the top level inset.
303 LastFilePosSection::FilePos fp;
304 fp.pit = d->cursor_.bottom().pit();
305 fp.pos = d->cursor_.bottom().pos();
306 theSession().lastFilePos().save(buffer_.fileName(), fp);
312 int BufferView::rightMargin() const
314 // The additional test for the case the outliner is opened.
316 !lyxrc.full_screen_limit ||
317 width_ < lyxrc.full_screen_width + 20)
320 return (width_ - lyxrc.full_screen_width) / 2;
324 int BufferView::leftMargin() const
326 return rightMargin();
330 bool BufferView::isTopScreen() const
332 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
336 bool BufferView::isBottomScreen() const
338 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
342 Intl & BufferView::getIntl()
348 Intl const & BufferView::getIntl() const
354 CoordCache & BufferView::coordCache()
356 return d->coord_cache_;
360 CoordCache const & BufferView::coordCache() const
362 return d->coord_cache_;
366 Buffer & BufferView::buffer()
372 Buffer const & BufferView::buffer() const
378 bool BufferView::fitCursor()
380 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
381 frontend::FontMetrics const & fm =
382 theFontMetrics(d->cursor_.getFont().fontInfo());
383 int const asc = fm.maxAscent();
384 int const des = fm.maxDescent();
385 Point const p = getPos(d->cursor_, d->cursor_.boundary());
386 if (p.y_ - asc >= 0 && p.y_ + des < height_)
393 void BufferView::processUpdateFlags(Update::flags flags)
395 // last_inset_ points to the last visited inset. This pointer may become
396 // invalid because of keyboard editing. Since all such operations
397 // causes screen update(), I reset last_inset_ to avoid such a problem.
399 // This is close to a hot-path.
400 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
401 << "[fitcursor = " << (flags & Update::FitCursor)
402 << ", forceupdate = " << (flags & Update::Force)
403 << ", singlepar = " << (flags & Update::SinglePar)
404 << "] buffer: " << &buffer_);
406 buffer_.updateMacros();
408 // Now do the first drawing step if needed. This consists on updating
409 // the CoordCache in updateMetrics().
410 // The second drawing step is done in WorkArea::redraw() if needed.
412 // Case when no explicit update is requested.
414 // no need to redraw anything.
415 d->update_strategy_ = NoScreenUpdate;
419 if (flags == Update::Decoration) {
420 d->update_strategy_ = DecorationUpdate;
425 if (flags == Update::FitCursor
426 || flags == (Update::Decoration | Update::FitCursor)) {
427 // tell the frontend to update the screen if needed.
432 if (flags & Update::Decoration) {
433 d->update_strategy_ = DecorationUpdate;
437 // no screen update is needed.
438 d->update_strategy_ = NoScreenUpdate;
442 bool const full_metrics = flags & Update::Force || !singleParUpdate();
445 // We have to update the full screen metrics.
448 if (!(flags & Update::FitCursor)) {
449 // Nothing to do anymore. Trigger a redraw and return
454 // updateMetrics() does not update paragraph position
455 // This is done at draw() time. So we need a redraw!
459 // The cursor is off screen so ensure it is visible.
466 void BufferView::updateScrollbar()
468 if (height_ == 0 && width_ == 0)
471 // We prefer fixed size line scrolling.
472 d->scrollbarParameters_.single_step = defaultRowHeight();
473 // We prefer full screen page scrolling.
474 d->scrollbarParameters_.page_step = height_;
476 Text & t = buffer_.text();
477 TextMetrics & tm = d->text_metrics_[&t];
479 LYXERR(Debug::GUI, " Updating scrollbar: height: "
480 << t.paragraphs().size()
481 << " curr par: " << d->cursor_.bottom().pit()
482 << " default height " << defaultRowHeight());
484 size_t const parsize = t.paragraphs().size();
485 if (d->par_height_.size() != parsize) {
486 d->par_height_.clear();
487 // FIXME: We assume a default paragraph height of 2 rows. This
488 // should probably be pondered with the screen width.
489 d->par_height_.resize(parsize, defaultRowHeight() * 2);
492 // Look at paragraph heights on-screen
493 pair<pit_type, ParagraphMetrics const *> first = tm.first();
494 pair<pit_type, ParagraphMetrics const *> last = tm.last();
495 for (pit_type pit = first.first; pit <= last.first; ++pit) {
496 d->par_height_[pit] = tm.parMetrics(pit).height();
497 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
498 << d->par_height_[pit]);
501 int top_pos = first.second->position() - first.second->ascent();
502 int bottom_pos = last.second->position() + last.second->descent();
503 bool first_visible = first.first == 0 && top_pos >= 0;
504 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
505 if (first_visible && last_visible) {
506 d->scrollbarParameters_.min = 0;
507 d->scrollbarParameters_.max = 0;
511 d->scrollbarParameters_.min = top_pos;
512 for (size_t i = 0; i != size_t(first.first); ++i)
513 d->scrollbarParameters_.min -= d->par_height_[i];
514 d->scrollbarParameters_.max = bottom_pos;
515 for (size_t i = last.first + 1; i != parsize; ++i)
516 d->scrollbarParameters_.max += d->par_height_[i];
518 d->scrollbarParameters_.position = 0;
519 // The reference is the top position so we remove one page.
520 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
524 ScrollbarParameters const & BufferView::scrollbarParameters() const
526 return d->scrollbarParameters_;
530 docstring BufferView::toolTip(int x, int y) const
532 // Get inset under mouse, if there is one.
533 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
535 // No inset, no tooltip...
537 return covering_inset->toolTip(*this, x, y);
541 docstring BufferView::contextMenu(int x, int y) const
543 //If there is a selection, return the containing inset menu
544 if (d->cursor_.selection())
545 return d->cursor_.inset().contextMenu(*this, x, y);
547 // Get inset under mouse, if there is one.
548 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
550 return covering_inset->contextMenu(*this, x, y);
552 return buffer_.inset().contextMenu(*this, x, y);
556 void BufferView::scrollDocView(int value)
558 int const offset = value - d->scrollbarParameters_.position;
560 // No scrolling at all? No need to redraw anything
564 // If the offset is less than 2 screen height, prefer to scroll instead.
565 if (abs(offset) <= 2 * height_) {
566 d->anchor_ypos_ -= offset;
572 // cut off at the top
573 if (value <= d->scrollbarParameters_.min) {
574 DocIterator dit = doc_iterator_begin(&buffer_);
576 LYXERR(Debug::SCROLLING, "scroll to top");
580 // cut off at the bottom
581 if (value >= d->scrollbarParameters_.max) {
582 DocIterator dit = doc_iterator_end(&buffer_);
585 LYXERR(Debug::SCROLLING, "scroll to bottom");
589 // find paragraph at target position
590 int par_pos = d->scrollbarParameters_.min;
592 for (; i != int(d->par_height_.size()); ++i) {
593 par_pos += d->par_height_[i];
594 if (par_pos >= value)
598 if (par_pos < value) {
599 // It seems we didn't find the correct pit so stay on the safe side and
601 LYXERR0("scrolling position not found!");
602 scrollDocView(d->scrollbarParameters_.max);
606 DocIterator dit = doc_iterator_begin(&buffer_);
608 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
613 // FIXME: this method is not working well.
614 void BufferView::setCursorFromScrollbar()
616 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
618 int const height = 2 * defaultRowHeight();
619 int const first = height;
620 int const last = height_ - height;
622 Cursor const & oldcur = d->cursor_;
624 switch (cursorStatus(oldcur)) {
632 int const y = getPos(oldcur, oldcur.boundary()).y_;
633 newy = min(last, max(y, first));
637 // We reset the cursor because cursorStatus() does not
638 // work when the cursor is within mathed.
640 cur.reset(buffer_.inset());
641 tm.setCursorFromCoordinates(cur, 0, newy);
643 // update the bufferview cursor and notify insets
644 // FIXME: Care about the d->cursor_ flags to redraw if needed
645 Cursor old = d->cursor_;
647 bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
649 d->cursor_.fixIfBroken();
653 Change const BufferView::getCurrentChange() const
655 if (!d->cursor_.selection())
656 return Change(Change::UNCHANGED);
658 DocIterator dit = d->cursor_.selectionBegin();
659 return dit.paragraph().lookupChange(dit.pos());
663 // this could be used elsewhere as well?
664 // FIXME: This does not work within mathed!
665 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
667 Point const p = getPos(dit, dit.boundary());
670 if (p.y_ > workHeight())
676 void BufferView::bookmarkEditPosition()
678 // Don't eat cpu time for each keystroke
679 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
682 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
686 void BufferView::saveBookmark(unsigned int idx)
688 // tentatively save bookmark, id and pos will be used to
689 // acturately locate a bookmark in a 'live' lyx session.
690 // pit and pos will be updated with bottom level pit/pos
692 theSession().bookmarks().save(
694 d->cursor_.bottom().pit(),
695 d->cursor_.bottom().pos(),
696 d->cursor_.paragraph().id(),
701 // emit message signal.
702 message(_("Save bookmark"));
706 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
707 int top_id, pos_type top_pos)
709 bool success = false;
712 d->cursor_.clearSelection();
714 // if a valid par_id is given, try it first
715 // This is the case for a 'live' bookmark when unique paragraph ID
716 // is used to track bookmarks.
718 dit = buffer_.getParFromID(top_id);
720 dit.pos() = min(dit.paragraph().size(), top_pos);
721 // Some slices of the iterator may not be
722 // reachable (e.g. closed collapsable inset)
723 // so the dociterator may need to be
724 // shortened. Otherwise, setCursor may crash
725 // lyx when the cursor can not be set to these
727 size_t const n = dit.depth();
728 for (size_t i = 0; i < n; ++i)
729 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
737 // if top_id == 0, or searching through top_id failed
738 // This is the case for a 'restored' bookmark when only bottom
739 // (document level) pit was saved. Because of this, bookmark
740 // restoration is inaccurate. If a bookmark was within an inset,
741 // it will be restored to the left of the outmost inset that contains
743 if (bottom_pit < int(buffer_.paragraphs().size())) {
744 dit = doc_iterator_begin(&buffer_);
746 dit.pit() = bottom_pit;
747 dit.pos() = min(bottom_pos, dit.paragraph().size());
752 // Note: only bottom (document) level pit is set.
754 // set the current font.
755 d->cursor_.setCurrentFont();
756 // To center the screen on this new position we need the
757 // paragraph position which is computed at draw() time.
758 // So we need a redraw!
768 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
770 if (lyxrc.rtl_support) {
771 if (d->cursor_.real_current_font.isRightToLeft()) {
772 if (d->intl_.keymap == Intl::PRIMARY)
773 d->intl_.keyMapSec();
775 if (d->intl_.keymap == Intl::SECONDARY)
776 d->intl_.keyMapPrim();
780 d->intl_.getTransManager().translateAndInsert(c, t, cur);
784 int BufferView::workWidth() const
790 void BufferView::showCursor()
792 showCursor(d->cursor_);
796 void BufferView::showCursor(DocIterator const & dit)
798 // We are not properly started yet, delay until resizing is
803 LYXERR(Debug::SCROLLING, "recentering!");
805 CursorSlice const & bot = dit.bottom();
806 TextMetrics & tm = d->text_metrics_[bot.text()];
808 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
809 int bot_pit = bot.pit();
810 if (bot_pit > max_pit) {
811 // FIXME: Why does this happen?
812 LYXERR0("bottom pit is greater that max pit: "
813 << bot_pit << " > " << max_pit);
817 if (bot_pit == tm.first().first - 1)
818 tm.newParMetricsUp();
819 else if (bot_pit == tm.last().first + 1)
820 tm.newParMetricsDown();
822 if (tm.contains(bot_pit)) {
823 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
824 LASSERT(!pm.rows().empty(), /**/);
825 // FIXME: smooth scrolling doesn't work in mathed.
826 CursorSlice const & cs = dit.innerTextSlice();
827 int offset = coordOffset(dit, dit.boundary()).y_;
828 int ypos = pm.position() + offset;
829 Dimension const & row_dim =
830 pm.getRow(cs.pos(), dit.boundary()).dimension();
832 if (ypos - row_dim.ascent() < 0)
833 scrolled = scrollUp(- ypos + row_dim.ascent());
834 else if (ypos + row_dim.descent() > height_)
835 scrolled = scrollDown(ypos - height_ + defaultRowHeight() );
837 // else, nothing to do, the cursor is already visible so we just return.
845 // fix inline completion position
846 if (d->inlineCompletionPos_.fixIfBroken())
847 d->inlineCompletionPos_ = DocIterator();
849 tm.redoParagraph(bot_pit);
850 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
851 int offset = coordOffset(dit, dit.boundary()).y_;
853 d->anchor_pit_ = bot_pit;
854 CursorSlice const & cs = dit.innerTextSlice();
855 Dimension const & row_dim =
856 pm.getRow(cs.pos(), dit.boundary()).dimension();
858 if (d->anchor_pit_ == 0)
859 d->anchor_ypos_ = offset + pm.ascent();
860 else if (d->anchor_pit_ == max_pit)
861 d->anchor_ypos_ = height_ - offset - row_dim.descent();
862 else if (offset > height_)
863 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
865 d->anchor_ypos_ = defaultRowHeight() * 2;
872 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
876 Cursor & cur = d->cursor_;
878 switch (cmd.action) {
881 flag.setEnabled(buffer_.undo().hasUndoStack());
884 flag.setEnabled(buffer_.undo().hasRedoStack());
886 case LFUN_FILE_INSERT:
887 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
888 case LFUN_FILE_INSERT_PLAINTEXT:
889 case LFUN_BOOKMARK_SAVE:
890 // FIXME: Actually, these LFUNS should be moved to Text
891 flag.setEnabled(cur.inTexted());
893 case LFUN_FONT_STATE:
894 case LFUN_LABEL_INSERT:
895 case LFUN_INFO_INSERT:
896 case LFUN_INSET_EDIT:
897 case LFUN_PARAGRAPH_GOTO:
899 case LFUN_REFERENCE_NEXT:
901 case LFUN_WORD_FINDADV:
902 case LFUN_WORD_REPLACE:
905 case LFUN_MARK_TOGGLE:
906 case LFUN_SCREEN_RECENTER:
907 case LFUN_BIBTEX_DATABASE_ADD:
908 case LFUN_BIBTEX_DATABASE_DEL:
909 case LFUN_NOTES_MUTATE:
910 case LFUN_ALL_INSETS_TOGGLE:
911 case LFUN_STATISTICS:
912 flag.setEnabled(true);
915 // @todo Test if current WorkArea is the search WorkArea
916 case LFUN_REGEXP_MODE:
917 flag.setEnabled(! this->cursor().inRegexped());
920 case LFUN_COPY_LABEL_AS_REF: {
921 // if there is an inset at cursor, see whether it
923 Inset * inset = cur.nextInset();
924 if (!inset || !inset->getStatus(cur, cmd, flag))
925 flag.setEnabled(false);
929 case LFUN_NEXT_INSET_TOGGLE:
930 case LFUN_NEXT_INSET_MODIFY: {
931 // this is the real function we want to invoke
932 FuncRequest tmpcmd = cmd;
933 tmpcmd.action = (cmd.action == LFUN_NEXT_INSET_TOGGLE)
934 ? LFUN_INSET_TOGGLE : LFUN_INSET_MODIFY;
935 // if there is an inset at cursor, see whether it
936 // handles the lfun, other start from scratch
937 Inset * inset = cur.nextInset();
938 if (!inset || !inset->getStatus(cur, tmpcmd, flag))
939 flag = lyx::getStatus(tmpcmd);
943 case LFUN_LABEL_GOTO: {
944 flag.setEnabled(!cmd.argument().empty()
945 || getInsetByCode<InsetRef>(cur, REF_CODE));
949 case LFUN_CHANGES_TRACK:
950 flag.setEnabled(true);
951 flag.setOnOff(buffer_.params().trackChanges);
954 case LFUN_CHANGES_OUTPUT:
955 flag.setEnabled(true);
956 flag.setOnOff(buffer_.params().outputChanges);
959 case LFUN_CHANGES_MERGE:
960 case LFUN_CHANGE_NEXT:
961 case LFUN_ALL_CHANGES_ACCEPT:
962 case LFUN_ALL_CHANGES_REJECT:
963 // TODO: context-sensitive enabling of LFUNs
964 // In principle, these command should only be enabled if there
965 // is a change in the document. However, without proper
966 // optimizations, this will inevitably result in poor performance.
967 flag.setEnabled(true);
970 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
971 flag.setOnOff(buffer_.params().compressed);
976 case LFUN_SCREEN_DOWN:
978 case LFUN_SCREEN_UP_SELECT:
979 case LFUN_SCREEN_DOWN_SELECT:
980 flag.setEnabled(true);
983 case LFUN_LAYOUT_TABULAR:
984 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
988 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
991 case LFUN_LAYOUT_PARAGRAPH:
992 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
995 case LFUN_INSET_SETTINGS: {
996 InsetCode code = cur.inset().lyxCode();
997 if (cmd.getArg(0) == insetName(code)) {
998 flag.setEnabled(true);
1001 bool enable = false;
1002 InsetCode next_code = cur.nextInset()
1003 ? cur.nextInset()->lyxCode() : NO_CODE;
1004 //FIXME: remove these special cases:
1005 switch (next_code) {
1015 enable = (cmd.argument().empty() ||
1016 cmd.getArg(0) == insetName(next_code));
1021 flag.setEnabled(enable);
1025 case LFUN_DIALOG_SHOW_NEW_INSET:
1026 flag.setEnabled(cur.inset().lyxCode() != ERT_CODE &&
1027 cur.inset().lyxCode() != LISTINGS_CODE);
1028 if (cur.inset().lyxCode() == CAPTION_CODE) {
1030 if (cur.inset().getStatus(cur, cmd, flag))
1035 case LFUN_BRANCH_ACTIVATE:
1036 case LFUN_BRANCH_DEACTIVATE: {
1037 bool enable = false;
1038 docstring const branchName = cmd.argument();
1039 if (!branchName.empty())
1040 enable = buffer_.params().branchlist().find(branchName);
1041 flag.setEnabled(enable);
1046 flag.setEnabled(false);
1053 bool BufferView::dispatch(FuncRequest const & cmd)
1055 //lyxerr << [ cmd = " << cmd << "]" << endl;
1057 // Make sure that the cached BufferView is correct.
1058 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1059 << " arg[" << to_utf8(cmd.argument()) << ']'
1060 << " x[" << cmd.x << ']'
1061 << " y[" << cmd.y << ']'
1062 << " button[" << cmd.button() << ']');
1064 Cursor & cur = d->cursor_;
1066 switch (cmd.action) {
1069 cur.message(_("Undo"));
1070 cur.clearSelection();
1071 if (!cur.textUndo())
1072 cur.message(_("No further undo information"));
1074 processUpdateFlags(Update::Force | Update::FitCursor);
1078 cur.message(_("Redo"));
1079 cur.clearSelection();
1080 if (!cur.textRedo())
1081 cur.message(_("No further redo information"));
1083 processUpdateFlags(Update::Force | Update::FitCursor);
1086 case LFUN_FONT_STATE:
1087 cur.message(cur.currentState());
1090 case LFUN_BOOKMARK_SAVE:
1091 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1094 case LFUN_LABEL_GOTO: {
1095 docstring label = cmd.argument();
1096 if (label.empty()) {
1098 getInsetByCode<InsetRef>(d->cursor_, REF_CODE);
1100 label = inset->getParam("reference");
1101 // persistent=false: use temp_bookmark
1110 case LFUN_INSET_EDIT: {
1111 FuncRequest fr(cmd);
1112 // if there is an inset at cursor, see whether it
1114 Inset * inset = cur.nextInset();
1116 inset->dispatch(cur, fr);
1117 // if it did not work, try the underlying inset.
1118 if (!inset || !cur.result().dispatched())
1121 // FIXME I'm adding the last break to solve a crash,
1122 // but that is obviously not right.
1123 if (!cur.result().dispatched())
1124 // It did not work too; no action needed.
1129 case LFUN_PARAGRAPH_GOTO: {
1130 int const id = convert<int>(cmd.getArg(0));
1131 int const pos = convert<int>(cmd.getArg(1));
1133 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1134 b = theBufferList().next(b)) {
1136 DocIterator dit = b->getParFromID(id);
1138 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1142 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1143 << " found in buffer `"
1144 << b->absFileName() << "'.");
1146 if (b == &buffer_) {
1150 processUpdateFlags(Update::Force | Update::FitCursor);
1152 // Switch to other buffer view and resend cmd
1153 theLyXFunc().dispatch(FuncRequest(
1154 LFUN_BUFFER_SWITCH, b->absFileName()));
1155 theLyXFunc().dispatch(cmd);
1162 case LFUN_NOTE_NEXT:
1163 gotoInset(this, NOTE_CODE, false);
1166 case LFUN_REFERENCE_NEXT: {
1167 vector<InsetCode> tmp;
1168 tmp.push_back(LABEL_CODE);
1169 tmp.push_back(REF_CODE);
1170 gotoInset(this, tmp, true);
1174 case LFUN_CHANGES_TRACK:
1175 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1178 case LFUN_CHANGES_OUTPUT:
1179 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1180 if (buffer_.params().outputChanges) {
1181 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1182 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1183 LaTeXFeatures::isAvailable("xcolor");
1185 if (!dvipost && !xcolorulem) {
1186 Alert::warning(_("Changes not shown in LaTeX output"),
1187 _("Changes will not be highlighted in LaTeX output, "
1188 "because neither dvipost nor xcolor/ulem are installed.\n"
1189 "Please install these packages or redefine "
1190 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1191 } else if (!xcolorulem) {
1192 Alert::warning(_("Changes not shown in LaTeX output"),
1193 _("Changes will not be highlighted in LaTeX output "
1194 "when using pdflatex, because xcolor and ulem are not installed.\n"
1195 "Please install both packages or redefine "
1196 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1201 case LFUN_CHANGE_NEXT:
1202 findNextChange(this);
1203 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1204 processUpdateFlags(Update::Force | Update::FitCursor);
1207 case LFUN_CHANGES_MERGE:
1208 if (findNextChange(this)) {
1209 processUpdateFlags(Update::Force | Update::FitCursor);
1210 showDialog("changes");
1214 case LFUN_ALL_CHANGES_ACCEPT:
1215 // select complete document
1216 d->cursor_.reset(buffer_.inset());
1217 d->cursor_.selHandle(true);
1218 buffer_.text().cursorBottom(d->cursor_);
1219 // accept everything in a single step to support atomic undo
1220 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1221 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1222 processUpdateFlags(Update::Force | Update::FitCursor);
1225 case LFUN_ALL_CHANGES_REJECT:
1226 // select complete document
1227 d->cursor_.reset(buffer_.inset());
1228 d->cursor_.selHandle(true);
1229 buffer_.text().cursorBottom(d->cursor_);
1230 // reject everything in a single step to support atomic undo
1231 // Note: reject does not work recursively; the user may have to repeat the operation
1232 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1233 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1234 processUpdateFlags(Update::Force | Update::FitCursor);
1237 case LFUN_WORD_FIND: {
1238 FuncRequest req = cmd;
1239 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1240 req = d->search_request_cache_;
1241 if (req.argument().empty()) {
1242 theLyXFunc().dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1245 if (find(this, req))
1248 message(_("String not found!"));
1249 d->search_request_cache_ = req;
1253 case LFUN_WORD_REPLACE: {
1254 bool has_deleted = false;
1255 if (cur.selection()) {
1256 DocIterator beg = cur.selectionBegin();
1257 DocIterator end = cur.selectionEnd();
1258 if (beg.pit() == end.pit()) {
1259 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1260 if (cur.paragraph().isDeleted(p))
1265 replace(this, cmd, has_deleted);
1269 case LFUN_WORD_FINDADV:
1274 cur.clearSelection();
1276 cur.message(from_utf8(N_("Mark off")));
1280 cur.clearSelection();
1283 cur.message(from_utf8(N_("Mark on")));
1286 case LFUN_MARK_TOGGLE:
1287 cur.clearSelection();
1290 cur.message(from_utf8(N_("Mark removed")));
1293 cur.message(from_utf8(N_("Mark set")));
1298 case LFUN_SCREEN_RECENTER:
1302 case LFUN_BIBTEX_DATABASE_ADD: {
1303 Cursor tmpcur = d->cursor_;
1304 findInset(tmpcur, BIBTEX_CODE, false);
1305 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1308 if (inset->addDatabase(cmd.argument()))
1309 buffer_.updateBibfilesCache();
1314 case LFUN_BIBTEX_DATABASE_DEL: {
1315 Cursor tmpcur = d->cursor_;
1316 findInset(tmpcur, BIBTEX_CODE, false);
1317 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1320 if (inset->delDatabase(cmd.argument()))
1321 buffer_.updateBibfilesCache();
1326 case LFUN_STATISTICS: {
1327 DocIterator from, to;
1328 if (cur.selection()) {
1329 from = cur.selectionBegin();
1330 to = cur.selectionEnd();
1332 from = doc_iterator_begin(&buffer_);
1333 to = doc_iterator_end(&buffer_);
1335 int const words = countWords(from, to);
1336 int const chars = countChars(from, to, false);
1337 int const chars_blanks = countChars(from, to, true);
1339 if (cur.selection())
1340 message = _("Statistics for the selection:");
1342 message = _("Statistics for the document:");
1345 message += bformat(_("%1$d words"), words);
1347 message += _("One word");
1349 if (chars_blanks != 1)
1350 message += bformat(_("%1$d characters (including blanks)"),
1353 message += _("One character (including blanks)");
1356 message += bformat(_("%1$d characters (excluding blanks)"),
1359 message += _("One character (excluding blanks)");
1361 Alert::information(_("Statistics"), message);
1365 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1366 // turn compression on/off
1367 buffer_.params().compressed = !buffer_.params().compressed;
1369 case LFUN_COPY_LABEL_AS_REF: {
1370 // if there is an inset at cursor, try to copy it
1371 Inset * inset = cur.nextInset();
1373 FuncRequest tmpcmd = cmd;
1374 inset->dispatch(cur, tmpcmd);
1376 if (!cur.result().dispatched())
1377 // It did not work too; no action needed.
1379 cur.clearSelection();
1380 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1383 case LFUN_NEXT_INSET_TOGGLE: {
1384 // create the the real function we want to invoke
1385 FuncRequest tmpcmd = cmd;
1386 tmpcmd.action = LFUN_INSET_TOGGLE;
1387 // if there is an inset at cursor, see whether it
1389 Inset * inset = cur.nextInset();
1391 if (inset->isActive()) {
1392 Cursor tmpcur = cur;
1393 tmpcur.pushBackward(*inset);
1394 inset->dispatch(tmpcur, tmpcmd);
1395 if (tmpcur.result().dispatched())
1398 inset->dispatch(cur, tmpcmd);
1400 // if it did not work, try the underlying inset.
1401 if (!inset || !cur.result().dispatched())
1402 cur.dispatch(tmpcmd);
1404 if (!cur.result().dispatched())
1405 // It did not work too; no action needed.
1407 cur.clearSelection();
1408 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1412 case LFUN_NEXT_INSET_MODIFY: {
1413 // create the the real function we want to invoke
1414 FuncRequest tmpcmd = cmd;
1415 tmpcmd.action = LFUN_INSET_MODIFY;
1416 // if there is an inset at cursor, see whether it
1418 Inset * inset = cur.nextInset();
1421 inset->dispatch(cur, tmpcmd);
1423 // if it did not work, try the underlying inset.
1424 if (!inset || !cur.result().dispatched()) {
1426 cur.dispatch(tmpcmd);
1429 if (!cur.result().dispatched())
1430 // It did not work too; no action needed.
1432 cur.clearSelection();
1433 processUpdateFlags(Update::Force | Update::FitCursor);
1437 case LFUN_SCREEN_UP:
1438 case LFUN_SCREEN_DOWN: {
1439 Point p = getPos(cur, cur.boundary());
1440 if (p.y_ < 0 || p.y_ > height_) {
1441 // The cursor is off-screen so recenter before proceeding.
1443 p = getPos(cur, cur.boundary());
1445 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1446 ? - height_ : height_);
1447 if (cmd.action == LFUN_SCREEN_UP && scrolled > - height_)
1449 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1450 p = Point(width_, height_);
1451 cur.reset(buffer_.inset());
1454 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1455 //FIXME: what to do with cur.x_target()?
1464 case LFUN_SCREEN_UP_SELECT: {
1465 cur.selHandle(true);
1466 if (isTopScreen()) {
1467 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1471 int y = getPos(cur, cur.boundary()).y_;
1472 int const ymin = y - height_ + defaultRowHeight();
1473 while (y > ymin && cur.up())
1474 y = getPos(cur, cur.boundary()).y_;
1477 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1481 case LFUN_SCREEN_DOWN_SELECT: {
1482 cur.selHandle(true);
1483 if (isBottomScreen()) {
1484 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1488 int y = getPos(cur, cur.boundary()).y_;
1489 int const ymax = y + height_ - defaultRowHeight();
1490 while (y < ymax && cur.down())
1491 y = getPos(cur, cur.boundary()).y_;
1494 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1498 case LFUN_BRANCH_ACTIVATE:
1499 case LFUN_BRANCH_DEACTIVATE:
1500 buffer_.dispatch(cmd);
1501 processUpdateFlags(Update::Force);
1504 // This could be rewriten using some command like forall <insetname> <command>
1505 // once the insets refactoring is done.
1506 case LFUN_NOTES_MUTATE: {
1507 if (cmd.argument().empty())
1510 if (mutateNotes(cur, cmd.getArg(0), cmd.getArg(1))) {
1511 processUpdateFlags(Update::Force);
1516 case LFUN_ALL_INSETS_TOGGLE: {
1518 string const name = split(to_utf8(cmd.argument()), action, ' ');
1519 InsetCode const inset_code = insetCode(name);
1521 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1523 Inset & inset = cur.buffer()->inset();
1524 InsetIterator it = inset_iterator_begin(inset);
1525 InsetIterator const end = inset_iterator_end(inset);
1526 for (; it != end; ++it) {
1527 if (it->asInsetCollapsable()
1528 && (inset_code == NO_CODE
1529 || inset_code == it->lyxCode())) {
1530 Cursor tmpcur = cur;
1531 tmpcur.pushBackward(*it);
1532 it->dispatch(tmpcur, fr);
1535 processUpdateFlags(Update::Force | Update::FitCursor);
1547 docstring const BufferView::requestSelection()
1549 Cursor & cur = d->cursor_;
1551 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1552 if (!cur.selection()) {
1553 d->xsel_cache_.set = false;
1557 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1558 if (!d->xsel_cache_.set ||
1559 cur.top() != d->xsel_cache_.cursor ||
1560 cur.anchor_.top() != d->xsel_cache_.anchor)
1562 d->xsel_cache_.cursor = cur.top();
1563 d->xsel_cache_.anchor = cur.anchor_.top();
1564 d->xsel_cache_.set = cur.selection();
1565 return cur.selectionAsString(false);
1571 void BufferView::clearSelection()
1573 d->cursor_.clearSelection();
1574 // Clear the selection buffer. Otherwise a subsequent
1575 // middle-mouse-button paste would use the selection buffer,
1576 // not the more current external selection.
1577 cap::clearSelection();
1578 d->xsel_cache_.set = false;
1579 // The buffer did not really change, but this causes the
1580 // redraw we need because we cleared the selection above.
1585 void BufferView::resize(int width, int height)
1587 // Update from work area
1591 // Clear the paragraph height cache.
1592 d->par_height_.clear();
1593 // Redo the metrics.
1598 Inset const * BufferView::getCoveringInset(Text const & text,
1601 TextMetrics & tm = d->text_metrics_[&text];
1602 Inset * inset = tm.checkInsetHit(x, y);
1606 if (!inset->descendable())
1607 // No need to go further down if the inset is not
1611 size_t cell_number = inset->nargs();
1612 // Check all the inner cell.
1613 for (size_t i = 0; i != cell_number; ++i) {
1614 Text const * inner_text = inset->getText(i);
1617 Inset const * inset_deeper =
1618 getCoveringInset(*inner_text, x, y);
1620 return inset_deeper;
1628 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1630 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1632 // This is only called for mouse related events including
1633 // LFUN_FILE_OPEN generated by drag-and-drop.
1634 FuncRequest cmd = cmd0;
1636 Cursor old = cursor();
1638 cur.push(buffer_.inset());
1639 cur.setSelection(d->cursor_.selection());
1641 // Either the inset under the cursor or the
1642 // surrounding Text will handle this event.
1644 // make sure we stay within the screen...
1645 cmd.y = min(max(cmd.y, -1), height_);
1647 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1649 // Get inset under mouse, if there is one.
1650 Inset const * covering_inset =
1651 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1652 if (covering_inset == d->last_inset_)
1653 // Same inset, no need to do anything...
1656 bool need_redraw = false;
1657 // const_cast because of setMouseHover().
1658 Inset * inset = const_cast<Inset *>(covering_inset);
1660 // Remove the hint on the last hovered inset (if any).
1661 need_redraw |= d->last_inset_->setMouseHover(false);
1663 // Highlighted the newly hovered inset (if any).
1664 need_redraw |= inset->setMouseHover(true);
1665 d->last_inset_ = inset;
1669 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1670 << cmd.x << ", " << cmd.y << ")");
1672 d->update_strategy_ = DecorationUpdate;
1674 // This event (moving without mouse click) is not passed further.
1675 // This should be changed if it is further utilized.
1680 // Build temporary cursor.
1681 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1683 // Put anchor at the same position.
1686 cur.beginUndoGroup();
1688 // Try to dispatch to an non-editable inset near this position
1689 // via the temp cursor. If the inset wishes to change the real
1690 // cursor it has to do so explicitly by using
1691 // cur.bv().cursor() = cur; (or similar)
1693 inset->dispatch(cur, cmd);
1695 // Now dispatch to the temporary cursor. If the real cursor should
1696 // be modified, the inset's dispatch has to do so explicitly.
1697 if (!inset || !cur.result().dispatched())
1702 // Notify left insets
1705 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
1707 cursor().fixIfBroken();
1710 // Do we have a selection?
1711 theSelection().haveSelection(cursor().selection());
1713 // If the command has been dispatched,
1714 if (cur.result().dispatched() || cur.result().update())
1715 processUpdateFlags(cur.result().update());
1719 void BufferView::lfunScroll(FuncRequest const & cmd)
1721 string const scroll_type = cmd.getArg(0);
1722 int const scroll_step =
1723 (scroll_type == "line") ? d->scrollbarParameters_.single_step
1724 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
1725 if (scroll_step == 0)
1727 string const scroll_quantity = cmd.getArg(1);
1728 if (scroll_quantity == "up")
1729 scrollUp(scroll_step);
1730 else if (scroll_quantity == "down")
1731 scrollDown(scroll_step);
1733 int const scroll_value = convert<int>(scroll_quantity);
1735 scroll(scroll_step * scroll_value);
1742 int BufferView::scroll(int y)
1745 return scrollDown(y);
1747 return scrollUp(-y);
1752 int BufferView::scrollDown(int offset)
1754 Text * text = &buffer_.text();
1755 TextMetrics & tm = d->text_metrics_[text];
1756 int ymax = height_ + offset;
1758 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1759 int bottom_pos = last.second->position() + last.second->descent();
1760 if (last.first + 1 == int(text->paragraphs().size())) {
1761 if (bottom_pos <= height_)
1763 offset = min(offset, bottom_pos - height_);
1766 if (bottom_pos > ymax)
1768 tm.newParMetricsDown();
1770 d->anchor_ypos_ -= offset;
1775 int BufferView::scrollUp(int offset)
1777 Text * text = &buffer_.text();
1778 TextMetrics & tm = d->text_metrics_[text];
1779 int ymin = - offset;
1781 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1782 int top_pos = first.second->position() - first.second->ascent();
1783 if (first.first == 0) {
1786 offset = min(offset, - top_pos);
1791 tm.newParMetricsUp();
1793 d->anchor_ypos_ += offset;
1798 void BufferView::setCursorFromRow(int row)
1803 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1805 d->cursor_.reset(buffer_.inset());
1807 buffer_.text().setCursor(d->cursor_, 0, 0);
1809 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1813 bool BufferView::setCursorFromInset(Inset const * inset)
1815 // are we already there?
1816 if (cursor().nextInset() == inset)
1819 // Inset is not at cursor position. Find it in the document.
1821 cur.reset(buffer().inset());
1822 while (cur && cur.nextInset() != inset)
1833 void BufferView::gotoLabel(docstring const & label)
1835 std::vector<Buffer const *> bufs = buffer().allRelatives();
1836 std::vector<Buffer const *>::iterator it = bufs.begin();
1837 for (; it != bufs.end(); ++it) {
1838 Buffer const * buf = *it;
1841 Toc & toc = buf->tocBackend().toc("label");
1842 TocIterator toc_it = toc.begin();
1843 TocIterator end = toc.end();
1844 for (; toc_it != end; ++toc_it) {
1845 if (label == toc_it->str()) {
1846 dispatch(toc_it->action());
1854 TextMetrics const & BufferView::textMetrics(Text const * t) const
1856 return const_cast<BufferView *>(this)->textMetrics(t);
1860 TextMetrics & BufferView::textMetrics(Text const * t)
1862 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1863 if (tmc_it == d->text_metrics_.end()) {
1864 tmc_it = d->text_metrics_.insert(
1865 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1867 return tmc_it->second;
1871 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1874 return textMetrics(t).parMetrics(pit);
1878 int BufferView::workHeight() const
1884 void BufferView::setCursor(DocIterator const & dit)
1886 size_t const n = dit.depth();
1887 for (size_t i = 0; i < n; ++i)
1888 dit[i].inset().edit(d->cursor_, true);
1890 d->cursor_.setCursor(dit);
1891 d->cursor_.setSelection(false);
1895 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1897 // Would be wrong to delete anything if we have a selection.
1898 if (cur.selection())
1901 bool need_anchor_change = false;
1902 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1903 need_anchor_change);
1905 if (need_anchor_change)
1913 buffer_.updateLabels();
1921 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1923 LASSERT(&cur.bv() == this, /**/);
1926 // this event will clear selection so we save selection for
1927 // persistent selection
1928 cap::saveSelection(cursor());
1930 // Has the cursor just left the inset?
1931 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1933 d->cursor_.fixIfBroken();
1935 // FIXME: shift-mouse selection doesn't work well across insets.
1936 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1938 // do the dEPM magic if needed
1939 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1940 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1941 // the leftinset bool would not be necessary (badcursor instead).
1942 bool update = leftinset;
1943 if (!do_selection && d->cursor_.inTexted())
1944 update |= checkDepm(cur, d->cursor_);
1946 d->cursor_.setCursor(cur);
1947 d->cursor_.boundary(cur.boundary());
1949 d->cursor_.setSelection();
1951 d->cursor_.clearSelection();
1953 d->cursor_.finishUndo();
1954 d->cursor_.setCurrentFont();
1959 void BufferView::putSelectionAt(DocIterator const & cur,
1960 int length, bool backwards)
1962 d->cursor_.clearSelection();
1968 d->cursor_.pos() += length;
1969 d->cursor_.setSelection(d->cursor_, -length);
1971 d->cursor_.setSelection(d->cursor_, length);
1973 // Ensure a redraw happens in any case because the new selection could
1974 // possibly be on the same screen as the previous selection.
1975 processUpdateFlags(Update::Force | Update::FitCursor);
1979 Cursor & BufferView::cursor()
1985 Cursor const & BufferView::cursor() const
1991 pit_type BufferView::anchor_ref() const
1993 return d->anchor_pit_;
1997 bool BufferView::singleParUpdate()
1999 Text & buftext = buffer_.text();
2000 pit_type const bottom_pit = d->cursor_.bottom().pit();
2001 TextMetrics & tm = textMetrics(&buftext);
2002 int old_height = tm.parMetrics(bottom_pit).height();
2004 // make sure inline completion pointer is ok
2005 if (d->inlineCompletionPos_.fixIfBroken())
2006 d->inlineCompletionPos_ = DocIterator();
2008 // In Single Paragraph mode, rebreak only
2009 // the (main text, not inset!) paragraph containing the cursor.
2010 // (if this paragraph contains insets etc., rebreaking will
2011 // recursively descend)
2012 tm.redoParagraph(bottom_pit);
2013 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2014 if (pm.height() != old_height)
2015 // Paragraph height has changed so we cannot proceed to
2016 // the singlePar optimisation.
2019 d->update_strategy_ = SingleParUpdate;
2021 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2022 << " y2: " << pm.position() + pm.descent()
2023 << " pit: " << bottom_pit
2024 << " singlepar: 1");
2029 void BufferView::updateMetrics()
2031 if (height_ == 0 || width_ == 0)
2034 Text & buftext = buffer_.text();
2035 pit_type const npit = int(buftext.paragraphs().size());
2037 // Clear out the position cache in case of full screen redraw,
2038 d->coord_cache_.clear();
2040 // Clear out paragraph metrics to avoid having invalid metrics
2041 // in the cache from paragraphs not relayouted below
2042 // The complete text metrics will be redone.
2043 d->text_metrics_.clear();
2045 TextMetrics & tm = textMetrics(&buftext);
2047 // make sure inline completion pointer is ok
2048 if (d->inlineCompletionPos_.fixIfBroken())
2049 d->inlineCompletionPos_ = DocIterator();
2051 if (d->anchor_pit_ >= npit)
2052 // The anchor pit must have been deleted...
2053 d->anchor_pit_ = npit - 1;
2055 // Rebreak anchor paragraph.
2056 tm.redoParagraph(d->anchor_pit_);
2057 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2060 if (d->anchor_pit_ == 0) {
2061 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2063 // Complete buffer visible? Then it's easy.
2064 if (scrollRange == 0)
2065 d->anchor_ypos_ = anchor_pm.ascent();
2067 // FIXME: Some clever handling needed to show
2068 // the _first_ paragraph up to the top if the cursor is
2069 // in the first line.
2071 anchor_pm.setPosition(d->anchor_ypos_);
2073 LYXERR(Debug::PAINTING, "metrics: "
2074 << " anchor pit = " << d->anchor_pit_
2075 << " anchor ypos = " << d->anchor_ypos_);
2077 // Redo paragraphs above anchor if necessary.
2078 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2079 // We are now just above the anchor paragraph.
2080 pit_type pit1 = d->anchor_pit_ - 1;
2081 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2082 tm.redoParagraph(pit1);
2083 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2085 // Save the paragraph position in the cache.
2090 // Redo paragraphs below the anchor if necessary.
2091 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2092 // We are now just below the anchor paragraph.
2093 pit_type pit2 = d->anchor_pit_ + 1;
2094 for (; pit2 < npit && y2 <= height_; ++pit2) {
2095 tm.redoParagraph(pit2);
2096 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2098 // Save the paragraph position in the cache.
2103 LYXERR(Debug::PAINTING, "Metrics: "
2104 << " anchor pit = " << d->anchor_pit_
2105 << " anchor ypos = " << d->anchor_ypos_
2108 << " pit1 = " << pit1
2109 << " pit2 = " << pit2);
2111 d->update_strategy_ = FullScreenUpdate;
2113 if (lyxerr.debugging(Debug::WORKAREA)) {
2114 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2115 d->coord_cache_.dump();
2120 void BufferView::insertLyXFile(FileName const & fname)
2122 LASSERT(d->cursor_.inTexted(), /**/);
2124 // Get absolute path of file and add ".lyx"
2125 // to the filename if necessary
2126 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2128 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2129 // emit message signal.
2130 message(bformat(_("Inserting document %1$s..."), disp_fn));
2133 Buffer buf("", false);
2134 if (buf.loadLyXFile(filename)) {
2135 ErrorList & el = buffer_.errorList("Parse");
2136 // Copy the inserted document error list into the current buffer one.
2137 el = buf.errorList("Parse");
2138 buffer_.undo().recordUndo(d->cursor_);
2139 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2140 buf.params().documentClassPtr(), el);
2141 res = _("Document %1$s inserted.");
2143 res = _("Could not insert document %1$s");
2148 // emit message signal.
2149 message(bformat(res, disp_fn));
2150 buffer_.errors("Parse");
2154 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2160 // Addup contribution of nested insets, from inside to outside,
2161 // keeping the outer paragraph for a special handling below
2162 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2163 CursorSlice const & sl = dit[i];
2167 // get relative position inside sl.inset()
2168 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2170 // Make relative position inside of the edited inset relative to sl.inset()
2174 // In case of an RTL inset, the edited inset will be positioned to the left
2177 bool boundary_i = boundary && i + 1 == dit.depth();
2178 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2183 // remember width for the case that sl.inset() is positioned in an RTL inset
2184 if (i && dit[i - 1].text()) {
2185 // If this Inset is inside a Text Inset, retrieve the Dimension
2186 // from the containing text instead of using Inset::dimension() which
2187 // might not be implemented.
2188 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2189 // elimination of Inset::dim_ cache. This coordOffset() method needs
2190 // to be rewritten in light of the new design.
2191 Dimension const & dim = parMetrics(dit[i - 1].text(),
2192 dit[i - 1].pit()).insetDimension(&sl.inset());
2195 Dimension const dim = sl.inset().dimension(*this);
2199 //lyxerr << "Cursor::getPos, i: "
2200 // << i << " x: " << xx << " y: " << y << endl;
2203 // Add contribution of initial rows of outermost paragraph
2204 CursorSlice const & sl = dit[0];
2205 TextMetrics const & tm = textMetrics(sl.text());
2206 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2207 LASSERT(!pm.rows().empty(), /**/);
2208 y -= pm.rows()[0].ascent();
2210 // FIXME: document this mess
2212 if (sl.pos() > 0 && dit.depth() == 1) {
2214 if (pos && boundary)
2216 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2217 rend = pm.pos2row(pos);
2219 rend = pm.pos2row(sl.pos());
2221 size_t rend = pm.pos2row(sl.pos());
2223 for (size_t rit = 0; rit != rend; ++rit)
2224 y += pm.rows()[rit].height();
2225 y += pm.rows()[rend].ascent();
2227 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2229 // Make relative position from the nested inset now bufferview absolute.
2230 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2233 // In the RTL case place the nested inset at the left of the cursor in
2234 // the outer paragraph
2235 bool boundary_1 = boundary && 1 == dit.depth();
2236 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2244 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2246 if (!paragraphVisible(dit))
2247 return Point(-1, -1);
2249 CursorSlice const & bot = dit.bottom();
2250 TextMetrics const & tm = textMetrics(bot.text());
2252 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2253 p.y_ += tm.parMetrics(bot.pit()).position();
2258 bool BufferView::paragraphVisible(DocIterator const & dit) const
2260 CursorSlice const & bot = dit.bottom();
2261 TextMetrics const & tm = textMetrics(bot.text());
2263 return tm.contains(bot.pit());
2267 void BufferView::draw(frontend::Painter & pain)
2269 if (height_ == 0 || width_ == 0)
2271 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2273 Text & text = buffer_.text();
2274 TextMetrics const & tm = d->text_metrics_[&text];
2275 int const y = tm.first().second->position();
2276 PainterInfo pi(this, pain);
2278 switch (d->update_strategy_) {
2280 case NoScreenUpdate:
2281 // If no screen painting is actually needed, only some the different
2282 // coordinates of insets and paragraphs needs to be updated.
2283 pi.full_repaint = true;
2284 pi.pain.setDrawingEnabled(false);
2288 case SingleParUpdate:
2289 pi.full_repaint = false;
2290 // In general, only the current row of the outermost paragraph
2291 // will be redrawn. Particular cases where selection spans
2292 // multiple paragraph are correctly detected in TextMetrics.
2296 case DecorationUpdate:
2297 // FIXME: We should also distinguish DecorationUpdate to avoid text
2298 // drawing if possible. This is not possible to do easily right now
2299 // because of the single backing pixmap.
2301 case FullScreenUpdate:
2302 // The whole screen, including insets, will be refreshed.
2303 pi.full_repaint = true;
2305 // Clear background.
2306 pain.fillRectangle(0, 0, width_, height_,
2307 pi.backgroundColor(&buffer_.inset()));
2312 // and possibly grey out below
2313 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2314 int const y2 = lastpm.second->position() + lastpm.second->descent();
2316 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2319 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2321 // The scrollbar needs an update.
2324 // Normalize anchor for next time
2325 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2326 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2327 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2328 ParagraphMetrics const & pm = tm.parMetrics(pit);
2329 if (pm.position() + pm.descent() > 0) {
2330 d->anchor_pit_ = pit;
2331 d->anchor_ypos_ = pm.position();
2335 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2336 << " anchor ypos = " << d->anchor_ypos_);
2340 void BufferView::message(docstring const & msg)
2343 d->gui_->message(msg);
2347 void BufferView::showDialog(string const & name)
2350 d->gui_->showDialog(name, string());
2354 void BufferView::showDialog(string const & name,
2355 string const & data, Inset * inset)
2358 d->gui_->showDialog(name, data, inset);
2362 void BufferView::updateDialog(string const & name, string const & data)
2365 d->gui_->updateDialog(name, data);
2369 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2375 // FIXME: Move this out of BufferView again
2376 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2378 if (!fname.isReadableFile()) {
2379 docstring const error = from_ascii(strerror(errno));
2380 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2381 docstring const text =
2382 bformat(_("Could not read the specified document\n"
2383 "%1$s\ndue to the error: %2$s"), file, error);
2384 Alert::error(_("Could not read file"), text);
2388 if (!fname.isReadableFile()) {
2389 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2390 docstring const text =
2391 bformat(_("%1$s\n is not readable."), file);
2392 Alert::error(_("Could not open file"), text);
2396 // FIXME UNICODE: We don't know the encoding of the file
2397 docstring file_content = fname.fileContents("UTF-8");
2398 if (file_content.empty()) {
2399 Alert::error(_("Reading not UTF-8 encoded file"),
2400 _("The file is not UTF-8 encoded.\n"
2401 "It will be read as local 8Bit-encoded.\n"
2402 "If this does not give the correct result\n"
2403 "then please change the encoding of the file\n"
2404 "to UTF-8 with a program other than LyX.\n"));
2405 file_content = fname.fileContents("local8bit");
2408 return normalize_c(file_content);
2412 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2414 docstring const tmpstr = contentsOfPlaintextFile(f);
2419 Cursor & cur = cursor();
2420 cap::replaceSelection(cur);
2421 buffer_.undo().recordUndo(cur);
2423 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2425 cur.innerText()->insertStringAsLines(cur, tmpstr);
2432 docstring const & BufferView::inlineCompletion() const
2434 return d->inlineCompletion_;
2438 size_t const & BufferView::inlineCompletionUniqueChars() const
2440 return d->inlineCompletionUniqueChars_;
2444 DocIterator const & BufferView::inlineCompletionPos() const
2446 return d->inlineCompletionPos_;
2450 bool samePar(DocIterator const & a, DocIterator const & b)
2452 if (a.empty() && b.empty())
2454 if (a.empty() || b.empty())
2456 if (a.depth() != b.depth())
2458 return &a.innerParagraph() == &b.innerParagraph();
2462 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2463 docstring const & completion, size_t uniqueChars)
2465 uniqueChars = min(completion.size(), uniqueChars);
2466 bool changed = d->inlineCompletion_ != completion
2467 || d->inlineCompletionUniqueChars_ != uniqueChars;
2468 bool singlePar = true;
2469 d->inlineCompletion_ = completion;
2470 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2472 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2475 DocIterator const & old = d->inlineCompletionPos_;
2477 //lyxerr << "inlineCompletionPos changed" << std::endl;
2478 // old or pos are in another paragraph?
2479 if ((!samePar(cur, pos) && !pos.empty())
2480 || (!samePar(cur, old) && !old.empty())) {
2482 //lyxerr << "different paragraph" << std::endl;
2484 d->inlineCompletionPos_ = pos;
2489 if (singlePar && !(cur.disp_.update() & Update::Force))
2490 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2492 cur.updateFlags(cur.disp_.update() | Update::Force);