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"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "CoordCache.h"
25 #include "CutAndPaste.h"
26 #include "DispatchResult.h"
27 #include "ErrorList.h"
29 #include "FloatList.h"
30 #include "FuncRequest.h"
31 #include "FuncStatus.h"
33 #include "InsetIterator.h"
35 #include "LaTeXFeatures.h"
41 #include "MetricsInfo.h"
42 #include "Paragraph.h"
43 #include "paragraph_funcs.h"
44 #include "ParagraphParameters.h"
45 #include "ParIterator.h"
48 #include "TextClass.h"
49 #include "TextMetrics.h"
51 #include "TocBackend.h"
53 #include "WordLangTuple.h"
55 #include "insets/InsetBibtex.h"
56 #include "insets/InsetCommand.h" // ChangeRefs
57 #include "insets/InsetExternal.h"
58 #include "insets/InsetGraphics.h"
59 #include "insets/InsetRef.h"
60 #include "insets/InsetText.h"
62 #include "frontends/alert.h"
63 #include "frontends/Application.h"
64 #include "frontends/Delegates.h"
65 #include "frontends/FontMetrics.h"
66 #include "frontends/Painter.h"
67 #include "frontends/Selection.h"
69 #include "graphics/Previews.h"
71 #include "support/convert.h"
72 #include "support/debug.h"
73 #include "support/ExceptionMessage.h"
74 #include "support/filetools.h"
75 #include "support/gettext.h"
76 #include "support/lstrings.h"
77 #include "support/Package.h"
78 #include "support/types.h"
87 using namespace lyx::support;
91 namespace Alert = frontend::Alert;
95 /// Return an inset of this class if it exists at the current cursor position
97 T * getInsetByCode(Cursor const & cur, InsetCode code)
100 Inset * inset = it.nextInset();
101 if (inset && inset->lyxCode() == code)
102 return static_cast<T*>(inset);
107 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
110 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
111 docstring const & contents)
113 DocIterator tmpdit = dit;
116 Inset const * inset = tmpdit.nextInset();
118 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
119 && (contents.empty() ||
120 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
124 tmpdit.forwardInset();
131 /// Looks for next inset with one of the given codes.
132 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
136 DocIterator tmpdit = dit;
137 tmpdit.forwardInset();
142 Inset const * inset = tmpdit.nextInset();
144 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
145 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
149 if (!findNextInset(tmpdit, codes, contents)) {
150 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
151 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
152 if (!findNextInset(tmpdit, codes, contents))
163 /// Looks for next inset with the given code
164 void findInset(DocIterator & dit, InsetCode code, bool same_content)
166 findInset(dit, vector<InsetCode>(1, code), same_content);
170 /// Moves cursor to the next inset with one of the given codes.
171 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
174 Cursor tmpcur = bv->cursor();
175 if (!findInset(tmpcur, codes, same_content)) {
176 bv->cursor().message(_("No more insets"));
180 tmpcur.clearSelection();
181 bv->setCursor(tmpcur);
186 /// Moves cursor to the next inset with given code.
187 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
189 gotoInset(bv, vector<InsetCode>(1, code), same_content);
193 /// A map from a Text to the associated text metrics
194 typedef map<Text const *, TextMetrics> TextMetricsCache;
196 enum ScreenUpdateStrategy {
206 /////////////////////////////////////////////////////////////////////
210 /////////////////////////////////////////////////////////////////////
212 struct BufferView::Private
214 Private(BufferView & bv): wh_(0), cursor_(bv),
215 anchor_pit_(0), anchor_ypos_(0),
216 inlineCompletionUniqueChars_(0),
217 last_inset_(0), gui_(0)
221 ScrollbarParameters scrollbarParameters_;
223 ScreenUpdateStrategy update_strategy_;
225 CoordCache coord_cache_;
227 /// Estimated average par height for scrollbar.
229 /// this is used to handle XSelection events in the right manner.
238 pit_type anchor_pit_;
242 vector<int> par_height_;
245 DocIterator inlineCompletionPos_;
247 docstring inlineCompletion_;
249 size_t inlineCompletionUniqueChars_;
251 /// keyboard mapping object.
254 /// last visited inset.
255 /** kept to send setMouseHover(false).
256 * Not owned, so don't delete.
260 mutable TextMetricsCache text_metrics_;
263 /** Not owned, so don't delete.
265 frontend::GuiBufferViewDelegate * gui_;
267 /// Cache for Find Next
268 FuncRequest search_request_cache_;
272 BufferView::BufferView(Buffer & buf)
273 : width_(0), height_(0), full_screen_(false), buffer_(buf), d(new Private(*this))
275 d->xsel_cache_.set = false;
276 d->intl_.initKeyMapper(lyxrc.use_kbmap);
278 d->cursor_.push(buffer_.inset());
279 d->cursor_.resetAnchor();
280 d->cursor_.setCurrentFont();
282 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
283 graphics::Previews::get().generateBufferPreviews(buffer_);
287 BufferView::~BufferView()
289 // current buffer is going to be switched-off, save cursor pos
290 // Ideally, the whole cursor stack should be saved, but session
291 // currently can only handle bottom (whole document) level pit and pos.
292 // That is to say, if a cursor is in a nested inset, it will be
293 // restore to the left of the top level inset.
294 LastFilePosSection::FilePos fp;
295 fp.pit = d->cursor_.bottom().pit();
296 fp.pos = d->cursor_.bottom().pos();
297 LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
303 int BufferView::rightMargin() const
305 // The additional test for the case the outliner is opened.
307 !lyxrc.full_screen_limit ||
308 width_ < lyxrc.full_screen_width + 20)
311 return (width_ - lyxrc.full_screen_width) / 2;
315 int BufferView::leftMargin() const
317 return rightMargin();
321 bool BufferView::isTopScreen() const
323 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
327 bool BufferView::isBottomScreen() const
329 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
333 Intl & BufferView::getIntl()
339 Intl const & BufferView::getIntl() const
345 CoordCache & BufferView::coordCache()
347 return d->coord_cache_;
351 CoordCache const & BufferView::coordCache() const
353 return d->coord_cache_;
357 Buffer & BufferView::buffer()
363 Buffer const & BufferView::buffer() const
369 bool BufferView::fitCursor()
371 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
372 frontend::FontMetrics const & fm =
373 theFontMetrics(d->cursor_.getFont().fontInfo());
374 int const asc = fm.maxAscent();
375 int const des = fm.maxDescent();
376 Point const p = getPos(d->cursor_, d->cursor_.boundary());
377 if (p.y_ - asc >= 0 && p.y_ + des < height_)
384 void BufferView::processUpdateFlags(Update::flags flags)
386 // last_inset_ points to the last visited inset. This pointer may become
387 // invalid because of keyboard editing. Since all such operations
388 // causes screen update(), I reset last_inset_ to avoid such a problem.
390 // This is close to a hot-path.
391 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
392 << "[fitcursor = " << (flags & Update::FitCursor)
393 << ", forceupdate = " << (flags & Update::Force)
394 << ", singlepar = " << (flags & Update::SinglePar)
395 << "] buffer: " << &buffer_);
397 buffer_.updateMacros();
399 // Now do the first drawing step if needed. This consists on updating
400 // the CoordCache in updateMetrics().
401 // The second drawing step is done in WorkArea::redraw() if needed.
403 // Case when no explicit update is requested.
405 // no need to redraw anything.
406 d->update_strategy_ = NoScreenUpdate;
410 if (flags == Update::Decoration) {
411 d->update_strategy_ = DecorationUpdate;
416 if (flags == Update::FitCursor
417 || flags == (Update::Decoration | Update::FitCursor)) {
418 // tell the frontend to update the screen if needed.
423 if (flags & Update::Decoration) {
424 d->update_strategy_ = DecorationUpdate;
428 // no screen update is needed.
429 d->update_strategy_ = NoScreenUpdate;
433 bool const full_metrics = flags & Update::Force || !singleParUpdate();
436 // We have to update the full screen metrics.
439 if (!(flags & Update::FitCursor)) {
440 // Nothing to do anymore. Trigger a redraw and return
445 // updateMetrics() does not update paragraph position
446 // This is done at draw() time. So we need a redraw!
450 // The cursor is off screen so ensure it is visible.
457 void BufferView::updateScrollbar()
462 // We prefer fixed size line scrolling.
463 d->scrollbarParameters_.single_step = defaultRowHeight();
464 // We prefer full screen page scrolling.
465 d->scrollbarParameters_.page_step = height_;
467 Text & t = buffer_.text();
468 TextMetrics & tm = d->text_metrics_[&t];
470 LYXERR(Debug::GUI, " Updating scrollbar: height: "
471 << t.paragraphs().size()
472 << " curr par: " << d->cursor_.bottom().pit()
473 << " default height " << defaultRowHeight());
475 size_t const parsize = t.paragraphs().size();
476 if (d->par_height_.size() != parsize) {
477 d->par_height_.clear();
478 // FIXME: We assume a default paragraph height of 2 rows. This
479 // should probably be pondered with the screen width.
480 d->par_height_.resize(parsize, defaultRowHeight() * 2);
483 // Look at paragraph heights on-screen
484 pair<pit_type, ParagraphMetrics const *> first = tm.first();
485 pair<pit_type, ParagraphMetrics const *> last = tm.last();
486 for (pit_type pit = first.first; pit <= last.first; ++pit) {
487 d->par_height_[pit] = tm.parMetrics(pit).height();
488 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
489 << d->par_height_[pit]);
492 int top_pos = first.second->position() - first.second->ascent();
493 int bottom_pos = last.second->position() + last.second->descent();
494 bool first_visible = first.first == 0 && top_pos >= 0;
495 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
496 if (first_visible && last_visible) {
497 d->scrollbarParameters_.min = 0;
498 d->scrollbarParameters_.max = 0;
502 d->scrollbarParameters_.min = top_pos;
503 for (size_t i = 0; i != size_t(first.first); ++i)
504 d->scrollbarParameters_.min -= d->par_height_[i];
505 d->scrollbarParameters_.max = bottom_pos;
506 for (size_t i = last.first + 1; i != parsize; ++i)
507 d->scrollbarParameters_.max += d->par_height_[i];
509 d->scrollbarParameters_.position = 0;
510 // The reference is the top position so we remove one page.
511 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
515 ScrollbarParameters const & BufferView::scrollbarParameters() const
517 return d->scrollbarParameters_;
521 docstring BufferView::toolTip(int x, int y) const
523 // Get inset under mouse, if there is one.
524 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
526 // No inset, no tooltip...
528 return covering_inset->toolTip(*this, x, y);
532 docstring BufferView::contextMenu(int x, int y) const
534 // Get inset under mouse, if there is one.
535 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
537 return covering_inset->contextMenu(*this, x, y);
539 return buffer_.inset().contextMenu(*this, x, y);
543 void BufferView::scrollDocView(int value)
545 int const offset = value - d->scrollbarParameters_.position;
546 // If the offset is less than 2 screen height, prefer to scroll instead.
547 if (abs(offset) <= 2 * height_) {
552 // cut off at the top
553 if (value <= d->scrollbarParameters_.min) {
554 DocIterator dit = doc_iterator_begin(buffer_.inset());
556 LYXERR(Debug::SCROLLING, "scroll to top");
560 // cut off at the bottom
561 if (value >= d->scrollbarParameters_.max) {
562 DocIterator dit = doc_iterator_end(buffer_.inset());
565 LYXERR(Debug::SCROLLING, "scroll to bottom");
569 // find paragraph at target position
570 int par_pos = d->scrollbarParameters_.min;
572 for (; i != int(d->par_height_.size()); ++i) {
573 par_pos += d->par_height_[i];
574 if (par_pos >= value)
578 if (par_pos < value) {
579 // It seems we didn't find the correct pit so stay on the safe side and
581 LYXERR0("scrolling position not found!");
582 scrollDocView(d->scrollbarParameters_.max);
586 DocIterator dit = doc_iterator_begin(buffer_.inset());
588 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
593 // FIXME: this method is not working well.
594 void BufferView::setCursorFromScrollbar()
596 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
598 int const height = 2 * defaultRowHeight();
599 int const first = height;
600 int const last = height_ - height;
601 Cursor & cur = d->cursor_;
603 switch (cursorStatus(cur)) {
605 // We reset the cursor because cursorStatus() does not
606 // work when the cursor is within mathed.
607 cur.reset(buffer_.inset());
608 tm.setCursorFromCoordinates(cur, 0, first);
609 cur.clearSelection();
612 // We reset the cursor because cursorStatus() does not
613 // work when the cursor is within mathed.
614 cur.reset(buffer_.inset());
615 tm.setCursorFromCoordinates(cur, 0, last);
616 cur.clearSelection();
619 int const y = getPos(cur, cur.boundary()).y_;
620 int const newy = min(last, max(y, first));
622 cur.reset(buffer_.inset());
623 tm.setCursorFromCoordinates(cur, 0, newy);
629 Change const BufferView::getCurrentChange() const
631 if (!d->cursor_.selection())
632 return Change(Change::UNCHANGED);
634 DocIterator dit = d->cursor_.selectionBegin();
635 return dit.paragraph().lookupChange(dit.pos());
639 // this could be used elsewhere as well?
640 // FIXME: This does not work within mathed!
641 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
643 Point const p = getPos(dit, dit.boundary());
646 if (p.y_ > workHeight())
652 void BufferView::saveBookmark(unsigned int idx)
654 // tenatively save bookmark, id and pos will be used to
655 // acturately locate a bookmark in a 'live' lyx session.
656 // pit and pos will be updated with bottom level pit/pos
658 LyX::ref().session().bookmarks().save(
660 d->cursor_.bottom().pit(),
661 d->cursor_.bottom().pos(),
662 d->cursor_.paragraph().id(),
667 // emit message signal.
668 message(_("Save bookmark"));
672 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
673 int top_id, pos_type top_pos)
675 bool success = false;
678 d->cursor_.clearSelection();
680 // if a valid par_id is given, try it first
681 // This is the case for a 'live' bookmark when unique paragraph ID
682 // is used to track bookmarks.
684 dit = buffer_.getParFromID(top_id);
686 dit.pos() = min(dit.paragraph().size(), top_pos);
687 // Some slices of the iterator may not be
688 // reachable (e.g. closed collapsable inset)
689 // so the dociterator may need to be
690 // shortened. Otherwise, setCursor may crash
691 // lyx when the cursor can not be set to these
693 size_t const n = dit.depth();
694 for (size_t i = 0; i < n; ++i)
695 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
703 // if top_id == 0, or searching through top_id failed
704 // This is the case for a 'restored' bookmark when only bottom
705 // (document level) pit was saved. Because of this, bookmark
706 // restoration is inaccurate. If a bookmark was within an inset,
707 // it will be restored to the left of the outmost inset that contains
709 if (bottom_pit < int(buffer_.paragraphs().size())) {
710 dit = doc_iterator_begin(buffer_.inset());
712 dit.pit() = bottom_pit;
713 dit.pos() = min(bottom_pos, dit.paragraph().size());
718 // Note: only bottom (document) level pit is set.
720 // set the current font.
721 d->cursor_.setCurrentFont();
722 // To center the screen on this new position we need the
723 // paragraph position which is computed at draw() time.
724 // So we need a redraw!
734 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
736 if (lyxrc.rtl_support) {
737 if (d->cursor_.real_current_font.isRightToLeft()) {
738 if (d->intl_.keymap == Intl::PRIMARY)
739 d->intl_.keyMapSec();
741 if (d->intl_.keymap == Intl::SECONDARY)
742 d->intl_.keyMapPrim();
746 d->intl_.getTransManager().translateAndInsert(c, t, cur);
750 int BufferView::workWidth() const
756 void BufferView::showCursor()
758 showCursor(d->cursor_);
762 void BufferView::showCursor(DocIterator const & dit)
764 // We are not properly started yet, delay until resizing is
769 LYXERR(Debug::SCROLLING, "recentering!");
771 CursorSlice const & bot = dit.bottom();
772 TextMetrics & tm = d->text_metrics_[bot.text()];
774 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
775 int bot_pit = bot.pit();
776 if (bot_pit > max_pit) {
777 // FIXME: Why does this happen?
778 LYXERR0("bottom pit is greater that max pit: "
779 << bot_pit << " > " << max_pit);
783 if (bot_pit == tm.first().first - 1)
784 tm.newParMetricsUp();
785 else if (bot_pit == tm.last().first + 1)
786 tm.newParMetricsDown();
788 if (tm.contains(bot_pit)) {
789 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
790 LASSERT(!pm.rows().empty(), /**/);
791 // FIXME: smooth scrolling doesn't work in mathed.
792 CursorSlice const & cs = dit.innerTextSlice();
793 int offset = coordOffset(dit, dit.boundary()).y_;
794 int ypos = pm.position() + offset;
795 Dimension const & row_dim =
796 pm.getRow(cs.pos(), dit.boundary()).dimension();
797 if (ypos - row_dim.ascent() < 0)
798 scrollUp(- ypos + row_dim.ascent());
799 else if (ypos + row_dim.descent() > height_)
800 scrollDown(ypos - height_ + row_dim.descent());
801 // else, nothing to do, the cursor is already visible so we just return.
805 // fix inline completion position
806 if (d->inlineCompletionPos_.fixIfBroken())
807 d->inlineCompletionPos_ = DocIterator();
809 tm.redoParagraph(bot_pit);
810 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
811 int offset = coordOffset(dit, dit.boundary()).y_;
813 d->anchor_pit_ = bot_pit;
814 CursorSlice const & cs = dit.innerTextSlice();
815 Dimension const & row_dim =
816 pm.getRow(cs.pos(), dit.boundary()).dimension();
818 if (d->anchor_pit_ == 0)
819 d->anchor_ypos_ = offset + pm.ascent();
820 else if (d->anchor_pit_ == max_pit)
821 d->anchor_ypos_ = height_ - offset - row_dim.descent();
823 d->anchor_ypos_ = defaultRowHeight() * 2 - offset - row_dim.descent();
830 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
834 Cursor & cur = d->cursor_;
836 switch (cmd.action) {
839 flag.enabled(buffer_.undo().hasUndoStack());
842 flag.enabled(buffer_.undo().hasRedoStack());
844 case LFUN_FILE_INSERT:
845 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
846 case LFUN_FILE_INSERT_PLAINTEXT:
847 case LFUN_BOOKMARK_SAVE:
848 // FIXME: Actually, these LFUNS should be moved to Text
849 flag.enabled(cur.inTexted());
851 case LFUN_FONT_STATE:
852 case LFUN_LABEL_INSERT:
853 case LFUN_INFO_INSERT:
854 case LFUN_INSET_EDIT:
855 case LFUN_PARAGRAPH_GOTO:
857 case LFUN_REFERENCE_NEXT:
859 case LFUN_WORD_REPLACE:
862 case LFUN_MARK_TOGGLE:
863 case LFUN_SCREEN_RECENTER:
864 case LFUN_BIBTEX_DATABASE_ADD:
865 case LFUN_BIBTEX_DATABASE_DEL:
866 case LFUN_STATISTICS:
870 case LFUN_NEXT_INSET_TOGGLE:
871 case LFUN_NEXT_INSET_MODIFY: {
872 // this is the real function we want to invoke
873 FuncCode const code =
874 (cmd.action == LFUN_NEXT_INSET_TOGGLE)
875 ? LFUN_INSET_TOGGLE : LFUN_INSET_MODIFY;
876 FuncRequest const tmpcmd = FuncRequest(code, cmd.argument());
877 // if there is an inset at cursor, see whether it
878 // handles the lfun, other start from scratch
879 Inset * inset = cur.nextInset();
880 if (!inset || !inset->getStatus(cur, tmpcmd, flag))
881 flag = lyx::getStatus(tmpcmd);
885 case LFUN_LABEL_GOTO: {
886 flag.enabled(!cmd.argument().empty()
887 || getInsetByCode<InsetRef>(cur, REF_CODE));
891 case LFUN_CHANGES_TRACK:
893 flag.setOnOff(buffer_.params().trackChanges);
896 case LFUN_CHANGES_OUTPUT:
898 flag.setOnOff(buffer_.params().outputChanges);
901 case LFUN_CHANGES_MERGE:
902 case LFUN_CHANGE_NEXT:
903 case LFUN_ALL_CHANGES_ACCEPT:
904 case LFUN_ALL_CHANGES_REJECT:
905 // TODO: context-sensitive enabling of LFUNs
906 // In principle, these command should only be enabled if there
907 // is a change in the document. However, without proper
908 // optimizations, this will inevitably result in poor performance.
912 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
913 flag.setOnOff(buffer_.params().compressed);
918 case LFUN_SCREEN_DOWN:
920 case LFUN_SCREEN_UP_SELECT:
921 case LFUN_SCREEN_DOWN_SELECT:
925 case LFUN_LAYOUT_TABULAR:
926 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
930 flag.enabled(!cur.inset().forceEmptyLayout(cur.idx()));
933 case LFUN_LAYOUT_PARAGRAPH:
934 flag.enabled(cur.inset().allowParagraphCustomization(cur.idx()));
937 case LFUN_INSET_SETTINGS: {
938 InsetCode code = cur.inset().lyxCode();
939 if (cmd.getArg(0) == insetName(code)) {
944 InsetCode next_code = cur.nextInset()
945 ? cur.nextInset()->lyxCode() : NO_CODE;
955 enable = (cmd.argument().empty() ||
956 cmd.getArg(0) == insetName(next_code));
961 flag.enabled(enable);
965 case LFUN_DIALOG_SHOW_NEW_INSET:
966 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
967 cur.inset().lyxCode() != LISTINGS_CODE);
968 if (cur.inset().lyxCode() == CAPTION_CODE) {
970 if (cur.inset().getStatus(cur, cmd, flag))
983 bool BufferView::dispatch(FuncRequest const & cmd)
985 //lyxerr << [ cmd = " << cmd << "]" << endl;
987 // Make sure that the cached BufferView is correct.
988 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
989 << " arg[" << to_utf8(cmd.argument()) << ']'
990 << " x[" << cmd.x << ']'
991 << " y[" << cmd.y << ']'
992 << " button[" << cmd.button() << ']');
994 Cursor & cur = d->cursor_;
996 switch (cmd.action) {
999 cur.message(_("Undo"));
1000 cur.clearSelection();
1001 if (!cur.textUndo())
1002 cur.message(_("No further undo information"));
1004 processUpdateFlags(Update::Force | Update::FitCursor);
1008 cur.message(_("Redo"));
1009 cur.clearSelection();
1010 if (!cur.textRedo())
1011 cur.message(_("No further redo information"));
1013 processUpdateFlags(Update::Force | Update::FitCursor);
1016 case LFUN_FONT_STATE:
1017 cur.message(cur.currentState());
1020 case LFUN_BOOKMARK_SAVE:
1021 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1024 case LFUN_LABEL_GOTO: {
1025 docstring label = cmd.argument();
1026 if (label.empty()) {
1028 getInsetByCode<InsetRef>(d->cursor_,
1031 label = inset->getParam("reference");
1032 // persistent=false: use temp_bookmark
1042 case LFUN_INSET_EDIT: {
1043 FuncRequest fr(cmd);
1044 // if there is an inset at cursor, see whether it
1046 Inset * inset = cur.nextInset();
1048 inset->dispatch(cur, fr);
1049 // if it did not work, try the underlying inset.
1050 if (!inset || !cur.result().dispatched())
1053 if (!cur.result().dispatched())
1054 // It did not work too; no action needed.
1058 case LFUN_PARAGRAPH_GOTO: {
1059 int const id = convert<int>(to_utf8(cmd.argument()));
1061 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1062 b = theBufferList().next(b)) {
1064 DocIterator dit = b->getParFromID(id);
1066 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1070 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1071 << " found in buffer `"
1072 << b->absFileName() << "'.");
1074 if (b == &buffer_) {
1077 processUpdateFlags(Update::Force | Update::FitCursor);
1079 // Switch to other buffer view and resend cmd
1080 theLyXFunc().dispatch(FuncRequest(
1081 LFUN_BUFFER_SWITCH, b->absFileName()));
1082 theLyXFunc().dispatch(cmd);
1089 case LFUN_NOTE_NEXT:
1090 gotoInset(this, NOTE_CODE, false);
1093 case LFUN_REFERENCE_NEXT: {
1094 vector<InsetCode> tmp;
1095 tmp.push_back(LABEL_CODE);
1096 tmp.push_back(REF_CODE);
1097 gotoInset(this, tmp, true);
1101 case LFUN_CHANGES_TRACK:
1102 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1105 case LFUN_CHANGES_OUTPUT:
1106 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1107 if (buffer_.params().outputChanges) {
1108 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1109 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1110 LaTeXFeatures::isAvailable("xcolor");
1112 if (!dvipost && !xcolorsoul) {
1113 Alert::warning(_("Changes not shown in LaTeX output"),
1114 _("Changes will not be highlighted in LaTeX output, "
1115 "because neither dvipost nor xcolor/soul are installed.\n"
1116 "Please install these packages or redefine "
1117 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1118 } else if (!xcolorsoul) {
1119 Alert::warning(_("Changes not shown in LaTeX output"),
1120 _("Changes will not be highlighted in LaTeX output "
1121 "when using pdflatex, because xcolor and soul are not installed.\n"
1122 "Please install both packages or redefine "
1123 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1128 case LFUN_CHANGE_NEXT:
1129 findNextChange(this);
1132 case LFUN_CHANGES_MERGE:
1133 if (findNextChange(this))
1134 showDialog("changes");
1137 case LFUN_ALL_CHANGES_ACCEPT:
1138 // select complete document
1139 d->cursor_.reset(buffer_.inset());
1140 d->cursor_.selHandle(true);
1141 buffer_.text().cursorBottom(d->cursor_);
1142 // accept everything in a single step to support atomic undo
1143 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1146 case LFUN_ALL_CHANGES_REJECT:
1147 // select complete document
1148 d->cursor_.reset(buffer_.inset());
1149 d->cursor_.selHandle(true);
1150 buffer_.text().cursorBottom(d->cursor_);
1151 // reject everything in a single step to support atomic undo
1152 // Note: reject does not work recursively; the user may have to repeat the operation
1153 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1156 case LFUN_WORD_FIND: {
1157 FuncRequest req = cmd;
1158 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1159 req = d->search_request_cache_;
1160 if (find(this, req))
1163 message(_("String not found!"));
1164 d->search_request_cache_ = req;
1168 case LFUN_WORD_REPLACE: {
1169 bool has_deleted = false;
1170 if (cur.selection()) {
1171 DocIterator beg = cur.selectionBegin();
1172 DocIterator end = cur.selectionEnd();
1173 if (beg.pit() == end.pit()) {
1174 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1175 if (cur.paragraph().isDeleted(p))
1180 replace(this, cmd, has_deleted);
1185 cur.clearSelection();
1187 cur.message(from_utf8(N_("Mark off")));
1191 cur.clearSelection();
1194 cur.message(from_utf8(N_("Mark on")));
1197 case LFUN_MARK_TOGGLE:
1198 cur.clearSelection();
1201 cur.message(from_utf8(N_("Mark removed")));
1204 cur.message(from_utf8(N_("Mark set")));
1209 case LFUN_SCREEN_RECENTER:
1213 case LFUN_BIBTEX_DATABASE_ADD: {
1214 Cursor tmpcur = d->cursor_;
1215 findInset(tmpcur, BIBTEX_CODE, false);
1216 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1219 if (inset->addDatabase(cmd.argument()))
1220 buffer_.updateBibfilesCache();
1225 case LFUN_BIBTEX_DATABASE_DEL: {
1226 Cursor tmpcur = d->cursor_;
1227 findInset(tmpcur, BIBTEX_CODE, false);
1228 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1231 if (inset->delDatabase(cmd.argument()))
1232 buffer_.updateBibfilesCache();
1237 case LFUN_STATISTICS: {
1238 DocIterator from, to;
1239 if (cur.selection()) {
1240 from = cur.selectionBegin();
1241 to = cur.selectionEnd();
1243 from = doc_iterator_begin(buffer_.inset());
1244 to = doc_iterator_end(buffer_.inset());
1246 int const words = countWords(from, to);
1247 int const chars = countChars(from, to, false);
1248 int const chars_blanks = countChars(from, to, true);
1250 if (cur.selection())
1251 message = _("Statistics for the selection:");
1253 message = _("Statistics for the document:");
1256 message += bformat(_("%1$d words"), words);
1258 message += _("One word");
1260 if (chars_blanks != 1)
1261 message += bformat(_("%1$d characters (including blanks)"),
1264 message += _("One character (including blanks)");
1267 message += bformat(_("%1$d characters (excluding blanks)"),
1270 message += _("One character (excluding blanks)");
1272 Alert::information(_("Statistics"), message);
1276 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1277 // turn compression on/off
1278 buffer_.params().compressed = !buffer_.params().compressed;
1281 case LFUN_NEXT_INSET_TOGGLE: {
1282 // this is the real function we want to invoke
1283 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1284 // if there is an inset at cursor, see whether it
1286 Inset * inset = cur.nextInset();
1288 if (inset->isActive()) {
1289 Cursor tmpcur = cur;
1290 tmpcur.pushBackward(*inset);
1291 inset->dispatch(tmpcur, tmpcmd);
1292 if (tmpcur.result().dispatched()) {
1295 } else if (inset->editable() == Inset::IS_EDITABLE) {
1296 inset->edit(cur, true);
1299 // if it did not work, try the underlying inset.
1300 if (!inset || !cur.result().dispatched())
1301 cur.dispatch(tmpcmd);
1303 if (!cur.result().dispatched())
1304 // It did not work too; no action needed.
1306 cur.clearSelection();
1307 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1311 case LFUN_NEXT_INSET_MODIFY: {
1312 // this is the real function we want to invoke
1313 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_MODIFY, cmd.argument());
1314 // if there is an inset at cursor, see whether it
1316 Inset * inset = cur.nextInset();
1318 inset->dispatch(cur, tmpcmd);
1319 // if it did not work, try the underlying inset.
1320 if (!inset || !cur.result().dispatched())
1321 cur.dispatch(tmpcmd);
1323 if (!cur.result().dispatched())
1324 // It did not work too; no action needed.
1326 cur.clearSelection();
1327 processUpdateFlags(Update::Force | Update::FitCursor);
1331 case LFUN_SCREEN_UP:
1332 case LFUN_SCREEN_DOWN: {
1333 Point p = getPos(cur, cur.boundary());
1334 if (p.y_ < 0 || p.y_ > height_) {
1335 // The cursor is off-screen so recenter before proceeding.
1337 p = getPos(cur, cur.boundary());
1339 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1340 cur.reset(buffer_.inset());
1341 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1342 //FIXME: what to do with cur.x_target()?
1351 case LFUN_SCREEN_UP_SELECT: {
1352 cur.selHandle(true);
1353 if (isTopScreen()) {
1354 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1358 int y = getPos(cur, cur.boundary()).y_;
1359 int const ymin = y - height_ + defaultRowHeight();
1360 while (y > ymin && cur.up())
1361 y = getPos(cur, cur.boundary()).y_;
1364 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1368 case LFUN_SCREEN_DOWN_SELECT: {
1369 cur.selHandle(true);
1370 if (isBottomScreen()) {
1371 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1375 int y = getPos(cur, cur.boundary()).y_;
1376 int const ymax = y + height_ - defaultRowHeight();
1377 while (y < ymax && cur.down())
1378 y = getPos(cur, cur.boundary()).y_;
1381 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1393 docstring const BufferView::requestSelection()
1395 Cursor & cur = d->cursor_;
1397 if (!cur.selection()) {
1398 d->xsel_cache_.set = false;
1402 if (!d->xsel_cache_.set ||
1403 cur.top() != d->xsel_cache_.cursor ||
1404 cur.anchor_.top() != d->xsel_cache_.anchor)
1406 d->xsel_cache_.cursor = cur.top();
1407 d->xsel_cache_.anchor = cur.anchor_.top();
1408 d->xsel_cache_.set = cur.selection();
1409 return cur.selectionAsString(false);
1415 void BufferView::clearSelection()
1417 d->cursor_.clearSelection();
1418 // Clear the selection buffer. Otherwise a subsequent
1419 // middle-mouse-button paste would use the selection buffer,
1420 // not the more current external selection.
1421 cap::clearSelection();
1422 d->xsel_cache_.set = false;
1423 // The buffer did not really change, but this causes the
1424 // redraw we need because we cleared the selection above.
1429 void BufferView::resize(int width, int height)
1431 // Update from work area
1435 // Clear the paragraph height cache.
1436 d->par_height_.clear();
1437 // Redo the metrics.
1442 Inset const * BufferView::getCoveringInset(Text const & text,
1445 TextMetrics & tm = d->text_metrics_[&text];
1446 Inset * inset = tm.checkInsetHit(x, y);
1450 if (!inset->descendable())
1451 // No need to go further down if the inset is not
1455 size_t cell_number = inset->nargs();
1456 // Check all the inner cell.
1457 for (size_t i = 0; i != cell_number; ++i) {
1458 Text const * inner_text = inset->getText(i);
1461 Inset const * inset_deeper =
1462 getCoveringInset(*inner_text, x, y);
1464 return inset_deeper;
1472 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1474 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1476 // This is only called for mouse related events including
1477 // LFUN_FILE_OPEN generated by drag-and-drop.
1478 FuncRequest cmd = cmd0;
1480 Cursor old = cursor();
1482 cur.push(buffer_.inset());
1483 cur.selection() = d->cursor_.selection();
1485 // Either the inset under the cursor or the
1486 // surrounding Text will handle this event.
1488 // make sure we stay within the screen...
1489 cmd.y = min(max(cmd.y, -1), height_);
1491 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1493 // Get inset under mouse, if there is one.
1494 Inset const * covering_inset =
1495 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1496 if (covering_inset == d->last_inset_)
1497 // Same inset, no need to do anything...
1500 bool need_redraw = false;
1501 // const_cast because of setMouseHover().
1502 Inset * inset = const_cast<Inset *>(covering_inset);
1504 // Remove the hint on the last hovered inset (if any).
1505 need_redraw |= d->last_inset_->setMouseHover(false);
1507 // Highlighted the newly hovered inset (if any).
1508 need_redraw |= inset->setMouseHover(true);
1509 d->last_inset_ = inset;
1513 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1514 << cmd.x << ", " << cmd.y << ")");
1516 d->update_strategy_ = DecorationUpdate;
1518 // This event (moving without mouse click) is not passed further.
1519 // This should be changed if it is further utilized.
1524 // Build temporary cursor.
1525 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1527 // Put anchor at the same position.
1530 // Try to dispatch to an non-editable inset near this position
1531 // via the temp cursor. If the inset wishes to change the real
1532 // cursor it has to do so explicitly by using
1533 // cur.bv().cursor() = cur; (or similar)
1535 inset->dispatch(cur, cmd);
1537 // Now dispatch to the temporary cursor. If the real cursor should
1538 // be modified, the inset's dispatch has to do so explicitly.
1539 if (!inset || !cur.result().dispatched())
1542 // Notify left insets
1545 bool badcursor = notifyCursorLeaves(old, cur);
1547 cursor().fixIfBroken();
1550 // Do we have a selection?
1551 theSelection().haveSelection(cursor().selection());
1553 // If the command has been dispatched,
1554 if (cur.result().dispatched() || cur.result().update())
1555 processUpdateFlags(cur.result().update());
1559 void BufferView::lfunScroll(FuncRequest const & cmd)
1561 string const scroll_type = cmd.getArg(0);
1562 int const scroll_step =
1563 (scroll_type == "line") ? d->scrollbarParameters_.single_step
1564 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
1565 if (scroll_step == 0)
1567 string const scroll_quantity = cmd.getArg(1);
1568 if (scroll_quantity == "up")
1569 scrollUp(scroll_step);
1570 else if (scroll_quantity == "down")
1571 scrollDown(scroll_step);
1573 int const scroll_value = convert<int>(scroll_quantity);
1575 scroll(scroll_step * scroll_value);
1580 void BufferView::scroll(int y)
1589 void BufferView::scrollDown(int offset)
1591 Text * text = &buffer_.text();
1592 TextMetrics & tm = d->text_metrics_[text];
1593 int ymax = height_ + offset;
1595 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1596 int bottom_pos = last.second->position() + last.second->descent();
1597 if (last.first + 1 == int(text->paragraphs().size())) {
1598 if (bottom_pos <= height_)
1600 offset = min(offset, bottom_pos - height_);
1603 if (bottom_pos > ymax)
1605 tm.newParMetricsDown();
1607 d->anchor_ypos_ -= offset;
1613 void BufferView::scrollUp(int offset)
1615 Text * text = &buffer_.text();
1616 TextMetrics & tm = d->text_metrics_[text];
1617 int ymin = - offset;
1619 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1620 int top_pos = first.second->position() - first.second->ascent();
1621 if (first.first == 0) {
1624 offset = min(offset, - top_pos);
1629 tm.newParMetricsUp();
1631 d->anchor_ypos_ += offset;
1637 void BufferView::setCursorFromRow(int row)
1642 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1644 d->cursor_.reset(buffer_.inset());
1646 buffer_.text().setCursor(d->cursor_, 0, 0);
1648 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1652 void BufferView::gotoLabel(docstring const & label)
1654 Toc & toc = buffer().tocBackend().toc("label");
1655 TocIterator toc_it = toc.begin();
1656 TocIterator end = toc.end();
1657 for (; toc_it != end; ++toc_it) {
1658 if (label == toc_it->str())
1659 dispatch(toc_it->action());
1661 //FIXME: We could do a bit more searching thanks to this:
1662 //InsetLabel const * inset = buffer_.insetLabel(label);
1666 TextMetrics const & BufferView::textMetrics(Text const * t) const
1668 return const_cast<BufferView *>(this)->textMetrics(t);
1672 TextMetrics & BufferView::textMetrics(Text const * t)
1674 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1675 if (tmc_it == d->text_metrics_.end()) {
1676 tmc_it = d->text_metrics_.insert(
1677 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1679 return tmc_it->second;
1683 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1686 return textMetrics(t).parMetrics(pit);
1690 int BufferView::workHeight() const
1696 void BufferView::setCursor(DocIterator const & dit)
1698 size_t const n = dit.depth();
1699 for (size_t i = 0; i < n; ++i)
1700 dit[i].inset().edit(d->cursor_, true);
1702 d->cursor_.setCursor(dit);
1703 d->cursor_.selection() = false;
1707 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1709 // Would be wrong to delete anything if we have a selection.
1710 if (cur.selection())
1713 bool need_anchor_change = false;
1714 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1715 need_anchor_change);
1717 if (need_anchor_change)
1725 updateLabels(buffer_);
1733 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1735 LASSERT(&cur.bv() == this, /**/);
1738 // this event will clear selection so we save selection for
1739 // persistent selection
1740 cap::saveSelection(cursor());
1742 // Has the cursor just left the inset?
1743 bool badcursor = false;
1744 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1746 d->cursor_.fixIfBroken();
1747 badcursor = notifyCursorLeaves(d->cursor_, cur);
1752 // FIXME: shift-mouse selection doesn't work well across insets.
1753 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1755 // do the dEPM magic if needed
1756 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1757 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1758 // the leftinset bool would not be necessary (badcursor instead).
1759 bool update = leftinset;
1760 if (!do_selection && !badcursor && d->cursor_.inTexted())
1761 update |= checkDepm(cur, d->cursor_);
1763 d->cursor_.setCursor(cur);
1764 d->cursor_.boundary(cur.boundary());
1766 d->cursor_.setSelection();
1768 d->cursor_.clearSelection();
1770 d->cursor_.finishUndo();
1771 d->cursor_.setCurrentFont();
1776 void BufferView::putSelectionAt(DocIterator const & cur,
1777 int length, bool backwards)
1779 d->cursor_.clearSelection();
1785 d->cursor_.pos() += length;
1786 d->cursor_.setSelection(d->cursor_, -length);
1788 d->cursor_.setSelection(d->cursor_, length);
1790 // Ensure a redraw happens in any case because the new selection could
1791 // possibly be on the same screen as the previous selection.
1792 processUpdateFlags(Update::Force | Update::FitCursor);
1796 Cursor & BufferView::cursor()
1802 Cursor const & BufferView::cursor() const
1808 pit_type BufferView::anchor_ref() const
1810 return d->anchor_pit_;
1814 bool BufferView::singleParUpdate()
1816 Text & buftext = buffer_.text();
1817 pit_type const bottom_pit = d->cursor_.bottom().pit();
1818 TextMetrics & tm = textMetrics(&buftext);
1819 int old_height = tm.parMetrics(bottom_pit).height();
1821 // make sure inline completion pointer is ok
1822 if (d->inlineCompletionPos_.fixIfBroken())
1823 d->inlineCompletionPos_ = DocIterator();
1825 // In Single Paragraph mode, rebreak only
1826 // the (main text, not inset!) paragraph containing the cursor.
1827 // (if this paragraph contains insets etc., rebreaking will
1828 // recursively descend)
1829 tm.redoParagraph(bottom_pit);
1830 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1831 if (pm.height() != old_height)
1832 // Paragraph height has changed so we cannot proceed to
1833 // the singlePar optimisation.
1836 d->update_strategy_ = SingleParUpdate;
1838 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1839 << " y2: " << pm.position() + pm.descent()
1840 << " pit: " << bottom_pit
1841 << " singlepar: 1");
1846 void BufferView::updateMetrics()
1848 Text & buftext = buffer_.text();
1849 pit_type const npit = int(buftext.paragraphs().size());
1851 // Clear out the position cache in case of full screen redraw,
1852 d->coord_cache_.clear();
1854 // Clear out paragraph metrics to avoid having invalid metrics
1855 // in the cache from paragraphs not relayouted below
1856 // The complete text metrics will be redone.
1857 d->text_metrics_.clear();
1859 TextMetrics & tm = textMetrics(&buftext);
1861 // make sure inline completion pointer is ok
1862 if (d->inlineCompletionPos_.fixIfBroken())
1863 d->inlineCompletionPos_ = DocIterator();
1865 if (d->anchor_pit_ >= npit)
1866 // The anchor pit must have been deleted...
1867 d->anchor_pit_ = npit - 1;
1869 // Rebreak anchor paragraph.
1870 tm.redoParagraph(d->anchor_pit_);
1871 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1874 if (d->anchor_pit_ == 0) {
1875 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
1877 // Complete buffer visible? Then it's easy.
1878 if (scrollRange == 0)
1879 d->anchor_ypos_ = anchor_pm.ascent();
1881 // FIXME: Some clever handling needed to show
1882 // the _first_ paragraph up to the top if the cursor is
1883 // in the first line.
1885 anchor_pm.setPosition(d->anchor_ypos_);
1887 LYXERR(Debug::PAINTING, "metrics: "
1888 << " anchor pit = " << d->anchor_pit_
1889 << " anchor ypos = " << d->anchor_ypos_);
1891 // Redo paragraphs above anchor if necessary.
1892 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1893 // We are now just above the anchor paragraph.
1894 pit_type pit1 = d->anchor_pit_ - 1;
1895 for (; pit1 >= 0 && y1 >= 0; --pit1) {
1896 tm.redoParagraph(pit1);
1897 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1899 // Save the paragraph position in the cache.
1904 // Redo paragraphs below the anchor if necessary.
1905 int y2 = d->anchor_ypos_ + anchor_pm.descent();
1906 // We are now just below the anchor paragraph.
1907 pit_type pit2 = d->anchor_pit_ + 1;
1908 for (; pit2 < npit && y2 <= height_; ++pit2) {
1909 tm.redoParagraph(pit2);
1910 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1912 // Save the paragraph position in the cache.
1917 LYXERR(Debug::PAINTING, "Metrics: "
1918 << " anchor pit = " << d->anchor_pit_
1919 << " anchor ypos = " << d->anchor_ypos_
1922 << " pit1 = " << pit1
1923 << " pit2 = " << pit2);
1925 d->update_strategy_ = FullScreenUpdate;
1927 if (lyxerr.debugging(Debug::WORKAREA)) {
1928 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1929 d->coord_cache_.dump();
1934 void BufferView::insertLyXFile(FileName const & fname)
1936 LASSERT(d->cursor_.inTexted(), /**/);
1938 // Get absolute path of file and add ".lyx"
1939 // to the filename if necessary
1940 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1942 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1943 // emit message signal.
1944 message(bformat(_("Inserting document %1$s..."), disp_fn));
1947 Buffer buf("", false);
1948 if (buf.loadLyXFile(filename)) {
1949 ErrorList & el = buffer_.errorList("Parse");
1950 // Copy the inserted document error list into the current buffer one.
1951 el = buf.errorList("Parse");
1952 buffer_.undo().recordUndo(d->cursor_);
1953 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1954 buf.params().documentClassPtr(), el);
1955 res = _("Document %1$s inserted.");
1957 res = _("Could not insert document %1$s");
1962 // emit message signal.
1963 message(bformat(res, disp_fn));
1964 buffer_.errors("Parse");
1968 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1974 // Addup contribution of nested insets, from inside to outside,
1975 // keeping the outer paragraph for a special handling below
1976 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1977 CursorSlice const & sl = dit[i];
1981 // get relative position inside sl.inset()
1982 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1984 // Make relative position inside of the edited inset relative to sl.inset()
1988 // In case of an RTL inset, the edited inset will be positioned to the left
1991 bool boundary_i = boundary && i + 1 == dit.depth();
1992 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1997 // remember width for the case that sl.inset() is positioned in an RTL inset
1998 if (i && dit[i - 1].text()) {
1999 // If this Inset is inside a Text Inset, retrieve the Dimension
2000 // from the containing text instead of using Inset::dimension() which
2001 // might not be implemented.
2002 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2003 // elimination of Inset::dim_ cache. This coordOffset() method needs
2004 // to be rewritten in light of the new design.
2005 Dimension const & dim = parMetrics(dit[i - 1].text(),
2006 dit[i - 1].pit()).insetDimension(&sl.inset());
2009 Dimension const dim = sl.inset().dimension(*this);
2013 //lyxerr << "Cursor::getPos, i: "
2014 // << i << " x: " << xx << " y: " << y << endl;
2017 // Add contribution of initial rows of outermost paragraph
2018 CursorSlice const & sl = dit[0];
2019 TextMetrics const & tm = textMetrics(sl.text());
2020 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2021 LASSERT(!pm.rows().empty(), /**/);
2022 y -= pm.rows()[0].ascent();
2024 // FIXME: document this mess
2026 if (sl.pos() > 0 && dit.depth() == 1) {
2028 if (pos && boundary)
2030 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2031 rend = pm.pos2row(pos);
2033 rend = pm.pos2row(sl.pos());
2035 size_t rend = pm.pos2row(sl.pos());
2037 for (size_t rit = 0; rit != rend; ++rit)
2038 y += pm.rows()[rit].height();
2039 y += pm.rows()[rend].ascent();
2041 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2043 // Make relative position from the nested inset now bufferview absolute.
2044 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2047 // In the RTL case place the nested inset at the left of the cursor in
2048 // the outer paragraph
2049 bool boundary_1 = boundary && 1 == dit.depth();
2050 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2058 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2060 CursorSlice const & bot = dit.bottom();
2061 TextMetrics const & tm = textMetrics(bot.text());
2062 if (!tm.contains(bot.pit()))
2063 return Point(-1, -1);
2065 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2066 p.y_ += tm.parMetrics(bot.pit()).position();
2071 void BufferView::draw(frontend::Painter & pain)
2073 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2074 Text & text = buffer_.text();
2075 TextMetrics const & tm = d->text_metrics_[&text];
2076 int const y = tm.first().second->position();
2077 PainterInfo pi(this, pain);
2079 switch (d->update_strategy_) {
2081 case NoScreenUpdate:
2082 // If no screen painting is actually needed, only some the different
2083 // coordinates of insets and paragraphs needs to be updated.
2084 pi.full_repaint = true;
2085 pi.pain.setDrawingEnabled(false);
2089 case SingleParUpdate:
2090 pi.full_repaint = false;
2091 // In general, only the current row of the outermost paragraph
2092 // will be redrawn. Particular cases where selection spans
2093 // multiple paragraph are correctly detected in TextMetrics.
2097 case DecorationUpdate:
2098 // FIXME: We should also distinguish DecorationUpdate to avoid text
2099 // drawing if possible. This is not possible to do easily right now
2100 // because of the single backing pixmap.
2102 case FullScreenUpdate:
2103 // The whole screen, including insets, will be refreshed.
2104 pi.full_repaint = true;
2106 // Clear background.
2107 pain.fillRectangle(0, 0, width_, height_,
2108 buffer_.inset().backgroundColor());
2113 // and possibly grey out below
2114 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2115 int const y2 = lastpm.second->position() + lastpm.second->descent();
2117 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2120 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2122 // The scrollbar needs an update.
2125 // Normalize anchor for next time
2126 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2127 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2128 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2129 ParagraphMetrics const & pm = tm.parMetrics(pit);
2130 if (pm.position() + pm.descent() > 0) {
2131 d->anchor_pit_ = pit;
2132 d->anchor_ypos_ = pm.position();
2136 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2137 << " anchor ypos = " << d->anchor_ypos_);
2141 void BufferView::message(docstring const & msg)
2144 d->gui_->message(msg);
2148 void BufferView::showDialog(string const & name)
2151 d->gui_->showDialog(name, string());
2155 void BufferView::showDialog(string const & name,
2156 string const & data, Inset * inset)
2159 d->gui_->showDialog(name, data, inset);
2163 void BufferView::updateDialog(string const & name, string const & data)
2166 d->gui_->updateDialog(name, data);
2170 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2176 // FIXME: Move this out of BufferView again
2177 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2179 if (!fname.isReadableFile()) {
2180 docstring const error = from_ascii(strerror(errno));
2181 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2182 docstring const text =
2183 bformat(_("Could not read the specified document\n"
2184 "%1$s\ndue to the error: %2$s"), file, error);
2185 Alert::error(_("Could not read file"), text);
2189 if (!fname.isReadableFile()) {
2190 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2191 docstring const text =
2192 bformat(_("%1$s\n is not readable."), file);
2193 Alert::error(_("Could not open file"), text);
2197 // FIXME UNICODE: We don't know the encoding of the file
2198 docstring file_content = fname.fileContents("UTF-8");
2199 if (file_content.empty()) {
2200 Alert::error(_("Reading not UTF-8 encoded file"),
2201 _("The file is not UTF-8 encoded.\n"
2202 "It will be read as local 8Bit-encoded.\n"
2203 "If this does not give the correct result\n"
2204 "then please change the encoding of the file\n"
2205 "to UTF-8 with a program other than LyX.\n"));
2206 file_content = fname.fileContents("local8bit");
2209 return normalize_c(file_content);
2213 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2215 docstring const tmpstr = contentsOfPlaintextFile(f);
2220 Cursor & cur = cursor();
2221 cap::replaceSelection(cur);
2222 buffer_.undo().recordUndo(cur);
2224 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2226 cur.innerText()->insertStringAsLines(cur, tmpstr);
2233 docstring const & BufferView::inlineCompletion() const
2235 return d->inlineCompletion_;
2239 size_t const & BufferView::inlineCompletionUniqueChars() const
2241 return d->inlineCompletionUniqueChars_;
2245 DocIterator const & BufferView::inlineCompletionPos() const
2247 return d->inlineCompletionPos_;
2251 bool samePar(DocIterator const & a, DocIterator const & b)
2253 if (a.empty() && b.empty())
2255 if (a.empty() || b.empty())
2257 return &a.innerParagraph() == &b.innerParagraph();
2261 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2262 docstring const & completion, size_t uniqueChars)
2264 uniqueChars = min(completion.size(), uniqueChars);
2265 bool changed = d->inlineCompletion_ != completion
2266 || d->inlineCompletionUniqueChars_ != uniqueChars;
2267 bool singlePar = true;
2268 d->inlineCompletion_ = completion;
2269 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2271 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2274 DocIterator const & old = d->inlineCompletionPos_;
2276 //lyxerr << "inlineCompletionPos changed" << std::endl;
2277 // old or pos are in another paragraph?
2278 if ((!samePar(cur, pos) && !pos.empty())
2279 || (!samePar(cur, old) && !old.empty())) {
2281 //lyxerr << "different paragraph" << std::endl;
2283 d->inlineCompletionPos_ = pos;
2288 if (singlePar && !(cur.disp_.update() & Update::Force))
2289 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2291 cur.updateFlags(cur.disp_.update() | Update::Force);