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 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
154 if (!findNextInset(tmpdit, codes, contents))
165 /// Looks for next inset with the given code
166 void findInset(DocIterator & dit, InsetCode code, bool same_content)
168 findInset(dit, vector<InsetCode>(1, code), same_content);
172 /// Moves cursor to the next inset with one of the given codes.
173 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
176 Cursor tmpcur = bv->cursor();
177 if (!findInset(tmpcur, codes, same_content)) {
178 bv->cursor().message(_("No more insets"));
182 tmpcur.clearSelection();
183 bv->setCursor(tmpcur);
188 /// Moves cursor to the next inset with given code.
189 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
191 gotoInset(bv, vector<InsetCode>(1, code), same_content);
195 /// A map from a Text to the associated text metrics
196 typedef map<Text const *, TextMetrics> TextMetricsCache;
198 enum ScreenUpdateStrategy {
208 /////////////////////////////////////////////////////////////////////
212 /////////////////////////////////////////////////////////////////////
214 struct BufferView::Private
216 Private(BufferView & bv): wh_(0), cursor_(bv),
217 anchor_pit_(0), anchor_ypos_(0),
218 inlineCompletionUniqueChars_(0),
219 last_inset_(0), gui_(0)
223 ScrollbarParameters scrollbarParameters_;
225 ScreenUpdateStrategy update_strategy_;
227 CoordCache coord_cache_;
229 /// Estimated average par height for scrollbar.
231 /// this is used to handle XSelection events in the right manner.
240 pit_type anchor_pit_;
244 vector<int> par_height_;
247 DocIterator inlineCompletionPos_;
249 docstring inlineCompletion_;
251 size_t inlineCompletionUniqueChars_;
253 /// keyboard mapping object.
256 /// last visited inset.
257 /** kept to send setMouseHover(false).
258 * Not owned, so don't delete.
262 mutable TextMetricsCache text_metrics_;
265 /** Not owned, so don't delete.
267 frontend::GuiBufferViewDelegate * gui_;
269 /// Cache for Find Next
270 FuncRequest search_request_cache_;
274 BufferView::BufferView(Buffer & buf)
275 : width_(0), height_(0), full_screen_(false), buffer_(buf), d(new Private(*this))
277 d->xsel_cache_.set = false;
278 d->intl_.initKeyMapper(lyxrc.use_kbmap);
280 d->cursor_.push(buffer_.inset());
281 d->cursor_.resetAnchor();
282 d->cursor_.setCurrentFont();
284 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
285 thePreviews().generateBufferPreviews(buffer_);
289 BufferView::~BufferView()
291 // current buffer is going to be switched-off, save cursor pos
292 // Ideally, the whole cursor stack should be saved, but session
293 // currently can only handle bottom (whole document) level pit and pos.
294 // That is to say, if a cursor is in a nested inset, it will be
295 // restore to the left of the top level inset.
296 LastFilePosSection::FilePos fp;
297 fp.pit = d->cursor_.bottom().pit();
298 fp.pos = d->cursor_.bottom().pos();
299 theSession().lastFilePos().save(buffer_.fileName(), fp);
305 int BufferView::rightMargin() const
307 // The additional test for the case the outliner is opened.
309 !lyxrc.full_screen_limit ||
310 width_ < lyxrc.full_screen_width + 20)
313 return (width_ - lyxrc.full_screen_width) / 2;
317 int BufferView::leftMargin() const
319 return rightMargin();
323 bool BufferView::isTopScreen() const
325 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
329 bool BufferView::isBottomScreen() const
331 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
335 Intl & BufferView::getIntl()
341 Intl const & BufferView::getIntl() const
347 CoordCache & BufferView::coordCache()
349 return d->coord_cache_;
353 CoordCache const & BufferView::coordCache() const
355 return d->coord_cache_;
359 Buffer & BufferView::buffer()
365 Buffer const & BufferView::buffer() const
371 bool BufferView::fitCursor()
373 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
374 frontend::FontMetrics const & fm =
375 theFontMetrics(d->cursor_.getFont().fontInfo());
376 int const asc = fm.maxAscent();
377 int const des = fm.maxDescent();
378 Point const p = getPos(d->cursor_, d->cursor_.boundary());
379 if (p.y_ - asc >= 0 && p.y_ + des < height_)
386 void BufferView::processUpdateFlags(Update::flags flags)
388 // last_inset_ points to the last visited inset. This pointer may become
389 // invalid because of keyboard editing. Since all such operations
390 // causes screen update(), I reset last_inset_ to avoid such a problem.
392 // This is close to a hot-path.
393 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
394 << "[fitcursor = " << (flags & Update::FitCursor)
395 << ", forceupdate = " << (flags & Update::Force)
396 << ", singlepar = " << (flags & Update::SinglePar)
397 << "] buffer: " << &buffer_);
399 buffer_.updateMacros();
401 // Now do the first drawing step if needed. This consists on updating
402 // the CoordCache in updateMetrics().
403 // The second drawing step is done in WorkArea::redraw() if needed.
405 // Case when no explicit update is requested.
407 // no need to redraw anything.
408 d->update_strategy_ = NoScreenUpdate;
412 if (flags == Update::Decoration) {
413 d->update_strategy_ = DecorationUpdate;
418 if (flags == Update::FitCursor
419 || flags == (Update::Decoration | Update::FitCursor)) {
420 // tell the frontend to update the screen if needed.
425 if (flags & Update::Decoration) {
426 d->update_strategy_ = DecorationUpdate;
430 // no screen update is needed.
431 d->update_strategy_ = NoScreenUpdate;
435 bool const full_metrics = flags & Update::Force || !singleParUpdate();
438 // We have to update the full screen metrics.
441 if (!(flags & Update::FitCursor)) {
442 // Nothing to do anymore. Trigger a redraw and return
447 // updateMetrics() does not update paragraph position
448 // This is done at draw() time. So we need a redraw!
452 // The cursor is off screen so ensure it is visible.
459 void BufferView::updateScrollbar()
461 if (height_ == 0 && width_ == 0)
464 // We prefer fixed size line scrolling.
465 d->scrollbarParameters_.single_step = defaultRowHeight();
466 // We prefer full screen page scrolling.
467 d->scrollbarParameters_.page_step = height_;
469 Text & t = buffer_.text();
470 TextMetrics & tm = d->text_metrics_[&t];
472 LYXERR(Debug::GUI, " Updating scrollbar: height: "
473 << t.paragraphs().size()
474 << " curr par: " << d->cursor_.bottom().pit()
475 << " default height " << defaultRowHeight());
477 size_t const parsize = t.paragraphs().size();
478 if (d->par_height_.size() != parsize) {
479 d->par_height_.clear();
480 // FIXME: We assume a default paragraph height of 2 rows. This
481 // should probably be pondered with the screen width.
482 d->par_height_.resize(parsize, defaultRowHeight() * 2);
485 // Look at paragraph heights on-screen
486 pair<pit_type, ParagraphMetrics const *> first = tm.first();
487 pair<pit_type, ParagraphMetrics const *> last = tm.last();
488 for (pit_type pit = first.first; pit <= last.first; ++pit) {
489 d->par_height_[pit] = tm.parMetrics(pit).height();
490 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
491 << d->par_height_[pit]);
494 int top_pos = first.second->position() - first.second->ascent();
495 int bottom_pos = last.second->position() + last.second->descent();
496 bool first_visible = first.first == 0 && top_pos >= 0;
497 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
498 if (first_visible && last_visible) {
499 d->scrollbarParameters_.min = 0;
500 d->scrollbarParameters_.max = 0;
504 d->scrollbarParameters_.min = top_pos;
505 for (size_t i = 0; i != size_t(first.first); ++i)
506 d->scrollbarParameters_.min -= d->par_height_[i];
507 d->scrollbarParameters_.max = bottom_pos;
508 for (size_t i = last.first + 1; i != parsize; ++i)
509 d->scrollbarParameters_.max += d->par_height_[i];
511 d->scrollbarParameters_.position = 0;
512 // The reference is the top position so we remove one page.
513 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
517 ScrollbarParameters const & BufferView::scrollbarParameters() const
519 return d->scrollbarParameters_;
523 docstring BufferView::toolTip(int x, int y) const
525 // Get inset under mouse, if there is one.
526 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
528 // No inset, no tooltip...
530 return covering_inset->toolTip(*this, x, y);
534 docstring BufferView::contextMenu(int x, int y) const
536 //If there is a selection, return the containing inset menu
537 if (d->cursor_.selection())
538 return d->cursor_.inset().contextMenu(*this, x, y);
540 // Get inset under mouse, if there is one.
541 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
543 return covering_inset->contextMenu(*this, x, y);
545 return buffer_.inset().contextMenu(*this, x, y);
549 void BufferView::scrollDocView(int value)
551 int const offset = value - d->scrollbarParameters_.position;
553 // No scrolling at all? No need to redraw anything
557 // If the offset is less than 2 screen height, prefer to scroll instead.
558 if (abs(offset) <= 2 * height_) {
559 d->anchor_ypos_ -= offset;
565 // cut off at the top
566 if (value <= d->scrollbarParameters_.min) {
567 DocIterator dit = doc_iterator_begin(buffer_.inset());
569 LYXERR(Debug::SCROLLING, "scroll to top");
573 // cut off at the bottom
574 if (value >= d->scrollbarParameters_.max) {
575 DocIterator dit = doc_iterator_end(buffer_.inset());
578 LYXERR(Debug::SCROLLING, "scroll to bottom");
582 // find paragraph at target position
583 int par_pos = d->scrollbarParameters_.min;
585 for (; i != int(d->par_height_.size()); ++i) {
586 par_pos += d->par_height_[i];
587 if (par_pos >= value)
591 if (par_pos < value) {
592 // It seems we didn't find the correct pit so stay on the safe side and
594 LYXERR0("scrolling position not found!");
595 scrollDocView(d->scrollbarParameters_.max);
599 DocIterator dit = doc_iterator_begin(buffer_.inset());
601 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
606 // FIXME: this method is not working well.
607 void BufferView::setCursorFromScrollbar()
609 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
611 int const height = 2 * defaultRowHeight();
612 int const first = height;
613 int const last = height_ - height;
615 Cursor const & oldcur = d->cursor_;
617 switch (cursorStatus(oldcur)) {
625 int const y = getPos(oldcur, oldcur.boundary()).y_;
626 newy = min(last, max(y, first));
630 // We reset the cursor because cursorStatus() does not
631 // work when the cursor is within mathed.
633 cur.reset(buffer_.inset());
634 tm.setCursorFromCoordinates(cur, 0, newy);
636 // update the bufferview cursor and notify insets
637 // FIXME: Care about the d->cursor_ flags to redraw if needed
638 Cursor old = d->cursor_;
640 bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
642 d->cursor_.fixIfBroken();
646 Change const BufferView::getCurrentChange() const
648 if (!d->cursor_.selection())
649 return Change(Change::UNCHANGED);
651 DocIterator dit = d->cursor_.selectionBegin();
652 return dit.paragraph().lookupChange(dit.pos());
656 // this could be used elsewhere as well?
657 // FIXME: This does not work within mathed!
658 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
660 Point const p = getPos(dit, dit.boundary());
663 if (p.y_ > workHeight())
669 void BufferView::saveBookmark(unsigned int idx)
671 // tenatively save bookmark, id and pos will be used to
672 // acturately locate a bookmark in a 'live' lyx session.
673 // pit and pos will be updated with bottom level pit/pos
675 theSession().bookmarks().save(
677 d->cursor_.bottom().pit(),
678 d->cursor_.bottom().pos(),
679 d->cursor_.paragraph().id(),
684 // emit message signal.
685 message(_("Save bookmark"));
689 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
690 int top_id, pos_type top_pos)
692 bool success = false;
695 d->cursor_.clearSelection();
697 // if a valid par_id is given, try it first
698 // This is the case for a 'live' bookmark when unique paragraph ID
699 // is used to track bookmarks.
701 dit = buffer_.getParFromID(top_id);
703 dit.pos() = min(dit.paragraph().size(), top_pos);
704 // Some slices of the iterator may not be
705 // reachable (e.g. closed collapsable inset)
706 // so the dociterator may need to be
707 // shortened. Otherwise, setCursor may crash
708 // lyx when the cursor can not be set to these
710 size_t const n = dit.depth();
711 for (size_t i = 0; i < n; ++i)
712 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
720 // if top_id == 0, or searching through top_id failed
721 // This is the case for a 'restored' bookmark when only bottom
722 // (document level) pit was saved. Because of this, bookmark
723 // restoration is inaccurate. If a bookmark was within an inset,
724 // it will be restored to the left of the outmost inset that contains
726 if (bottom_pit < int(buffer_.paragraphs().size())) {
727 dit = doc_iterator_begin(buffer_.inset());
729 dit.pit() = bottom_pit;
730 dit.pos() = min(bottom_pos, dit.paragraph().size());
735 // Note: only bottom (document) level pit is set.
737 // set the current font.
738 d->cursor_.setCurrentFont();
739 // To center the screen on this new position we need the
740 // paragraph position which is computed at draw() time.
741 // So we need a redraw!
751 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
753 if (lyxrc.rtl_support) {
754 if (d->cursor_.real_current_font.isRightToLeft()) {
755 if (d->intl_.keymap == Intl::PRIMARY)
756 d->intl_.keyMapSec();
758 if (d->intl_.keymap == Intl::SECONDARY)
759 d->intl_.keyMapPrim();
763 d->intl_.getTransManager().translateAndInsert(c, t, cur);
767 int BufferView::workWidth() const
773 void BufferView::showCursor()
775 showCursor(d->cursor_);
779 void BufferView::showCursor(DocIterator const & dit)
781 // We are not properly started yet, delay until resizing is
786 LYXERR(Debug::SCROLLING, "recentering!");
788 CursorSlice const & bot = dit.bottom();
789 TextMetrics & tm = d->text_metrics_[bot.text()];
791 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
792 int bot_pit = bot.pit();
793 if (bot_pit > max_pit) {
794 // FIXME: Why does this happen?
795 LYXERR0("bottom pit is greater that max pit: "
796 << bot_pit << " > " << max_pit);
800 if (bot_pit == tm.first().first - 1)
801 tm.newParMetricsUp();
802 else if (bot_pit == tm.last().first + 1)
803 tm.newParMetricsDown();
805 if (tm.contains(bot_pit)) {
806 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
807 LASSERT(!pm.rows().empty(), /**/);
808 // FIXME: smooth scrolling doesn't work in mathed.
809 CursorSlice const & cs = dit.innerTextSlice();
810 int offset = coordOffset(dit, dit.boundary()).y_;
811 int ypos = pm.position() + offset;
812 Dimension const & row_dim =
813 pm.getRow(cs.pos(), dit.boundary()).dimension();
815 if (ypos - row_dim.ascent() < 0)
816 scrolled = scrollUp(- ypos + row_dim.ascent());
817 else if (ypos + row_dim.descent() > height_)
818 scrolled = scrollDown(ypos - height_ + row_dim.descent());
819 // else, nothing to do, the cursor is already visible so we just return.
827 // fix inline completion position
828 if (d->inlineCompletionPos_.fixIfBroken())
829 d->inlineCompletionPos_ = DocIterator();
831 tm.redoParagraph(bot_pit);
832 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
833 int offset = coordOffset(dit, dit.boundary()).y_;
835 d->anchor_pit_ = bot_pit;
836 CursorSlice const & cs = dit.innerTextSlice();
837 Dimension const & row_dim =
838 pm.getRow(cs.pos(), dit.boundary()).dimension();
840 if (d->anchor_pit_ == 0)
841 d->anchor_ypos_ = offset + pm.ascent();
842 else if (d->anchor_pit_ == max_pit)
843 d->anchor_ypos_ = height_ - offset - row_dim.descent();
845 d->anchor_ypos_ = defaultRowHeight() * 2 - offset - row_dim.descent();
852 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
856 Cursor & cur = d->cursor_;
858 switch (cmd.action) {
861 flag.setEnabled(buffer_.undo().hasUndoStack());
864 flag.setEnabled(buffer_.undo().hasRedoStack());
866 case LFUN_FILE_INSERT:
867 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
868 case LFUN_FILE_INSERT_PLAINTEXT:
869 case LFUN_BOOKMARK_SAVE:
870 // FIXME: Actually, these LFUNS should be moved to Text
871 flag.setEnabled(cur.inTexted());
873 case LFUN_FONT_STATE:
874 case LFUN_LABEL_INSERT:
875 case LFUN_INFO_INSERT:
876 case LFUN_INSET_EDIT:
877 case LFUN_PARAGRAPH_GOTO:
879 case LFUN_REFERENCE_NEXT:
881 case LFUN_WORD_FINDADV:
882 case LFUN_WORD_REPLACE:
885 case LFUN_MARK_TOGGLE:
886 case LFUN_SCREEN_RECENTER:
887 case LFUN_BIBTEX_DATABASE_ADD:
888 case LFUN_BIBTEX_DATABASE_DEL:
889 case LFUN_NOTES_MUTATE:
890 case LFUN_ALL_INSETS_TOGGLE:
891 case LFUN_STATISTICS:
892 flag.setEnabled(true);
895 // @todo Test if current WorkArea is the search WorkArea
896 case LFUN_REGEXP_MODE:
897 flag.setEnabled(! this->cursor().inRegexped());
900 case LFUN_COPY_LABEL_AS_REF:
901 // if there is an inset at cursor, see whether it
902 // handles the lfun, other start from scratch
903 Inset * inset = cur.nextInset();
904 if (!inset || !inset->getStatus(cur, cmd, flag))
905 flag = lyx::getStatus(cmd);
908 case LFUN_NEXT_INSET_TOGGLE:
909 case LFUN_NEXT_INSET_MODIFY: {
910 // this is the real function we want to invoke
911 FuncRequest tmpcmd = cmd;
912 tmpcmd.action = (cmd.action == LFUN_NEXT_INSET_TOGGLE)
913 ? LFUN_INSET_TOGGLE : LFUN_INSET_MODIFY;
914 // if there is an inset at cursor, see whether it
915 // handles the lfun, other start from scratch
916 Inset * inset = cur.nextInset();
917 if (!inset || !inset->getStatus(cur, tmpcmd, flag))
918 flag = lyx::getStatus(tmpcmd);
922 case LFUN_LABEL_GOTO: {
923 flag.setEnabled(!cmd.argument().empty()
924 || getInsetByCode<InsetRef>(cur, REF_CODE));
928 case LFUN_CHANGES_TRACK:
929 flag.setEnabled(true);
930 flag.setOnOff(buffer_.params().trackChanges);
933 case LFUN_CHANGES_OUTPUT:
934 flag.setEnabled(true);
935 flag.setOnOff(buffer_.params().outputChanges);
938 case LFUN_CHANGES_MERGE:
939 case LFUN_CHANGE_NEXT:
940 case LFUN_ALL_CHANGES_ACCEPT:
941 case LFUN_ALL_CHANGES_REJECT:
942 // TODO: context-sensitive enabling of LFUNs
943 // In principle, these command should only be enabled if there
944 // is a change in the document. However, without proper
945 // optimizations, this will inevitably result in poor performance.
946 flag.setEnabled(true);
949 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
950 flag.setOnOff(buffer_.params().compressed);
955 case LFUN_SCREEN_DOWN:
957 case LFUN_SCREEN_UP_SELECT:
958 case LFUN_SCREEN_DOWN_SELECT:
959 flag.setEnabled(true);
962 case LFUN_LAYOUT_TABULAR:
963 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
967 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
970 case LFUN_LAYOUT_PARAGRAPH:
971 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
974 case LFUN_INSET_SETTINGS: {
975 InsetCode code = cur.inset().lyxCode();
976 if (cmd.getArg(0) == insetName(code)) {
977 flag.setEnabled(true);
981 InsetCode next_code = cur.nextInset()
982 ? cur.nextInset()->lyxCode() : NO_CODE;
983 //FIXME: remove these special cases:
993 enable = (cmd.argument().empty() ||
994 cmd.getArg(0) == insetName(next_code));
999 flag.setEnabled(enable);
1003 case LFUN_DIALOG_SHOW_NEW_INSET:
1004 flag.setEnabled(cur.inset().lyxCode() != ERT_CODE &&
1005 cur.inset().lyxCode() != LISTINGS_CODE);
1006 if (cur.inset().lyxCode() == CAPTION_CODE) {
1008 if (cur.inset().getStatus(cur, cmd, flag))
1013 case LFUN_BRANCH_ACTIVATE:
1014 case LFUN_BRANCH_DEACTIVATE: {
1015 bool enable = false;
1016 docstring const branchName = cmd.argument();
1017 if (!branchName.empty())
1018 enable = buffer_.params().branchlist().find(branchName);
1019 flag.setEnabled(enable);
1024 flag.setEnabled(false);
1031 bool BufferView::dispatch(FuncRequest const & cmd)
1033 //lyxerr << [ cmd = " << cmd << "]" << endl;
1035 // Make sure that the cached BufferView is correct.
1036 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1037 << " arg[" << to_utf8(cmd.argument()) << ']'
1038 << " x[" << cmd.x << ']'
1039 << " y[" << cmd.y << ']'
1040 << " button[" << cmd.button() << ']');
1042 Cursor & cur = d->cursor_;
1044 switch (cmd.action) {
1047 cur.message(_("Undo"));
1048 cur.clearSelection();
1049 if (!cur.textUndo())
1050 cur.message(_("No further undo information"));
1052 processUpdateFlags(Update::Force | Update::FitCursor);
1056 cur.message(_("Redo"));
1057 cur.clearSelection();
1058 if (!cur.textRedo())
1059 cur.message(_("No further redo information"));
1061 processUpdateFlags(Update::Force | Update::FitCursor);
1064 case LFUN_FONT_STATE:
1065 cur.message(cur.currentState());
1068 case LFUN_BOOKMARK_SAVE:
1069 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1072 case LFUN_LABEL_GOTO: {
1073 docstring label = cmd.argument();
1074 if (label.empty()) {
1076 getInsetByCode<InsetRef>(d->cursor_,
1079 label = inset->getParam("reference");
1080 // persistent=false: use temp_bookmark
1090 case LFUN_INSET_EDIT: {
1091 FuncRequest fr(cmd);
1092 // if there is an inset at cursor, see whether it
1094 Inset * inset = cur.nextInset();
1096 inset->dispatch(cur, fr);
1097 // if it did not work, try the underlying inset.
1098 if (!inset || !cur.result().dispatched())
1101 // FIXME I'm adding the last break to solve a crash,
1102 // but that is obviously not right.
1103 if (!cur.result().dispatched())
1104 // It did not work too; no action needed.
1109 case LFUN_PARAGRAPH_GOTO: {
1110 int const id = convert<int>(cmd.getArg(0));
1111 int const pos = convert<int>(cmd.getArg(1));
1113 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1114 b = theBufferList().next(b)) {
1116 DocIterator dit = b->getParFromID(id);
1118 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1122 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1123 << " found in buffer `"
1124 << b->absFileName() << "'.");
1126 if (b == &buffer_) {
1130 processUpdateFlags(Update::Force | Update::FitCursor);
1132 // Switch to other buffer view and resend cmd
1133 theLyXFunc().dispatch(FuncRequest(
1134 LFUN_BUFFER_SWITCH, b->absFileName()));
1135 theLyXFunc().dispatch(cmd);
1142 case LFUN_NOTE_NEXT:
1143 gotoInset(this, NOTE_CODE, false);
1146 case LFUN_REFERENCE_NEXT: {
1147 vector<InsetCode> tmp;
1148 tmp.push_back(LABEL_CODE);
1149 tmp.push_back(REF_CODE);
1150 gotoInset(this, tmp, true);
1154 case LFUN_CHANGES_TRACK:
1155 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1158 case LFUN_CHANGES_OUTPUT:
1159 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1160 if (buffer_.params().outputChanges) {
1161 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1162 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1163 LaTeXFeatures::isAvailable("xcolor");
1165 if (!dvipost && !xcolorsoul) {
1166 Alert::warning(_("Changes not shown in LaTeX output"),
1167 _("Changes will not be highlighted in LaTeX output, "
1168 "because neither dvipost nor xcolor/soul are installed.\n"
1169 "Please install these packages or redefine "
1170 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1171 } else if (!xcolorsoul) {
1172 Alert::warning(_("Changes not shown in LaTeX output"),
1173 _("Changes will not be highlighted in LaTeX output "
1174 "when using pdflatex, because xcolor and soul are not installed.\n"
1175 "Please install both packages or redefine "
1176 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1181 case LFUN_CHANGE_NEXT:
1182 findNextChange(this);
1183 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1184 processUpdateFlags(Update::Force | Update::FitCursor);
1187 case LFUN_CHANGES_MERGE:
1188 if (findNextChange(this)) {
1189 processUpdateFlags(Update::Force | Update::FitCursor);
1190 showDialog("changes");
1194 case LFUN_ALL_CHANGES_ACCEPT:
1195 // select complete document
1196 d->cursor_.reset(buffer_.inset());
1197 d->cursor_.selHandle(true);
1198 buffer_.text().cursorBottom(d->cursor_);
1199 // accept everything in a single step to support atomic undo
1200 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1201 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1202 processUpdateFlags(Update::Force | Update::FitCursor);
1205 case LFUN_ALL_CHANGES_REJECT:
1206 // select complete document
1207 d->cursor_.reset(buffer_.inset());
1208 d->cursor_.selHandle(true);
1209 buffer_.text().cursorBottom(d->cursor_);
1210 // reject everything in a single step to support atomic undo
1211 // Note: reject does not work recursively; the user may have to repeat the operation
1212 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1213 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1214 processUpdateFlags(Update::Force | Update::FitCursor);
1217 case LFUN_WORD_FIND: {
1218 FuncRequest req = cmd;
1219 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1220 req = d->search_request_cache_;
1221 if (req.argument().empty()) {
1222 theLyXFunc().dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1225 if (find(this, req))
1228 message(_("String not found!"));
1229 d->search_request_cache_ = req;
1233 case LFUN_WORD_REPLACE: {
1234 bool has_deleted = false;
1235 if (cur.selection()) {
1236 DocIterator beg = cur.selectionBegin();
1237 DocIterator end = cur.selectionEnd();
1238 if (beg.pit() == end.pit()) {
1239 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1240 if (cur.paragraph().isDeleted(p))
1245 replace(this, cmd, has_deleted);
1249 case LFUN_WORD_FINDADV:
1254 cur.clearSelection();
1256 cur.message(from_utf8(N_("Mark off")));
1260 cur.clearSelection();
1263 cur.message(from_utf8(N_("Mark on")));
1266 case LFUN_MARK_TOGGLE:
1267 cur.clearSelection();
1270 cur.message(from_utf8(N_("Mark removed")));
1273 cur.message(from_utf8(N_("Mark set")));
1278 case LFUN_SCREEN_RECENTER:
1282 case LFUN_BIBTEX_DATABASE_ADD: {
1283 Cursor tmpcur = d->cursor_;
1284 findInset(tmpcur, BIBTEX_CODE, false);
1285 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1288 if (inset->addDatabase(cmd.argument()))
1289 buffer_.updateBibfilesCache();
1294 case LFUN_BIBTEX_DATABASE_DEL: {
1295 Cursor tmpcur = d->cursor_;
1296 findInset(tmpcur, BIBTEX_CODE, false);
1297 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1300 if (inset->delDatabase(cmd.argument()))
1301 buffer_.updateBibfilesCache();
1306 case LFUN_STATISTICS: {
1307 DocIterator from, to;
1308 if (cur.selection()) {
1309 from = cur.selectionBegin();
1310 to = cur.selectionEnd();
1312 from = doc_iterator_begin(buffer_.inset());
1313 to = doc_iterator_end(buffer_.inset());
1315 int const words = countWords(from, to);
1316 int const chars = countChars(from, to, false);
1317 int const chars_blanks = countChars(from, to, true);
1319 if (cur.selection())
1320 message = _("Statistics for the selection:");
1322 message = _("Statistics for the document:");
1325 message += bformat(_("%1$d words"), words);
1327 message += _("One word");
1329 if (chars_blanks != 1)
1330 message += bformat(_("%1$d characters (including blanks)"),
1333 message += _("One character (including blanks)");
1336 message += bformat(_("%1$d characters (excluding blanks)"),
1339 message += _("One character (excluding blanks)");
1341 Alert::information(_("Statistics"), message);
1345 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1346 // turn compression on/off
1347 buffer_.params().compressed = !buffer_.params().compressed;
1349 case LFUN_COPY_LABEL_AS_REF: {
1350 // if there is an inset at cursor, try to copy it
1351 Inset * inset = cur.nextInset();
1353 FuncRequest tmpcmd = cmd;
1354 inset->dispatch(cur, tmpcmd);
1356 if (!cur.result().dispatched())
1357 // It did not work too; no action needed.
1359 cur.clearSelection();
1360 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1363 case LFUN_NEXT_INSET_TOGGLE: {
1364 // create the the real function we want to invoke
1365 FuncRequest tmpcmd = cmd;
1366 tmpcmd.action = LFUN_INSET_TOGGLE;
1367 // if there is an inset at cursor, see whether it
1369 Inset * inset = cur.nextInset();
1371 if (inset->isActive()) {
1372 Cursor tmpcur = cur;
1373 tmpcur.pushBackward(*inset);
1374 inset->dispatch(tmpcur, tmpcmd);
1375 if (tmpcur.result().dispatched())
1378 inset->dispatch(cur, tmpcmd);
1380 // if it did not work, try the underlying inset.
1381 if (!inset || !cur.result().dispatched())
1382 cur.dispatch(tmpcmd);
1384 if (!cur.result().dispatched())
1385 // It did not work too; no action needed.
1387 cur.clearSelection();
1388 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1392 case LFUN_NEXT_INSET_MODIFY: {
1393 // create the the real function we want to invoke
1394 FuncRequest tmpcmd = cmd;
1395 tmpcmd.action = LFUN_INSET_MODIFY;
1396 // if there is an inset at cursor, see whether it
1398 Inset * inset = cur.nextInset();
1400 inset->dispatch(cur, tmpcmd);
1401 // if it did not work, try the underlying inset.
1402 if (!inset || !cur.result().dispatched())
1403 cur.dispatch(tmpcmd);
1405 if (!cur.result().dispatched())
1406 // It did not work too; no action needed.
1408 cur.clearSelection();
1409 processUpdateFlags(Update::Force | Update::FitCursor);
1413 case LFUN_SCREEN_UP:
1414 case LFUN_SCREEN_DOWN: {
1415 Point p = getPos(cur, cur.boundary());
1416 if (p.y_ < 0 || p.y_ > height_) {
1417 // The cursor is off-screen so recenter before proceeding.
1419 p = getPos(cur, cur.boundary());
1421 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1422 ? - height_ : height_);
1423 if (cmd.action == LFUN_SCREEN_UP && scrolled > - height_)
1425 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1426 p = Point(width_, height_);
1427 cur.reset(buffer_.inset());
1430 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1431 //FIXME: what to do with cur.x_target()?
1440 case LFUN_SCREEN_UP_SELECT: {
1441 cur.selHandle(true);
1442 if (isTopScreen()) {
1443 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1447 int y = getPos(cur, cur.boundary()).y_;
1448 int const ymin = y - height_ + defaultRowHeight();
1449 while (y > ymin && cur.up())
1450 y = getPos(cur, cur.boundary()).y_;
1453 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1457 case LFUN_SCREEN_DOWN_SELECT: {
1458 cur.selHandle(true);
1459 if (isBottomScreen()) {
1460 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1464 int y = getPos(cur, cur.boundary()).y_;
1465 int const ymax = y + height_ - defaultRowHeight();
1466 while (y < ymax && cur.down())
1467 y = getPos(cur, cur.boundary()).y_;
1470 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1474 case LFUN_BRANCH_ACTIVATE:
1475 case LFUN_BRANCH_DEACTIVATE:
1476 buffer_.dispatch(cmd);
1477 processUpdateFlags(Update::Force);
1480 // This could be rewriten using some command like forall <insetname> <command>
1481 // once the insets refactoring is done.
1482 case LFUN_NOTES_MUTATE: {
1483 if (cmd.argument().empty())
1486 if (mutateNotes(cur, cmd.getArg(0), cmd.getArg(1))) {
1487 processUpdateFlags(Update::Force);
1492 case LFUN_ALL_INSETS_TOGGLE: {
1494 string const name = split(to_utf8(cmd.argument()), action, ' ');
1495 InsetCode const inset_code = insetCode(name);
1497 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1499 Inset & inset = cur.buffer().inset();
1500 InsetIterator it = inset_iterator_begin(inset);
1501 InsetIterator const end = inset_iterator_end(inset);
1502 for (; it != end; ++it) {
1503 if (it->asInsetCollapsable()
1504 && (inset_code == NO_CODE
1505 || inset_code == it->lyxCode())) {
1506 Cursor tmpcur = cur;
1507 tmpcur.pushBackward(*it);
1508 it->dispatch(tmpcur, fr);
1511 processUpdateFlags(Update::Force | Update::FitCursor);
1523 docstring const BufferView::requestSelection()
1525 Cursor & cur = d->cursor_;
1527 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1528 if (!cur.selection()) {
1529 d->xsel_cache_.set = false;
1533 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1534 if (!d->xsel_cache_.set ||
1535 cur.top() != d->xsel_cache_.cursor ||
1536 cur.anchor_.top() != d->xsel_cache_.anchor)
1538 d->xsel_cache_.cursor = cur.top();
1539 d->xsel_cache_.anchor = cur.anchor_.top();
1540 d->xsel_cache_.set = cur.selection();
1541 return cur.selectionAsString(false);
1547 void BufferView::clearSelection()
1549 d->cursor_.clearSelection();
1550 // Clear the selection buffer. Otherwise a subsequent
1551 // middle-mouse-button paste would use the selection buffer,
1552 // not the more current external selection.
1553 cap::clearSelection();
1554 d->xsel_cache_.set = false;
1555 // The buffer did not really change, but this causes the
1556 // redraw we need because we cleared the selection above.
1561 void BufferView::resize(int width, int height)
1563 // Update from work area
1567 // Clear the paragraph height cache.
1568 d->par_height_.clear();
1569 // Redo the metrics.
1574 Inset const * BufferView::getCoveringInset(Text const & text,
1577 TextMetrics & tm = d->text_metrics_[&text];
1578 Inset * inset = tm.checkInsetHit(x, y);
1582 if (!inset->descendable())
1583 // No need to go further down if the inset is not
1587 size_t cell_number = inset->nargs();
1588 // Check all the inner cell.
1589 for (size_t i = 0; i != cell_number; ++i) {
1590 Text const * inner_text = inset->getText(i);
1593 Inset const * inset_deeper =
1594 getCoveringInset(*inner_text, x, y);
1596 return inset_deeper;
1604 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1606 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1608 // This is only called for mouse related events including
1609 // LFUN_FILE_OPEN generated by drag-and-drop.
1610 FuncRequest cmd = cmd0;
1612 Cursor old = cursor();
1614 cur.push(buffer_.inset());
1615 cur.setSelection(d->cursor_.selection());
1617 // Either the inset under the cursor or the
1618 // surrounding Text will handle this event.
1620 // make sure we stay within the screen...
1621 cmd.y = min(max(cmd.y, -1), height_);
1623 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1625 // Get inset under mouse, if there is one.
1626 Inset const * covering_inset =
1627 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1628 if (covering_inset == d->last_inset_)
1629 // Same inset, no need to do anything...
1632 bool need_redraw = false;
1633 // const_cast because of setMouseHover().
1634 Inset * inset = const_cast<Inset *>(covering_inset);
1636 // Remove the hint on the last hovered inset (if any).
1637 need_redraw |= d->last_inset_->setMouseHover(false);
1639 // Highlighted the newly hovered inset (if any).
1640 need_redraw |= inset->setMouseHover(true);
1641 d->last_inset_ = inset;
1645 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1646 << cmd.x << ", " << cmd.y << ")");
1648 d->update_strategy_ = DecorationUpdate;
1650 // This event (moving without mouse click) is not passed further.
1651 // This should be changed if it is further utilized.
1656 // Build temporary cursor.
1657 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1659 // Put anchor at the same position.
1662 cur.beginUndoGroup();
1664 // Try to dispatch to an non-editable inset near this position
1665 // via the temp cursor. If the inset wishes to change the real
1666 // cursor it has to do so explicitly by using
1667 // cur.bv().cursor() = cur; (or similar)
1669 inset->dispatch(cur, cmd);
1671 // Now dispatch to the temporary cursor. If the real cursor should
1672 // be modified, the inset's dispatch has to do so explicitly.
1673 if (!inset || !cur.result().dispatched())
1678 // Notify left insets
1681 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
1683 cursor().fixIfBroken();
1686 // Do we have a selection?
1687 theSelection().haveSelection(cursor().selection());
1689 // If the command has been dispatched,
1690 if (cur.result().dispatched() || cur.result().update())
1691 processUpdateFlags(cur.result().update());
1695 void BufferView::lfunScroll(FuncRequest const & cmd)
1697 string const scroll_type = cmd.getArg(0);
1698 int const scroll_step =
1699 (scroll_type == "line") ? d->scrollbarParameters_.single_step
1700 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
1701 if (scroll_step == 0)
1703 string const scroll_quantity = cmd.getArg(1);
1704 if (scroll_quantity == "up")
1705 scrollUp(scroll_step);
1706 else if (scroll_quantity == "down")
1707 scrollDown(scroll_step);
1709 int const scroll_value = convert<int>(scroll_quantity);
1711 scroll(scroll_step * scroll_value);
1718 int BufferView::scroll(int y)
1721 return scrollDown(y);
1723 return scrollUp(-y);
1728 int BufferView::scrollDown(int offset)
1730 Text * text = &buffer_.text();
1731 TextMetrics & tm = d->text_metrics_[text];
1732 int ymax = height_ + offset;
1734 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1735 int bottom_pos = last.second->position() + last.second->descent();
1736 if (last.first + 1 == int(text->paragraphs().size())) {
1737 if (bottom_pos <= height_)
1739 offset = min(offset, bottom_pos - height_);
1742 if (bottom_pos > ymax)
1744 tm.newParMetricsDown();
1746 d->anchor_ypos_ -= offset;
1751 int BufferView::scrollUp(int offset)
1753 Text * text = &buffer_.text();
1754 TextMetrics & tm = d->text_metrics_[text];
1755 int ymin = - offset;
1757 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1758 int top_pos = first.second->position() - first.second->ascent();
1759 if (first.first == 0) {
1762 offset = min(offset, - top_pos);
1767 tm.newParMetricsUp();
1769 d->anchor_ypos_ += offset;
1774 void BufferView::setCursorFromRow(int row)
1779 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1781 d->cursor_.reset(buffer_.inset());
1783 buffer_.text().setCursor(d->cursor_, 0, 0);
1785 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1789 bool BufferView::setCursorFromInset(Inset const * inset)
1791 // are we already there?
1792 if (cursor().nextInset() == inset)
1795 // Inset is not at cursor position. Find it in the document.
1797 cur.reset(buffer().inset());
1798 while (cur && cur.nextInset() != inset)
1809 void BufferView::gotoLabel(docstring const & label)
1811 Toc & toc = buffer().tocBackend().toc("label");
1812 TocIterator toc_it = toc.begin();
1813 TocIterator end = toc.end();
1814 for (; toc_it != end; ++toc_it) {
1815 if (label == toc_it->str())
1816 dispatch(toc_it->action());
1818 //FIXME: We could do a bit more searching thanks to this:
1819 //InsetLabel const * inset = buffer_.insetLabel(label);
1823 TextMetrics const & BufferView::textMetrics(Text const * t) const
1825 return const_cast<BufferView *>(this)->textMetrics(t);
1829 TextMetrics & BufferView::textMetrics(Text const * t)
1831 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1832 if (tmc_it == d->text_metrics_.end()) {
1833 tmc_it = d->text_metrics_.insert(
1834 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1836 return tmc_it->second;
1840 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1843 return textMetrics(t).parMetrics(pit);
1847 int BufferView::workHeight() const
1853 void BufferView::setCursor(DocIterator const & dit)
1855 size_t const n = dit.depth();
1856 for (size_t i = 0; i < n; ++i)
1857 dit[i].inset().edit(d->cursor_, true);
1859 d->cursor_.setCursor(dit);
1860 d->cursor_.setSelection(false);
1864 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1866 // Would be wrong to delete anything if we have a selection.
1867 if (cur.selection())
1870 bool need_anchor_change = false;
1871 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1872 need_anchor_change);
1874 if (need_anchor_change)
1882 buffer_.updateLabels();
1890 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1892 LASSERT(&cur.bv() == this, /**/);
1895 // this event will clear selection so we save selection for
1896 // persistent selection
1897 cap::saveSelection(cursor());
1899 // Has the cursor just left the inset?
1900 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1902 d->cursor_.fixIfBroken();
1904 // FIXME: shift-mouse selection doesn't work well across insets.
1905 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1907 // do the dEPM magic if needed
1908 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1909 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1910 // the leftinset bool would not be necessary (badcursor instead).
1911 bool update = leftinset;
1912 if (!do_selection && d->cursor_.inTexted())
1913 update |= checkDepm(cur, d->cursor_);
1915 d->cursor_.setCursor(cur);
1916 d->cursor_.boundary(cur.boundary());
1918 d->cursor_.setSelection();
1920 d->cursor_.clearSelection();
1922 d->cursor_.finishUndo();
1923 d->cursor_.setCurrentFont();
1928 void BufferView::putSelectionAt(DocIterator const & cur,
1929 int length, bool backwards)
1931 d->cursor_.clearSelection();
1937 d->cursor_.pos() += length;
1938 d->cursor_.setSelection(d->cursor_, -length);
1940 d->cursor_.setSelection(d->cursor_, length);
1942 // Ensure a redraw happens in any case because the new selection could
1943 // possibly be on the same screen as the previous selection.
1944 processUpdateFlags(Update::Force | Update::FitCursor);
1948 Cursor & BufferView::cursor()
1954 Cursor const & BufferView::cursor() const
1960 pit_type BufferView::anchor_ref() const
1962 return d->anchor_pit_;
1966 bool BufferView::singleParUpdate()
1968 Text & buftext = buffer_.text();
1969 pit_type const bottom_pit = d->cursor_.bottom().pit();
1970 TextMetrics & tm = textMetrics(&buftext);
1971 int old_height = tm.parMetrics(bottom_pit).height();
1973 // make sure inline completion pointer is ok
1974 if (d->inlineCompletionPos_.fixIfBroken())
1975 d->inlineCompletionPos_ = DocIterator();
1977 // In Single Paragraph mode, rebreak only
1978 // the (main text, not inset!) paragraph containing the cursor.
1979 // (if this paragraph contains insets etc., rebreaking will
1980 // recursively descend)
1981 tm.redoParagraph(bottom_pit);
1982 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1983 if (pm.height() != old_height)
1984 // Paragraph height has changed so we cannot proceed to
1985 // the singlePar optimisation.
1988 d->update_strategy_ = SingleParUpdate;
1990 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1991 << " y2: " << pm.position() + pm.descent()
1992 << " pit: " << bottom_pit
1993 << " singlepar: 1");
1998 void BufferView::updateMetrics()
2000 if (height_ == 0 || width_ == 0)
2003 Text & buftext = buffer_.text();
2004 pit_type const npit = int(buftext.paragraphs().size());
2006 // Clear out the position cache in case of full screen redraw,
2007 d->coord_cache_.clear();
2009 // Clear out paragraph metrics to avoid having invalid metrics
2010 // in the cache from paragraphs not relayouted below
2011 // The complete text metrics will be redone.
2012 d->text_metrics_.clear();
2014 TextMetrics & tm = textMetrics(&buftext);
2016 // make sure inline completion pointer is ok
2017 if (d->inlineCompletionPos_.fixIfBroken())
2018 d->inlineCompletionPos_ = DocIterator();
2020 if (d->anchor_pit_ >= npit)
2021 // The anchor pit must have been deleted...
2022 d->anchor_pit_ = npit - 1;
2024 // Rebreak anchor paragraph.
2025 tm.redoParagraph(d->anchor_pit_);
2026 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2029 if (d->anchor_pit_ == 0) {
2030 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2032 // Complete buffer visible? Then it's easy.
2033 if (scrollRange == 0)
2034 d->anchor_ypos_ = anchor_pm.ascent();
2036 // FIXME: Some clever handling needed to show
2037 // the _first_ paragraph up to the top if the cursor is
2038 // in the first line.
2040 anchor_pm.setPosition(d->anchor_ypos_);
2042 LYXERR(Debug::PAINTING, "metrics: "
2043 << " anchor pit = " << d->anchor_pit_
2044 << " anchor ypos = " << d->anchor_ypos_);
2046 // Redo paragraphs above anchor if necessary.
2047 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2048 // We are now just above the anchor paragraph.
2049 pit_type pit1 = d->anchor_pit_ - 1;
2050 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2051 tm.redoParagraph(pit1);
2052 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2054 // Save the paragraph position in the cache.
2059 // Redo paragraphs below the anchor if necessary.
2060 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2061 // We are now just below the anchor paragraph.
2062 pit_type pit2 = d->anchor_pit_ + 1;
2063 for (; pit2 < npit && y2 <= height_; ++pit2) {
2064 tm.redoParagraph(pit2);
2065 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2067 // Save the paragraph position in the cache.
2072 LYXERR(Debug::PAINTING, "Metrics: "
2073 << " anchor pit = " << d->anchor_pit_
2074 << " anchor ypos = " << d->anchor_ypos_
2077 << " pit1 = " << pit1
2078 << " pit2 = " << pit2);
2080 d->update_strategy_ = FullScreenUpdate;
2082 if (lyxerr.debugging(Debug::WORKAREA)) {
2083 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2084 d->coord_cache_.dump();
2089 void BufferView::insertLyXFile(FileName const & fname)
2091 LASSERT(d->cursor_.inTexted(), /**/);
2093 // Get absolute path of file and add ".lyx"
2094 // to the filename if necessary
2095 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2097 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2098 // emit message signal.
2099 message(bformat(_("Inserting document %1$s..."), disp_fn));
2102 Buffer buf("", false);
2103 if (buf.loadLyXFile(filename)) {
2104 ErrorList & el = buffer_.errorList("Parse");
2105 // Copy the inserted document error list into the current buffer one.
2106 el = buf.errorList("Parse");
2107 buffer_.undo().recordUndo(d->cursor_);
2108 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2109 buf.params().documentClassPtr(), el);
2110 res = _("Document %1$s inserted.");
2112 res = _("Could not insert document %1$s");
2117 // emit message signal.
2118 message(bformat(res, disp_fn));
2119 buffer_.errors("Parse");
2123 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2129 // Addup contribution of nested insets, from inside to outside,
2130 // keeping the outer paragraph for a special handling below
2131 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2132 CursorSlice const & sl = dit[i];
2136 // get relative position inside sl.inset()
2137 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2139 // Make relative position inside of the edited inset relative to sl.inset()
2143 // In case of an RTL inset, the edited inset will be positioned to the left
2146 bool boundary_i = boundary && i + 1 == dit.depth();
2147 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2152 // remember width for the case that sl.inset() is positioned in an RTL inset
2153 if (i && dit[i - 1].text()) {
2154 // If this Inset is inside a Text Inset, retrieve the Dimension
2155 // from the containing text instead of using Inset::dimension() which
2156 // might not be implemented.
2157 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2158 // elimination of Inset::dim_ cache. This coordOffset() method needs
2159 // to be rewritten in light of the new design.
2160 Dimension const & dim = parMetrics(dit[i - 1].text(),
2161 dit[i - 1].pit()).insetDimension(&sl.inset());
2164 Dimension const dim = sl.inset().dimension(*this);
2168 //lyxerr << "Cursor::getPos, i: "
2169 // << i << " x: " << xx << " y: " << y << endl;
2172 // Add contribution of initial rows of outermost paragraph
2173 CursorSlice const & sl = dit[0];
2174 TextMetrics const & tm = textMetrics(sl.text());
2175 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2176 LASSERT(!pm.rows().empty(), /**/);
2177 y -= pm.rows()[0].ascent();
2179 // FIXME: document this mess
2181 if (sl.pos() > 0 && dit.depth() == 1) {
2183 if (pos && boundary)
2185 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2186 rend = pm.pos2row(pos);
2188 rend = pm.pos2row(sl.pos());
2190 size_t rend = pm.pos2row(sl.pos());
2192 for (size_t rit = 0; rit != rend; ++rit)
2193 y += pm.rows()[rit].height();
2194 y += pm.rows()[rend].ascent();
2196 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2198 // Make relative position from the nested inset now bufferview absolute.
2199 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2202 // In the RTL case place the nested inset at the left of the cursor in
2203 // the outer paragraph
2204 bool boundary_1 = boundary && 1 == dit.depth();
2205 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2213 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2215 CursorSlice const & bot = dit.bottom();
2216 TextMetrics const & tm = textMetrics(bot.text());
2217 if (!tm.contains(bot.pit()))
2218 return Point(-1, -1);
2220 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2221 p.y_ += tm.parMetrics(bot.pit()).position();
2226 void BufferView::draw(frontend::Painter & pain)
2228 if (height_ == 0 || width_ == 0)
2230 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2232 Text & text = buffer_.text();
2233 TextMetrics const & tm = d->text_metrics_[&text];
2234 int const y = tm.first().second->position();
2235 PainterInfo pi(this, pain);
2237 switch (d->update_strategy_) {
2239 case NoScreenUpdate:
2240 // If no screen painting is actually needed, only some the different
2241 // coordinates of insets and paragraphs needs to be updated.
2242 pi.full_repaint = true;
2243 pi.pain.setDrawingEnabled(false);
2247 case SingleParUpdate:
2248 pi.full_repaint = false;
2249 // In general, only the current row of the outermost paragraph
2250 // will be redrawn. Particular cases where selection spans
2251 // multiple paragraph are correctly detected in TextMetrics.
2255 case DecorationUpdate:
2256 // FIXME: We should also distinguish DecorationUpdate to avoid text
2257 // drawing if possible. This is not possible to do easily right now
2258 // because of the single backing pixmap.
2260 case FullScreenUpdate:
2261 // The whole screen, including insets, will be refreshed.
2262 pi.full_repaint = true;
2264 // Clear background.
2265 pain.fillRectangle(0, 0, width_, height_,
2266 pi.backgroundColor(&buffer_.inset()));
2271 // and possibly grey out below
2272 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2273 int const y2 = lastpm.second->position() + lastpm.second->descent();
2275 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2278 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2280 // The scrollbar needs an update.
2283 // Normalize anchor for next time
2284 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2285 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2286 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2287 ParagraphMetrics const & pm = tm.parMetrics(pit);
2288 if (pm.position() + pm.descent() > 0) {
2289 d->anchor_pit_ = pit;
2290 d->anchor_ypos_ = pm.position();
2294 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2295 << " anchor ypos = " << d->anchor_ypos_);
2299 void BufferView::message(docstring const & msg)
2302 d->gui_->message(msg);
2306 void BufferView::showDialog(string const & name)
2309 d->gui_->showDialog(name, string());
2313 void BufferView::showDialog(string const & name,
2314 string const & data, Inset * inset)
2317 d->gui_->showDialog(name, data, inset);
2321 void BufferView::updateDialog(string const & name, string const & data)
2324 d->gui_->updateDialog(name, data);
2328 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2334 // FIXME: Move this out of BufferView again
2335 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2337 if (!fname.isReadableFile()) {
2338 docstring const error = from_ascii(strerror(errno));
2339 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2340 docstring const text =
2341 bformat(_("Could not read the specified document\n"
2342 "%1$s\ndue to the error: %2$s"), file, error);
2343 Alert::error(_("Could not read file"), text);
2347 if (!fname.isReadableFile()) {
2348 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2349 docstring const text =
2350 bformat(_("%1$s\n is not readable."), file);
2351 Alert::error(_("Could not open file"), text);
2355 // FIXME UNICODE: We don't know the encoding of the file
2356 docstring file_content = fname.fileContents("UTF-8");
2357 if (file_content.empty()) {
2358 Alert::error(_("Reading not UTF-8 encoded file"),
2359 _("The file is not UTF-8 encoded.\n"
2360 "It will be read as local 8Bit-encoded.\n"
2361 "If this does not give the correct result\n"
2362 "then please change the encoding of the file\n"
2363 "to UTF-8 with a program other than LyX.\n"));
2364 file_content = fname.fileContents("local8bit");
2367 return normalize_c(file_content);
2371 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2373 docstring const tmpstr = contentsOfPlaintextFile(f);
2378 Cursor & cur = cursor();
2379 cap::replaceSelection(cur);
2380 buffer_.undo().recordUndo(cur);
2382 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2384 cur.innerText()->insertStringAsLines(cur, tmpstr);
2391 docstring const & BufferView::inlineCompletion() const
2393 return d->inlineCompletion_;
2397 size_t const & BufferView::inlineCompletionUniqueChars() const
2399 return d->inlineCompletionUniqueChars_;
2403 DocIterator const & BufferView::inlineCompletionPos() const
2405 return d->inlineCompletionPos_;
2409 bool samePar(DocIterator const & a, DocIterator const & b)
2411 if (a.empty() && b.empty())
2413 if (a.empty() || b.empty())
2415 return &a.innerParagraph() == &b.innerParagraph();
2419 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2420 docstring const & completion, size_t uniqueChars)
2422 uniqueChars = min(completion.size(), uniqueChars);
2423 bool changed = d->inlineCompletion_ != completion
2424 || d->inlineCompletionUniqueChars_ != uniqueChars;
2425 bool singlePar = true;
2426 d->inlineCompletion_ = completion;
2427 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2429 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2432 DocIterator const & old = d->inlineCompletionPos_;
2434 //lyxerr << "inlineCompletionPos changed" << std::endl;
2435 // old or pos are in another paragraph?
2436 if ((!samePar(cur, pos) && !pos.empty())
2437 || (!samePar(cur, old) && !old.empty())) {
2439 //lyxerr << "different paragraph" << std::endl;
2441 d->inlineCompletionPos_ = pos;
2446 if (singlePar && !(cur.disp_.update() & Update::Force))
2447 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2449 cur.updateFlags(cur.disp_.update() | Update::Force);