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 graphics::Previews::get().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 LyX::ref().session().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 // Get inset under mouse, if there is one.
537 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
539 return covering_inset->contextMenu(*this, x, y);
541 return buffer_.inset().contextMenu(*this, x, y);
545 void BufferView::scrollDocView(int value)
547 int const offset = value - d->scrollbarParameters_.position;
548 // If the offset is less than 2 screen height, prefer to scroll instead.
549 if (abs(offset) <= 2 * height_) {
554 // cut off at the top
555 if (value <= d->scrollbarParameters_.min) {
556 DocIterator dit = doc_iterator_begin(buffer_.inset());
558 LYXERR(Debug::SCROLLING, "scroll to top");
562 // cut off at the bottom
563 if (value >= d->scrollbarParameters_.max) {
564 DocIterator dit = doc_iterator_end(buffer_.inset());
567 LYXERR(Debug::SCROLLING, "scroll to bottom");
571 // find paragraph at target position
572 int par_pos = d->scrollbarParameters_.min;
574 for (; i != int(d->par_height_.size()); ++i) {
575 par_pos += d->par_height_[i];
576 if (par_pos >= value)
580 if (par_pos < value) {
581 // It seems we didn't find the correct pit so stay on the safe side and
583 LYXERR0("scrolling position not found!");
584 scrollDocView(d->scrollbarParameters_.max);
588 DocIterator dit = doc_iterator_begin(buffer_.inset());
590 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
595 // FIXME: this method is not working well.
596 void BufferView::setCursorFromScrollbar()
598 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
600 int const height = 2 * defaultRowHeight();
601 int const first = height;
602 int const last = height_ - height;
603 Cursor & cur = d->cursor_;
605 switch (cursorStatus(cur)) {
607 // We reset the cursor because cursorStatus() does not
608 // work when the cursor is within mathed.
609 cur.reset(buffer_.inset());
610 tm.setCursorFromCoordinates(cur, 0, first);
611 cur.clearSelection();
614 // We reset the cursor because cursorStatus() does not
615 // work when the cursor is within mathed.
616 cur.reset(buffer_.inset());
617 tm.setCursorFromCoordinates(cur, 0, last);
618 cur.clearSelection();
621 int const y = getPos(cur, cur.boundary()).y_;
622 int const newy = min(last, max(y, first));
624 cur.reset(buffer_.inset());
625 tm.setCursorFromCoordinates(cur, 0, newy);
631 Change const BufferView::getCurrentChange() const
633 if (!d->cursor_.selection())
634 return Change(Change::UNCHANGED);
636 DocIterator dit = d->cursor_.selectionBegin();
637 return dit.paragraph().lookupChange(dit.pos());
641 // this could be used elsewhere as well?
642 // FIXME: This does not work within mathed!
643 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
645 Point const p = getPos(dit, dit.boundary());
648 if (p.y_ > workHeight())
654 void BufferView::saveBookmark(unsigned int idx)
656 // tenatively save bookmark, id and pos will be used to
657 // acturately locate a bookmark in a 'live' lyx session.
658 // pit and pos will be updated with bottom level pit/pos
660 LyX::ref().session().bookmarks().save(
662 d->cursor_.bottom().pit(),
663 d->cursor_.bottom().pos(),
664 d->cursor_.paragraph().id(),
669 // emit message signal.
670 message(_("Save bookmark"));
674 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
675 int top_id, pos_type top_pos)
677 bool success = false;
680 d->cursor_.clearSelection();
682 // if a valid par_id is given, try it first
683 // This is the case for a 'live' bookmark when unique paragraph ID
684 // is used to track bookmarks.
686 dit = buffer_.getParFromID(top_id);
688 dit.pos() = min(dit.paragraph().size(), top_pos);
689 // Some slices of the iterator may not be
690 // reachable (e.g. closed collapsable inset)
691 // so the dociterator may need to be
692 // shortened. Otherwise, setCursor may crash
693 // lyx when the cursor can not be set to these
695 size_t const n = dit.depth();
696 for (size_t i = 0; i < n; ++i)
697 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
705 // if top_id == 0, or searching through top_id failed
706 // This is the case for a 'restored' bookmark when only bottom
707 // (document level) pit was saved. Because of this, bookmark
708 // restoration is inaccurate. If a bookmark was within an inset,
709 // it will be restored to the left of the outmost inset that contains
711 if (bottom_pit < int(buffer_.paragraphs().size())) {
712 dit = doc_iterator_begin(buffer_.inset());
714 dit.pit() = bottom_pit;
715 dit.pos() = min(bottom_pos, dit.paragraph().size());
720 // Note: only bottom (document) level pit is set.
722 // set the current font.
723 d->cursor_.setCurrentFont();
724 // To center the screen on this new position we need the
725 // paragraph position which is computed at draw() time.
726 // So we need a redraw!
736 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
738 if (lyxrc.rtl_support) {
739 if (d->cursor_.real_current_font.isRightToLeft()) {
740 if (d->intl_.keymap == Intl::PRIMARY)
741 d->intl_.keyMapSec();
743 if (d->intl_.keymap == Intl::SECONDARY)
744 d->intl_.keyMapPrim();
748 d->intl_.getTransManager().translateAndInsert(c, t, cur);
752 int BufferView::workWidth() const
758 void BufferView::showCursor()
760 showCursor(d->cursor_);
764 void BufferView::showCursor(DocIterator const & dit)
766 // We are not properly started yet, delay until resizing is
771 LYXERR(Debug::SCROLLING, "recentering!");
773 CursorSlice const & bot = dit.bottom();
774 TextMetrics & tm = d->text_metrics_[bot.text()];
776 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
777 int bot_pit = bot.pit();
778 if (bot_pit > max_pit) {
779 // FIXME: Why does this happen?
780 LYXERR0("bottom pit is greater that max pit: "
781 << bot_pit << " > " << max_pit);
785 if (bot_pit == tm.first().first - 1)
786 tm.newParMetricsUp();
787 else if (bot_pit == tm.last().first + 1)
788 tm.newParMetricsDown();
790 if (tm.contains(bot_pit)) {
791 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
792 LASSERT(!pm.rows().empty(), /**/);
793 // FIXME: smooth scrolling doesn't work in mathed.
794 CursorSlice const & cs = dit.innerTextSlice();
795 int offset = coordOffset(dit, dit.boundary()).y_;
796 int ypos = pm.position() + offset;
797 Dimension const & row_dim =
798 pm.getRow(cs.pos(), dit.boundary()).dimension();
799 if (ypos - row_dim.ascent() < 0)
800 scrollUp(- ypos + row_dim.ascent());
801 else if (ypos + row_dim.descent() > height_)
802 scrollDown(ypos - height_ + row_dim.descent());
803 // else, nothing to do, the cursor is already visible so we just return.
807 // fix inline completion position
808 if (d->inlineCompletionPos_.fixIfBroken())
809 d->inlineCompletionPos_ = DocIterator();
811 tm.redoParagraph(bot_pit);
812 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
813 int offset = coordOffset(dit, dit.boundary()).y_;
815 d->anchor_pit_ = bot_pit;
816 CursorSlice const & cs = dit.innerTextSlice();
817 Dimension const & row_dim =
818 pm.getRow(cs.pos(), dit.boundary()).dimension();
820 if (d->anchor_pit_ == 0)
821 d->anchor_ypos_ = offset + pm.ascent();
822 else if (d->anchor_pit_ == max_pit)
823 d->anchor_ypos_ = height_ - offset - row_dim.descent();
825 d->anchor_ypos_ = defaultRowHeight() * 2 - offset - row_dim.descent();
832 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
836 Cursor & cur = d->cursor_;
838 switch (cmd.action) {
841 flag.setEnabled(buffer_.undo().hasUndoStack());
844 flag.setEnabled(buffer_.undo().hasRedoStack());
846 case LFUN_FILE_INSERT:
847 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
848 case LFUN_FILE_INSERT_PLAINTEXT:
849 case LFUN_BOOKMARK_SAVE:
850 // FIXME: Actually, these LFUNS should be moved to Text
851 flag.setEnabled(cur.inTexted());
853 case LFUN_FONT_STATE:
854 case LFUN_LABEL_INSERT:
855 case LFUN_INFO_INSERT:
856 case LFUN_INSET_EDIT:
857 case LFUN_PARAGRAPH_GOTO:
859 case LFUN_REFERENCE_NEXT:
861 case LFUN_WORD_REPLACE:
864 case LFUN_MARK_TOGGLE:
865 case LFUN_SCREEN_RECENTER:
866 case LFUN_BIBTEX_DATABASE_ADD:
867 case LFUN_BIBTEX_DATABASE_DEL:
868 case LFUN_GRAPHICS_GROUPS_UNIFY:
869 case LFUN_NOTES_MUTATE:
870 case LFUN_STATISTICS:
871 flag.setEnabled(true);
874 case LFUN_NEXT_INSET_TOGGLE:
875 case LFUN_NEXT_INSET_MODIFY: {
876 // this is the real function we want to invoke
877 FuncRequest tmpcmd = cmd;
878 tmpcmd.action = (cmd.action == LFUN_NEXT_INSET_TOGGLE)
879 ? LFUN_INSET_TOGGLE : LFUN_INSET_MODIFY;
880 // if there is an inset at cursor, see whether it
881 // handles the lfun, other start from scratch
882 Inset * inset = cur.nextInset();
883 if (!inset || !inset->getStatus(cur, tmpcmd, flag))
884 flag = lyx::getStatus(tmpcmd);
888 case LFUN_LABEL_GOTO: {
889 flag.setEnabled(!cmd.argument().empty()
890 || getInsetByCode<InsetRef>(cur, REF_CODE));
894 case LFUN_CHANGES_TRACK:
895 flag.setEnabled(true);
896 flag.setOnOff(buffer_.params().trackChanges);
899 case LFUN_CHANGES_OUTPUT:
900 flag.setEnabled(true);
901 flag.setOnOff(buffer_.params().outputChanges);
904 case LFUN_CHANGES_MERGE:
905 case LFUN_CHANGE_NEXT:
906 case LFUN_ALL_CHANGES_ACCEPT:
907 case LFUN_ALL_CHANGES_REJECT:
908 // TODO: context-sensitive enabling of LFUNs
909 // In principle, these command should only be enabled if there
910 // is a change in the document. However, without proper
911 // optimizations, this will inevitably result in poor performance.
912 flag.setEnabled(true);
915 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
916 flag.setOnOff(buffer_.params().compressed);
921 case LFUN_SCREEN_DOWN:
923 case LFUN_SCREEN_UP_SELECT:
924 case LFUN_SCREEN_DOWN_SELECT:
925 flag.setEnabled(true);
928 case LFUN_LAYOUT_TABULAR:
929 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
933 flag.setEnabled(!cur.inset().forceEmptyLayout(cur.idx()));
936 case LFUN_LAYOUT_PARAGRAPH:
937 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
940 case LFUN_INSET_SETTINGS: {
941 InsetCode code = cur.inset().lyxCode();
942 if (cmd.getArg(0) == insetName(code)) {
943 flag.setEnabled(true);
947 InsetCode next_code = cur.nextInset()
948 ? cur.nextInset()->lyxCode() : NO_CODE;
949 //FIXME: remove these special cases:
959 enable = (cmd.argument().empty() ||
960 cmd.getArg(0) == insetName(next_code));
965 flag.setEnabled(enable);
969 case LFUN_DIALOG_SHOW_NEW_INSET:
970 flag.setEnabled(cur.inset().lyxCode() != ERT_CODE &&
971 cur.inset().lyxCode() != LISTINGS_CODE);
972 if (cur.inset().lyxCode() == CAPTION_CODE) {
974 if (cur.inset().getStatus(cur, cmd, flag))
979 case LFUN_BRANCH_ACTIVATE:
980 case LFUN_BRANCH_DEACTIVATE: {
982 docstring const branchName = cmd.argument();
983 if (!branchName.empty())
984 enable = buffer_.params().branchlist().find(branchName);
985 flag.setEnabled(enable);
990 flag.setEnabled(false);
997 bool BufferView::dispatch(FuncRequest const & cmd)
999 //lyxerr << [ cmd = " << cmd << "]" << endl;
1001 // Make sure that the cached BufferView is correct.
1002 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1003 << " arg[" << to_utf8(cmd.argument()) << ']'
1004 << " x[" << cmd.x << ']'
1005 << " y[" << cmd.y << ']'
1006 << " button[" << cmd.button() << ']');
1008 Cursor & cur = d->cursor_;
1010 switch (cmd.action) {
1013 cur.message(_("Undo"));
1014 cur.clearSelection();
1015 if (!cur.textUndo())
1016 cur.message(_("No further undo information"));
1018 processUpdateFlags(Update::Force | Update::FitCursor);
1022 cur.message(_("Redo"));
1023 cur.clearSelection();
1024 if (!cur.textRedo())
1025 cur.message(_("No further redo information"));
1027 processUpdateFlags(Update::Force | Update::FitCursor);
1030 case LFUN_FONT_STATE:
1031 cur.message(cur.currentState());
1034 case LFUN_BOOKMARK_SAVE:
1035 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1038 case LFUN_LABEL_GOTO: {
1039 docstring label = cmd.argument();
1040 if (label.empty()) {
1042 getInsetByCode<InsetRef>(d->cursor_,
1045 label = inset->getParam("reference");
1046 // persistent=false: use temp_bookmark
1056 case LFUN_INSET_EDIT: {
1057 FuncRequest fr(cmd);
1058 // if there is an inset at cursor, see whether it
1060 Inset * inset = cur.nextInset();
1062 inset->dispatch(cur, fr);
1063 // if it did not work, try the underlying inset.
1064 if (!inset || !cur.result().dispatched())
1067 if (!cur.result().dispatched())
1068 // It did not work too; no action needed.
1072 case LFUN_PARAGRAPH_GOTO: {
1073 int const id = convert<int>(cmd.getArg(0));
1074 int const pos = convert<int>(cmd.getArg(1));
1076 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1077 b = theBufferList().next(b)) {
1079 DocIterator dit = b->getParFromID(id);
1081 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1085 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1086 << " found in buffer `"
1087 << b->absFileName() << "'.");
1089 if (b == &buffer_) {
1093 processUpdateFlags(Update::Force | Update::FitCursor);
1095 // Switch to other buffer view and resend cmd
1096 theLyXFunc().dispatch(FuncRequest(
1097 LFUN_BUFFER_SWITCH, b->absFileName()));
1098 theLyXFunc().dispatch(cmd);
1105 case LFUN_NOTE_NEXT:
1106 gotoInset(this, NOTE_CODE, false);
1109 case LFUN_REFERENCE_NEXT: {
1110 vector<InsetCode> tmp;
1111 tmp.push_back(LABEL_CODE);
1112 tmp.push_back(REF_CODE);
1113 gotoInset(this, tmp, true);
1117 case LFUN_CHANGES_TRACK:
1118 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1121 case LFUN_CHANGES_OUTPUT:
1122 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1123 if (buffer_.params().outputChanges) {
1124 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1125 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1126 LaTeXFeatures::isAvailable("xcolor");
1128 if (!dvipost && !xcolorsoul) {
1129 Alert::warning(_("Changes not shown in LaTeX output"),
1130 _("Changes will not be highlighted in LaTeX output, "
1131 "because neither dvipost nor xcolor/soul are installed.\n"
1132 "Please install these packages or redefine "
1133 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1134 } else if (!xcolorsoul) {
1135 Alert::warning(_("Changes not shown in LaTeX output"),
1136 _("Changes will not be highlighted in LaTeX output "
1137 "when using pdflatex, because xcolor and soul are not installed.\n"
1138 "Please install both packages or redefine "
1139 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1144 case LFUN_CHANGE_NEXT:
1145 findNextChange(this);
1148 case LFUN_CHANGES_MERGE:
1149 if (findNextChange(this))
1150 showDialog("changes");
1153 case LFUN_ALL_CHANGES_ACCEPT:
1154 // select complete document
1155 d->cursor_.reset(buffer_.inset());
1156 d->cursor_.selHandle(true);
1157 buffer_.text().cursorBottom(d->cursor_);
1158 // accept everything in a single step to support atomic undo
1159 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1162 case LFUN_ALL_CHANGES_REJECT:
1163 // select complete document
1164 d->cursor_.reset(buffer_.inset());
1165 d->cursor_.selHandle(true);
1166 buffer_.text().cursorBottom(d->cursor_);
1167 // reject everything in a single step to support atomic undo
1168 // Note: reject does not work recursively; the user may have to repeat the operation
1169 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1172 case LFUN_WORD_FIND: {
1173 FuncRequest req = cmd;
1174 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1175 req = d->search_request_cache_;
1176 if (find(this, req))
1179 message(_("String not found!"));
1180 d->search_request_cache_ = req;
1184 case LFUN_WORD_REPLACE: {
1185 bool has_deleted = false;
1186 if (cur.selection()) {
1187 DocIterator beg = cur.selectionBegin();
1188 DocIterator end = cur.selectionEnd();
1189 if (beg.pit() == end.pit()) {
1190 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1191 if (cur.paragraph().isDeleted(p))
1196 replace(this, cmd, has_deleted);
1201 cur.clearSelection();
1203 cur.message(from_utf8(N_("Mark off")));
1207 cur.clearSelection();
1210 cur.message(from_utf8(N_("Mark on")));
1213 case LFUN_MARK_TOGGLE:
1214 cur.clearSelection();
1217 cur.message(from_utf8(N_("Mark removed")));
1220 cur.message(from_utf8(N_("Mark set")));
1225 case LFUN_SCREEN_RECENTER:
1229 case LFUN_BIBTEX_DATABASE_ADD: {
1230 Cursor tmpcur = d->cursor_;
1231 findInset(tmpcur, BIBTEX_CODE, false);
1232 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1235 if (inset->addDatabase(cmd.argument()))
1236 buffer_.updateBibfilesCache();
1241 case LFUN_BIBTEX_DATABASE_DEL: {
1242 Cursor tmpcur = d->cursor_;
1243 findInset(tmpcur, BIBTEX_CODE, false);
1244 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1247 if (inset->delDatabase(cmd.argument()))
1248 buffer_.updateBibfilesCache();
1253 case LFUN_STATISTICS: {
1254 DocIterator from, to;
1255 if (cur.selection()) {
1256 from = cur.selectionBegin();
1257 to = cur.selectionEnd();
1259 from = doc_iterator_begin(buffer_.inset());
1260 to = doc_iterator_end(buffer_.inset());
1262 int const words = countWords(from, to);
1263 int const chars = countChars(from, to, false);
1264 int const chars_blanks = countChars(from, to, true);
1266 if (cur.selection())
1267 message = _("Statistics for the selection:");
1269 message = _("Statistics for the document:");
1272 message += bformat(_("%1$d words"), words);
1274 message += _("One word");
1276 if (chars_blanks != 1)
1277 message += bformat(_("%1$d characters (including blanks)"),
1280 message += _("One character (including blanks)");
1283 message += bformat(_("%1$d characters (excluding blanks)"),
1286 message += _("One character (excluding blanks)");
1288 Alert::information(_("Statistics"), message);
1292 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1293 // turn compression on/off
1294 buffer_.params().compressed = !buffer_.params().compressed;
1297 case LFUN_NEXT_INSET_TOGGLE: {
1298 // create the the real function we want to invoke
1299 FuncRequest tmpcmd = cmd;
1300 tmpcmd.action = LFUN_INSET_TOGGLE;
1301 // if there is an inset at cursor, see whether it
1303 Inset * inset = cur.nextInset();
1305 if (inset->isActive()) {
1306 Cursor tmpcur = cur;
1307 tmpcur.pushBackward(*inset);
1308 inset->dispatch(tmpcur, tmpcmd);
1309 if (tmpcur.result().dispatched())
1312 inset->dispatch(cur, tmpcmd);
1314 // if it did not work, try the underlying inset.
1315 if (!inset || !cur.result().dispatched())
1316 cur.dispatch(tmpcmd);
1318 if (!cur.result().dispatched())
1319 // It did not work too; no action needed.
1321 cur.clearSelection();
1322 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1326 case LFUN_NEXT_INSET_MODIFY: {
1327 // create the the real function we want to invoke
1328 FuncRequest tmpcmd = cmd;
1329 tmpcmd.action = LFUN_INSET_MODIFY;
1330 // if there is an inset at cursor, see whether it
1332 Inset * inset = cur.nextInset();
1334 inset->dispatch(cur, tmpcmd);
1335 // if it did not work, try the underlying inset.
1336 if (!inset || !cur.result().dispatched())
1337 cur.dispatch(tmpcmd);
1339 if (!cur.result().dispatched())
1340 // It did not work too; no action needed.
1342 cur.clearSelection();
1343 processUpdateFlags(Update::Force | Update::FitCursor);
1347 case LFUN_SCREEN_UP:
1348 case LFUN_SCREEN_DOWN: {
1349 Point p = getPos(cur, cur.boundary());
1350 if (p.y_ < 0 || p.y_ > height_) {
1351 // The cursor is off-screen so recenter before proceeding.
1353 p = getPos(cur, cur.boundary());
1355 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1356 cur.reset(buffer_.inset());
1357 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1358 //FIXME: what to do with cur.x_target()?
1367 case LFUN_SCREEN_UP_SELECT: {
1368 cur.selHandle(true);
1369 if (isTopScreen()) {
1370 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1374 int y = getPos(cur, cur.boundary()).y_;
1375 int const ymin = y - height_ + defaultRowHeight();
1376 while (y > ymin && cur.up())
1377 y = getPos(cur, cur.boundary()).y_;
1380 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1384 case LFUN_SCREEN_DOWN_SELECT: {
1385 cur.selHandle(true);
1386 if (isBottomScreen()) {
1387 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1391 int y = getPos(cur, cur.boundary()).y_;
1392 int const ymax = y + height_ - defaultRowHeight();
1393 while (y < ymax && cur.down())
1394 y = getPos(cur, cur.boundary()).y_;
1397 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1401 case LFUN_BRANCH_ACTIVATE:
1402 case LFUN_BRANCH_DEACTIVATE:
1403 buffer_.dispatch(cmd);
1404 processUpdateFlags(Update::Force);
1407 // These Two could be rewriten using some command like forall <insetname> <command>
1408 // once the insets refactoring is done.
1409 case LFUN_GRAPHICS_GROUPS_UNIFY: {
1410 if (cmd.argument().empty())
1412 //view()->cursor().recordUndoFullDocument(); let inset-apply do that job
1413 graphics::unifyGraphicsGroups(cur.buffer(), to_utf8(cmd.argument()));
1414 processUpdateFlags(Update::Force | Update::FitCursor);
1418 case LFUN_NOTES_MUTATE: {
1419 if (cmd.argument().empty())
1421 cur.recordUndoFullDocument();
1423 if (mutateNotes(cur, cmd.getArg(0), cmd.getArg(1))) {
1424 processUpdateFlags(Update::Force);
1437 docstring const BufferView::requestSelection()
1439 Cursor & cur = d->cursor_;
1441 if (!cur.selection()) {
1442 d->xsel_cache_.set = false;
1446 if (!d->xsel_cache_.set ||
1447 cur.top() != d->xsel_cache_.cursor ||
1448 cur.anchor_.top() != d->xsel_cache_.anchor)
1450 d->xsel_cache_.cursor = cur.top();
1451 d->xsel_cache_.anchor = cur.anchor_.top();
1452 d->xsel_cache_.set = cur.selection();
1453 return cur.selectionAsString(false);
1459 void BufferView::clearSelection()
1461 d->cursor_.clearSelection();
1462 // Clear the selection buffer. Otherwise a subsequent
1463 // middle-mouse-button paste would use the selection buffer,
1464 // not the more current external selection.
1465 cap::clearSelection();
1466 d->xsel_cache_.set = false;
1467 // The buffer did not really change, but this causes the
1468 // redraw we need because we cleared the selection above.
1473 void BufferView::resize(int width, int height)
1475 // Update from work area
1479 // Clear the paragraph height cache.
1480 d->par_height_.clear();
1481 // Redo the metrics.
1486 Inset const * BufferView::getCoveringInset(Text const & text,
1489 TextMetrics & tm = d->text_metrics_[&text];
1490 Inset * inset = tm.checkInsetHit(x, y);
1494 if (!inset->descendable())
1495 // No need to go further down if the inset is not
1499 size_t cell_number = inset->nargs();
1500 // Check all the inner cell.
1501 for (size_t i = 0; i != cell_number; ++i) {
1502 Text const * inner_text = inset->getText(i);
1505 Inset const * inset_deeper =
1506 getCoveringInset(*inner_text, x, y);
1508 return inset_deeper;
1516 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1518 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1520 // This is only called for mouse related events including
1521 // LFUN_FILE_OPEN generated by drag-and-drop.
1522 FuncRequest cmd = cmd0;
1524 Cursor old = cursor();
1526 cur.push(buffer_.inset());
1527 cur.selection() = d->cursor_.selection();
1529 // Either the inset under the cursor or the
1530 // surrounding Text will handle this event.
1532 // make sure we stay within the screen...
1533 cmd.y = min(max(cmd.y, -1), height_);
1535 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1537 // Get inset under mouse, if there is one.
1538 Inset const * covering_inset =
1539 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1540 if (covering_inset == d->last_inset_)
1541 // Same inset, no need to do anything...
1544 bool need_redraw = false;
1545 // const_cast because of setMouseHover().
1546 Inset * inset = const_cast<Inset *>(covering_inset);
1548 // Remove the hint on the last hovered inset (if any).
1549 need_redraw |= d->last_inset_->setMouseHover(false);
1551 // Highlighted the newly hovered inset (if any).
1552 need_redraw |= inset->setMouseHover(true);
1553 d->last_inset_ = inset;
1557 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1558 << cmd.x << ", " << cmd.y << ")");
1560 d->update_strategy_ = DecorationUpdate;
1562 // This event (moving without mouse click) is not passed further.
1563 // This should be changed if it is further utilized.
1568 // Build temporary cursor.
1569 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1571 // Put anchor at the same position.
1574 // Try to dispatch to an non-editable inset near this position
1575 // via the temp cursor. If the inset wishes to change the real
1576 // cursor it has to do so explicitly by using
1577 // cur.bv().cursor() = cur; (or similar)
1579 inset->dispatch(cur, cmd);
1581 // Now dispatch to the temporary cursor. If the real cursor should
1582 // be modified, the inset's dispatch has to do so explicitly.
1583 if (!inset || !cur.result().dispatched())
1586 // Notify left insets
1589 bool badcursor = notifyCursorLeaves(old, cur);
1591 cursor().fixIfBroken();
1594 // Do we have a selection?
1595 theSelection().haveSelection(cursor().selection());
1597 // If the command has been dispatched,
1598 if (cur.result().dispatched() || cur.result().update())
1599 processUpdateFlags(cur.result().update());
1603 void BufferView::lfunScroll(FuncRequest const & cmd)
1605 string const scroll_type = cmd.getArg(0);
1606 int const scroll_step =
1607 (scroll_type == "line") ? d->scrollbarParameters_.single_step
1608 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
1609 if (scroll_step == 0)
1611 string const scroll_quantity = cmd.getArg(1);
1612 if (scroll_quantity == "up")
1613 scrollUp(scroll_step);
1614 else if (scroll_quantity == "down")
1615 scrollDown(scroll_step);
1617 int const scroll_value = convert<int>(scroll_quantity);
1619 scroll(scroll_step * scroll_value);
1624 void BufferView::scroll(int y)
1633 void BufferView::scrollDown(int offset)
1635 Text * text = &buffer_.text();
1636 TextMetrics & tm = d->text_metrics_[text];
1637 int ymax = height_ + offset;
1639 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1640 int bottom_pos = last.second->position() + last.second->descent();
1641 if (last.first + 1 == int(text->paragraphs().size())) {
1642 if (bottom_pos <= height_)
1644 offset = min(offset, bottom_pos - height_);
1647 if (bottom_pos > ymax)
1649 tm.newParMetricsDown();
1651 d->anchor_ypos_ -= offset;
1657 void BufferView::scrollUp(int offset)
1659 Text * text = &buffer_.text();
1660 TextMetrics & tm = d->text_metrics_[text];
1661 int ymin = - offset;
1663 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1664 int top_pos = first.second->position() - first.second->ascent();
1665 if (first.first == 0) {
1668 offset = min(offset, - top_pos);
1673 tm.newParMetricsUp();
1675 d->anchor_ypos_ += offset;
1681 void BufferView::setCursorFromRow(int row)
1686 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1688 d->cursor_.reset(buffer_.inset());
1690 buffer_.text().setCursor(d->cursor_, 0, 0);
1692 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1696 void BufferView::gotoLabel(docstring const & label)
1698 Toc & toc = buffer().tocBackend().toc("label");
1699 TocIterator toc_it = toc.begin();
1700 TocIterator end = toc.end();
1701 for (; toc_it != end; ++toc_it) {
1702 if (label == toc_it->str())
1703 dispatch(toc_it->action());
1705 //FIXME: We could do a bit more searching thanks to this:
1706 //InsetLabel const * inset = buffer_.insetLabel(label);
1710 TextMetrics const & BufferView::textMetrics(Text const * t) const
1712 return const_cast<BufferView *>(this)->textMetrics(t);
1716 TextMetrics & BufferView::textMetrics(Text const * t)
1718 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1719 if (tmc_it == d->text_metrics_.end()) {
1720 tmc_it = d->text_metrics_.insert(
1721 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1723 return tmc_it->second;
1727 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1730 return textMetrics(t).parMetrics(pit);
1734 int BufferView::workHeight() const
1740 void BufferView::setCursor(DocIterator const & dit)
1742 size_t const n = dit.depth();
1743 for (size_t i = 0; i < n; ++i)
1744 dit[i].inset().edit(d->cursor_, true);
1746 d->cursor_.setCursor(dit);
1747 d->cursor_.selection() = false;
1751 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1753 // Would be wrong to delete anything if we have a selection.
1754 if (cur.selection())
1757 bool need_anchor_change = false;
1758 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1759 need_anchor_change);
1761 if (need_anchor_change)
1769 updateLabels(buffer_);
1777 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1779 LASSERT(&cur.bv() == this, /**/);
1782 // this event will clear selection so we save selection for
1783 // persistent selection
1784 cap::saveSelection(cursor());
1786 // Has the cursor just left the inset?
1787 bool badcursor = false;
1788 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1790 d->cursor_.fixIfBroken();
1791 badcursor = notifyCursorLeaves(d->cursor_, cur);
1796 // FIXME: shift-mouse selection doesn't work well across insets.
1797 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1799 // do the dEPM magic if needed
1800 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1801 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1802 // the leftinset bool would not be necessary (badcursor instead).
1803 bool update = leftinset;
1804 if (!do_selection && !badcursor && d->cursor_.inTexted())
1805 update |= checkDepm(cur, d->cursor_);
1807 d->cursor_.setCursor(cur);
1808 d->cursor_.boundary(cur.boundary());
1810 d->cursor_.setSelection();
1812 d->cursor_.clearSelection();
1814 d->cursor_.finishUndo();
1815 d->cursor_.setCurrentFont();
1820 void BufferView::putSelectionAt(DocIterator const & cur,
1821 int length, bool backwards)
1823 d->cursor_.clearSelection();
1829 d->cursor_.pos() += length;
1830 d->cursor_.setSelection(d->cursor_, -length);
1832 d->cursor_.setSelection(d->cursor_, length);
1834 // Ensure a redraw happens in any case because the new selection could
1835 // possibly be on the same screen as the previous selection.
1836 processUpdateFlags(Update::Force | Update::FitCursor);
1840 Cursor & BufferView::cursor()
1846 Cursor const & BufferView::cursor() const
1852 pit_type BufferView::anchor_ref() const
1854 return d->anchor_pit_;
1858 bool BufferView::singleParUpdate()
1860 Text & buftext = buffer_.text();
1861 pit_type const bottom_pit = d->cursor_.bottom().pit();
1862 TextMetrics & tm = textMetrics(&buftext);
1863 int old_height = tm.parMetrics(bottom_pit).height();
1865 // make sure inline completion pointer is ok
1866 if (d->inlineCompletionPos_.fixIfBroken())
1867 d->inlineCompletionPos_ = DocIterator();
1869 // In Single Paragraph mode, rebreak only
1870 // the (main text, not inset!) paragraph containing the cursor.
1871 // (if this paragraph contains insets etc., rebreaking will
1872 // recursively descend)
1873 tm.redoParagraph(bottom_pit);
1874 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1875 if (pm.height() != old_height)
1876 // Paragraph height has changed so we cannot proceed to
1877 // the singlePar optimisation.
1880 d->update_strategy_ = SingleParUpdate;
1882 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1883 << " y2: " << pm.position() + pm.descent()
1884 << " pit: " << bottom_pit
1885 << " singlepar: 1");
1890 void BufferView::updateMetrics()
1892 if (height_ == 0 || width_ == 0)
1895 Text & buftext = buffer_.text();
1896 pit_type const npit = int(buftext.paragraphs().size());
1898 // Clear out the position cache in case of full screen redraw,
1899 d->coord_cache_.clear();
1901 // Clear out paragraph metrics to avoid having invalid metrics
1902 // in the cache from paragraphs not relayouted below
1903 // The complete text metrics will be redone.
1904 d->text_metrics_.clear();
1906 TextMetrics & tm = textMetrics(&buftext);
1908 // make sure inline completion pointer is ok
1909 if (d->inlineCompletionPos_.fixIfBroken())
1910 d->inlineCompletionPos_ = DocIterator();
1912 if (d->anchor_pit_ >= npit)
1913 // The anchor pit must have been deleted...
1914 d->anchor_pit_ = npit - 1;
1916 // Rebreak anchor paragraph.
1917 tm.redoParagraph(d->anchor_pit_);
1918 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1921 if (d->anchor_pit_ == 0) {
1922 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
1924 // Complete buffer visible? Then it's easy.
1925 if (scrollRange == 0)
1926 d->anchor_ypos_ = anchor_pm.ascent();
1928 // FIXME: Some clever handling needed to show
1929 // the _first_ paragraph up to the top if the cursor is
1930 // in the first line.
1932 anchor_pm.setPosition(d->anchor_ypos_);
1934 LYXERR(Debug::PAINTING, "metrics: "
1935 << " anchor pit = " << d->anchor_pit_
1936 << " anchor ypos = " << d->anchor_ypos_);
1938 // Redo paragraphs above anchor if necessary.
1939 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1940 // We are now just above the anchor paragraph.
1941 pit_type pit1 = d->anchor_pit_ - 1;
1942 for (; pit1 >= 0 && y1 >= 0; --pit1) {
1943 tm.redoParagraph(pit1);
1944 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1946 // Save the paragraph position in the cache.
1951 // Redo paragraphs below the anchor if necessary.
1952 int y2 = d->anchor_ypos_ + anchor_pm.descent();
1953 // We are now just below the anchor paragraph.
1954 pit_type pit2 = d->anchor_pit_ + 1;
1955 for (; pit2 < npit && y2 <= height_; ++pit2) {
1956 tm.redoParagraph(pit2);
1957 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1959 // Save the paragraph position in the cache.
1964 LYXERR(Debug::PAINTING, "Metrics: "
1965 << " anchor pit = " << d->anchor_pit_
1966 << " anchor ypos = " << d->anchor_ypos_
1969 << " pit1 = " << pit1
1970 << " pit2 = " << pit2);
1972 d->update_strategy_ = FullScreenUpdate;
1974 if (lyxerr.debugging(Debug::WORKAREA)) {
1975 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1976 d->coord_cache_.dump();
1981 void BufferView::insertLyXFile(FileName const & fname)
1983 LASSERT(d->cursor_.inTexted(), /**/);
1985 // Get absolute path of file and add ".lyx"
1986 // to the filename if necessary
1987 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1989 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1990 // emit message signal.
1991 message(bformat(_("Inserting document %1$s..."), disp_fn));
1994 Buffer buf("", false);
1995 if (buf.loadLyXFile(filename)) {
1996 ErrorList & el = buffer_.errorList("Parse");
1997 // Copy the inserted document error list into the current buffer one.
1998 el = buf.errorList("Parse");
1999 buffer_.undo().recordUndo(d->cursor_);
2000 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2001 buf.params().documentClassPtr(), el);
2002 res = _("Document %1$s inserted.");
2004 res = _("Could not insert document %1$s");
2009 // emit message signal.
2010 message(bformat(res, disp_fn));
2011 buffer_.errors("Parse");
2015 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2021 // Addup contribution of nested insets, from inside to outside,
2022 // keeping the outer paragraph for a special handling below
2023 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2024 CursorSlice const & sl = dit[i];
2028 // get relative position inside sl.inset()
2029 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2031 // Make relative position inside of the edited inset relative to sl.inset()
2035 // In case of an RTL inset, the edited inset will be positioned to the left
2038 bool boundary_i = boundary && i + 1 == dit.depth();
2039 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2044 // remember width for the case that sl.inset() is positioned in an RTL inset
2045 if (i && dit[i - 1].text()) {
2046 // If this Inset is inside a Text Inset, retrieve the Dimension
2047 // from the containing text instead of using Inset::dimension() which
2048 // might not be implemented.
2049 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2050 // elimination of Inset::dim_ cache. This coordOffset() method needs
2051 // to be rewritten in light of the new design.
2052 Dimension const & dim = parMetrics(dit[i - 1].text(),
2053 dit[i - 1].pit()).insetDimension(&sl.inset());
2056 Dimension const dim = sl.inset().dimension(*this);
2060 //lyxerr << "Cursor::getPos, i: "
2061 // << i << " x: " << xx << " y: " << y << endl;
2064 // Add contribution of initial rows of outermost paragraph
2065 CursorSlice const & sl = dit[0];
2066 TextMetrics const & tm = textMetrics(sl.text());
2067 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2068 LASSERT(!pm.rows().empty(), /**/);
2069 y -= pm.rows()[0].ascent();
2071 // FIXME: document this mess
2073 if (sl.pos() > 0 && dit.depth() == 1) {
2075 if (pos && boundary)
2077 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2078 rend = pm.pos2row(pos);
2080 rend = pm.pos2row(sl.pos());
2082 size_t rend = pm.pos2row(sl.pos());
2084 for (size_t rit = 0; rit != rend; ++rit)
2085 y += pm.rows()[rit].height();
2086 y += pm.rows()[rend].ascent();
2088 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2090 // Make relative position from the nested inset now bufferview absolute.
2091 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2094 // In the RTL case place the nested inset at the left of the cursor in
2095 // the outer paragraph
2096 bool boundary_1 = boundary && 1 == dit.depth();
2097 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2105 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2107 CursorSlice const & bot = dit.bottom();
2108 TextMetrics const & tm = textMetrics(bot.text());
2109 if (!tm.contains(bot.pit()))
2110 return Point(-1, -1);
2112 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2113 p.y_ += tm.parMetrics(bot.pit()).position();
2118 void BufferView::draw(frontend::Painter & pain)
2120 if (height_ == 0 || width_ == 0)
2122 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2123 Text & text = buffer_.text();
2124 TextMetrics const & tm = d->text_metrics_[&text];
2125 int const y = tm.first().second->position();
2126 PainterInfo pi(this, pain);
2128 switch (d->update_strategy_) {
2130 case NoScreenUpdate:
2131 // If no screen painting is actually needed, only some the different
2132 // coordinates of insets and paragraphs needs to be updated.
2133 pi.full_repaint = true;
2134 pi.pain.setDrawingEnabled(false);
2138 case SingleParUpdate:
2139 pi.full_repaint = false;
2140 // In general, only the current row of the outermost paragraph
2141 // will be redrawn. Particular cases where selection spans
2142 // multiple paragraph are correctly detected in TextMetrics.
2146 case DecorationUpdate:
2147 // FIXME: We should also distinguish DecorationUpdate to avoid text
2148 // drawing if possible. This is not possible to do easily right now
2149 // because of the single backing pixmap.
2151 case FullScreenUpdate:
2152 // The whole screen, including insets, will be refreshed.
2153 pi.full_repaint = true;
2155 // Clear background.
2156 pain.fillRectangle(0, 0, width_, height_,
2157 buffer_.inset().backgroundColor());
2162 // and possibly grey out below
2163 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2164 int const y2 = lastpm.second->position() + lastpm.second->descent();
2166 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2169 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2171 // The scrollbar needs an update.
2174 // Normalize anchor for next time
2175 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2176 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2177 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2178 ParagraphMetrics const & pm = tm.parMetrics(pit);
2179 if (pm.position() + pm.descent() > 0) {
2180 d->anchor_pit_ = pit;
2181 d->anchor_ypos_ = pm.position();
2185 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2186 << " anchor ypos = " << d->anchor_ypos_);
2190 void BufferView::message(docstring const & msg)
2193 d->gui_->message(msg);
2197 void BufferView::showDialog(string const & name)
2200 d->gui_->showDialog(name, string());
2204 void BufferView::showDialog(string const & name,
2205 string const & data, Inset * inset)
2208 d->gui_->showDialog(name, data, inset);
2212 void BufferView::updateDialog(string const & name, string const & data)
2215 d->gui_->updateDialog(name, data);
2219 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2225 // FIXME: Move this out of BufferView again
2226 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2228 if (!fname.isReadableFile()) {
2229 docstring const error = from_ascii(strerror(errno));
2230 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2231 docstring const text =
2232 bformat(_("Could not read the specified document\n"
2233 "%1$s\ndue to the error: %2$s"), file, error);
2234 Alert::error(_("Could not read file"), text);
2238 if (!fname.isReadableFile()) {
2239 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2240 docstring const text =
2241 bformat(_("%1$s\n is not readable."), file);
2242 Alert::error(_("Could not open file"), text);
2246 // FIXME UNICODE: We don't know the encoding of the file
2247 docstring file_content = fname.fileContents("UTF-8");
2248 if (file_content.empty()) {
2249 Alert::error(_("Reading not UTF-8 encoded file"),
2250 _("The file is not UTF-8 encoded.\n"
2251 "It will be read as local 8Bit-encoded.\n"
2252 "If this does not give the correct result\n"
2253 "then please change the encoding of the file\n"
2254 "to UTF-8 with a program other than LyX.\n"));
2255 file_content = fname.fileContents("local8bit");
2258 return normalize_c(file_content);
2262 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2264 docstring const tmpstr = contentsOfPlaintextFile(f);
2269 Cursor & cur = cursor();
2270 cap::replaceSelection(cur);
2271 buffer_.undo().recordUndo(cur);
2273 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2275 cur.innerText()->insertStringAsLines(cur, tmpstr);
2282 docstring const & BufferView::inlineCompletion() const
2284 return d->inlineCompletion_;
2288 size_t const & BufferView::inlineCompletionUniqueChars() const
2290 return d->inlineCompletionUniqueChars_;
2294 DocIterator const & BufferView::inlineCompletionPos() const
2296 return d->inlineCompletionPos_;
2300 bool samePar(DocIterator const & a, DocIterator const & b)
2302 if (a.empty() && b.empty())
2304 if (a.empty() || b.empty())
2306 return &a.innerParagraph() == &b.innerParagraph();
2310 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2311 docstring const & completion, size_t uniqueChars)
2313 uniqueChars = min(completion.size(), uniqueChars);
2314 bool changed = d->inlineCompletion_ != completion
2315 || d->inlineCompletionUniqueChars_ != uniqueChars;
2316 bool singlePar = true;
2317 d->inlineCompletion_ = completion;
2318 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2320 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2323 DocIterator const & old = d->inlineCompletionPos_;
2325 //lyxerr << "inlineCompletionPos changed" << std::endl;
2326 // old or pos are in another paragraph?
2327 if ((!samePar(cur, pos) && !pos.empty())
2328 || (!samePar(cur, old) && !old.empty())) {
2330 //lyxerr << "different paragraph" << std::endl;
2332 d->inlineCompletionPos_ = pos;
2337 if (singlePar && !(cur.disp_.update() & Update::Force))
2338 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2340 cur.updateFlags(cur.disp_.update() | Update::Force);