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 "EmbeddedFiles.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"
53 #include "WordLangTuple.h"
55 #include "insets/InsetBibtex.h"
56 #include "insets/InsetCommand.h" // ChangeRefs
57 #include "insets/InsetRef.h"
58 #include "insets/InsetText.h"
60 #include "frontends/alert.h"
61 #include "frontends/Application.h"
62 #include "frontends/Delegates.h"
63 #include "frontends/FontMetrics.h"
64 #include "frontends/Painter.h"
65 #include "frontends/Selection.h"
67 #include "graphics/Previews.h"
69 #include "support/convert.h"
70 #include "support/debug.h"
71 #include "support/ExceptionMessage.h"
72 #include "support/filetools.h"
73 #include "support/gettext.h"
74 #include "support/lstrings.h"
75 #include "support/Package.h"
76 #include "support/types.h"
85 using namespace lyx::support;
89 namespace Alert = frontend::Alert;
93 /// Return an inset of this class if it exists at the current cursor position
95 T * getInsetByCode(Cursor const & cur, InsetCode code)
98 Inset * inset = it.nextInset();
99 if (inset && inset->lyxCode() == code)
100 return static_cast<T*>(inset);
105 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
108 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
109 docstring const & contents)
111 DocIterator tmpdit = dit;
114 Inset const * inset = tmpdit.nextInset();
116 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
117 && (contents.empty() ||
118 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
122 tmpdit.forwardInset();
129 /// Looks for next inset with one of the given codes.
130 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
134 DocIterator tmpdit = dit;
135 tmpdit.forwardInset();
140 Inset const * inset = tmpdit.nextInset();
142 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
143 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
147 if (!findNextInset(tmpdit, codes, contents)) {
148 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
149 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
150 if (!findNextInset(tmpdit, codes, contents))
161 /// Looks for next inset with the given code
162 void findInset(DocIterator & dit, InsetCode code, bool same_content)
164 findInset(dit, vector<InsetCode>(1, code), same_content);
168 /// Moves cursor to the next inset with one of the given codes.
169 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
172 Cursor tmpcur = bv->cursor();
173 if (!findInset(tmpcur, codes, same_content)) {
174 bv->cursor().message(_("No more insets"));
178 tmpcur.clearSelection();
179 bv->setCursor(tmpcur);
184 /// Moves cursor to the next inset with given code.
185 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
187 gotoInset(bv, vector<InsetCode>(1, code), same_content);
191 /// A map from a Text to the associated text metrics
192 typedef map<Text const *, TextMetrics> TextMetricsCache;
194 enum ScreenUpdateStrategy {
204 /////////////////////////////////////////////////////////////////////
208 /////////////////////////////////////////////////////////////////////
210 struct BufferView::Private
212 Private(BufferView & bv): wh_(0), cursor_(bv),
213 anchor_pit_(0), anchor_ypos_(0),
214 last_inset_(0), gui_(0)
218 ScrollbarParameters scrollbarParameters_;
220 ScreenUpdateStrategy update_strategy_;
222 CoordCache coord_cache_;
224 /// Estimated average par height for scrollbar.
226 /// this is used to handle XSelection events in the right manner.
235 pit_type anchor_pit_;
239 vector<int> par_height_;
242 DocIterator inlineCompletionPos;
244 docstring inlineCompletion;
246 size_t inlineCompletionUniqueChars;
248 /// keyboard mapping object.
251 /// last visited inset.
252 /** kept to send setMouseHover(false).
253 * Not owned, so don't delete.
257 mutable TextMetricsCache text_metrics_;
260 /** Not owned, so don't delete.
262 frontend::GuiBufferViewDelegate * gui_;
266 BufferView::BufferView(Buffer & buf)
267 : width_(0), height_(0), full_screen_(false), buffer_(buf), d(new Private(*this))
269 d->xsel_cache_.set = false;
270 d->intl_.initKeyMapper(lyxrc.use_kbmap);
272 d->cursor_.push(buffer_.inset());
273 d->cursor_.resetAnchor();
274 d->cursor_.setCurrentFont();
276 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
277 graphics::Previews::get().generateBufferPreviews(buffer_);
281 BufferView::~BufferView()
283 // current buffer is going to be switched-off, save cursor pos
284 // Ideally, the whole cursor stack should be saved, but session
285 // currently can only handle bottom (whole document) level pit and pos.
286 // That is to say, if a cursor is in a nested inset, it will be
287 // restore to the left of the top level inset.
288 LastFilePosSection::FilePos fp;
289 fp.pit = d->cursor_.bottom().pit();
290 fp.pos = d->cursor_.bottom().pos();
291 LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
297 int BufferView::rightMargin() const
299 // The additional test for the case the outliner is opened.
301 !lyxrc.full_screen_limit ||
302 width_ < lyxrc.full_screen_width + 20)
305 return (width_ - lyxrc.full_screen_width) / 2;
309 int BufferView::leftMargin() const
311 return rightMargin();
315 Intl & BufferView::getIntl()
321 Intl const & BufferView::getIntl() const
327 CoordCache & BufferView::coordCache()
329 return d->coord_cache_;
333 CoordCache const & BufferView::coordCache() const
335 return d->coord_cache_;
339 Buffer & BufferView::buffer()
345 Buffer const & BufferView::buffer() const
351 bool BufferView::fitCursor()
353 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
354 frontend::FontMetrics const & fm =
355 theFontMetrics(d->cursor_.getFont().fontInfo());
356 int const asc = fm.maxAscent();
357 int const des = fm.maxDescent();
358 Point const p = getPos(d->cursor_, d->cursor_.boundary());
359 if (p.y_ - asc >= 0 && p.y_ + des < height_)
366 void BufferView::processUpdateFlags(Update::flags flags)
368 // last_inset_ points to the last visited inset. This pointer may become
369 // invalid because of keyboard editing. Since all such operations
370 // causes screen update(), I reset last_inset_ to avoid such a problem.
372 // This is close to a hot-path.
373 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
374 << "[fitcursor = " << (flags & Update::FitCursor)
375 << ", forceupdate = " << (flags & Update::Force)
376 << ", singlepar = " << (flags & Update::SinglePar)
377 << "] buffer: " << &buffer_);
379 buffer_.updateMacros();
381 // Now do the first drawing step if needed. This consists on updating
382 // the CoordCache in updateMetrics().
383 // The second drawing step is done in WorkArea::redraw() if needed.
385 // Case when no explicit update is requested.
387 // no need to redraw anything.
388 d->update_strategy_ = NoScreenUpdate;
392 if (flags == Update::Decoration) {
393 d->update_strategy_ = DecorationUpdate;
398 if (flags == Update::FitCursor
399 || flags == (Update::Decoration | Update::FitCursor)) {
400 // tell the frontend to update the screen if needed.
405 if (flags & Update::Decoration) {
406 d->update_strategy_ = DecorationUpdate;
410 // no screen update is needed.
411 d->update_strategy_ = NoScreenUpdate;
415 bool const full_metrics = flags & Update::Force || !singleParUpdate();
418 // We have to update the full screen metrics.
421 if (!(flags & Update::FitCursor)) {
422 // Nothing to do anymore. Trigger a redraw and return
427 // updateMetrics() does not update paragraph position
428 // This is done at draw() time. So we need a redraw!
432 // The cursor is off screen so ensure it is visible.
439 void BufferView::updateScrollbar()
444 // We prefer fixed size line scrolling.
445 d->scrollbarParameters_.single_step = defaultRowHeight();
446 // We prefer full screen page scrolling.
447 d->scrollbarParameters_.page_step = height_;
449 Text & t = buffer_.text();
450 TextMetrics & tm = d->text_metrics_[&t];
452 LYXERR(Debug::GUI, " Updating scrollbar: height: "
453 << t.paragraphs().size()
454 << " curr par: " << d->cursor_.bottom().pit()
455 << " default height " << defaultRowHeight());
457 size_t const parsize = t.paragraphs().size();
458 if (d->par_height_.size() != parsize) {
459 d->par_height_.clear();
460 // FIXME: We assume a default paragraph height of 2 rows. This
461 // should probably be pondered with the screen width.
462 d->par_height_.resize(parsize, defaultRowHeight() * 2);
465 // Look at paragraph heights on-screen
466 pair<pit_type, ParagraphMetrics const *> first = tm.first();
467 pair<pit_type, ParagraphMetrics const *> last = tm.last();
468 for (pit_type pit = first.first; pit <= last.first; ++pit) {
469 d->par_height_[pit] = tm.parMetrics(pit).height();
470 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
471 << d->par_height_[pit]);
474 int top_pos = first.second->position() - first.second->ascent();
475 int bottom_pos = last.second->position() + last.second->descent();
476 bool first_visible = first.first == 0 && top_pos >= 0;
477 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
478 if (first_visible && last_visible) {
479 d->scrollbarParameters_.min = 0;
480 d->scrollbarParameters_.max = 0;
484 d->scrollbarParameters_.min = top_pos;
485 for (size_t i = 0; i != size_t(first.first); ++i)
486 d->scrollbarParameters_.min -= d->par_height_[i];
487 d->scrollbarParameters_.max = bottom_pos;
488 for (size_t i = last.first + 1; i != parsize; ++i)
489 d->scrollbarParameters_.max += d->par_height_[i];
491 d->scrollbarParameters_.position = 0;
492 // The reference is the top position so we remove one page.
493 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
497 ScrollbarParameters const & BufferView::scrollbarParameters() const
499 return d->scrollbarParameters_;
503 docstring BufferView::toolTip(int x, int y) const
505 // Get inset under mouse, if there is one.
506 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
508 // No inset, no tooltip...
510 return covering_inset->toolTip(*this, x, y);
514 docstring BufferView::contextMenu(int x, int y) const
516 // Get inset under mouse, if there is one.
517 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
519 return covering_inset->contextMenu(*this, x, y);
521 // FIXME: Do something more elaborate here.
522 return from_ascii("edit");
526 void BufferView::scrollDocView(int value)
528 int const offset = value - d->scrollbarParameters_.position;
529 // If the offset is less than 2 screen height, prefer to scroll instead.
530 if (abs(offset) <= 2 * height_) {
535 // cut off at the top
536 if (value <= d->scrollbarParameters_.min) {
537 DocIterator dit = doc_iterator_begin(buffer_.inset());
539 LYXERR(Debug::SCROLLING, "scroll to top");
543 // cut off at the bottom
544 if (value >= d->scrollbarParameters_.max) {
545 DocIterator dit = doc_iterator_end(buffer_.inset());
548 LYXERR(Debug::SCROLLING, "scroll to bottom");
552 // find paragraph at target position
553 int par_pos = d->scrollbarParameters_.min;
555 for (; i != int(d->par_height_.size()); ++i) {
556 par_pos += d->par_height_[i];
557 if (par_pos >= value)
561 if (par_pos < value) {
562 // It seems we didn't find the correct pit so stay on the safe side and
564 LYXERR0("scrolling position not found!");
565 scrollDocView(d->scrollbarParameters_.max);
569 DocIterator dit = doc_iterator_begin(buffer_.inset());
571 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
576 // FIXME: this method is not working well.
577 void BufferView::setCursorFromScrollbar()
579 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
581 int const height = 2 * defaultRowHeight();
582 int const first = height;
583 int const last = height_ - height;
584 Cursor & cur = d->cursor_;
586 switch (cursorStatus(cur)) {
588 // We reset the cursor because cursorStatus() does not
589 // work when the cursor is within mathed.
590 cur.reset(buffer_.inset());
591 tm.setCursorFromCoordinates(cur, 0, first);
592 cur.clearSelection();
595 // We reset the cursor because cursorStatus() does not
596 // work when the cursor is within mathed.
597 cur.reset(buffer_.inset());
598 tm.setCursorFromCoordinates(cur, 0, last);
599 cur.clearSelection();
602 int const y = getPos(cur, cur.boundary()).y_;
603 int const newy = min(last, max(y, first));
605 cur.reset(buffer_.inset());
606 tm.setCursorFromCoordinates(cur, 0, newy);
612 Change const BufferView::getCurrentChange() const
614 if (!d->cursor_.selection())
615 return Change(Change::UNCHANGED);
617 DocIterator dit = d->cursor_.selectionBegin();
618 return dit.paragraph().lookupChange(dit.pos());
622 // this could be used elsewhere as well?
623 // FIXME: This does not work within mathed!
624 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
626 Point const p = getPos(dit, dit.boundary());
629 if (p.y_ > workHeight())
635 void BufferView::saveBookmark(unsigned int idx)
637 // tenatively save bookmark, id and pos will be used to
638 // acturately locate a bookmark in a 'live' lyx session.
639 // pit and pos will be updated with bottom level pit/pos
641 LyX::ref().session().bookmarks().save(
643 d->cursor_.bottom().pit(),
644 d->cursor_.bottom().pos(),
645 d->cursor_.paragraph().id(),
650 // emit message signal.
651 message(_("Save bookmark"));
655 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
656 int top_id, pos_type top_pos)
658 bool success = false;
661 d->cursor_.clearSelection();
663 // if a valid par_id is given, try it first
664 // This is the case for a 'live' bookmark when unique paragraph ID
665 // is used to track bookmarks.
667 dit = buffer_.getParFromID(top_id);
669 dit.pos() = min(dit.paragraph().size(), top_pos);
670 // Some slices of the iterator may not be
671 // reachable (e.g. closed collapsable inset)
672 // so the dociterator may need to be
673 // shortened. Otherwise, setCursor may crash
674 // lyx when the cursor can not be set to these
676 size_t const n = dit.depth();
677 for (size_t i = 0; i < n; ++i)
678 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
686 // if top_id == 0, or searching through top_id failed
687 // This is the case for a 'restored' bookmark when only bottom
688 // (document level) pit was saved. Because of this, bookmark
689 // restoration is inaccurate. If a bookmark was within an inset,
690 // it will be restored to the left of the outmost inset that contains
692 if (bottom_pit < int(buffer_.paragraphs().size())) {
693 dit = doc_iterator_begin(buffer_.inset());
695 dit.pit() = bottom_pit;
696 dit.pos() = min(bottom_pos, dit.paragraph().size());
701 // Note: only bottom (document) level pit is set.
703 // set the current font.
704 d->cursor_.setCurrentFont();
705 // To center the screen on this new position we need the
706 // paragraph position which is computed at draw() time.
707 // So we need a redraw!
717 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
719 if (lyxrc.rtl_support) {
720 if (d->cursor_.real_current_font.isRightToLeft()) {
721 if (d->intl_.keymap == Intl::PRIMARY)
722 d->intl_.keyMapSec();
724 if (d->intl_.keymap == Intl::SECONDARY)
725 d->intl_.keyMapPrim();
729 d->intl_.getTransManager().translateAndInsert(c, t, cur);
733 int BufferView::workWidth() const
739 void BufferView::showCursor()
741 showCursor(d->cursor_);
745 void BufferView::showCursor(DocIterator const & dit)
747 // We are not properly started yet, delay until resizing is
752 LYXERR(Debug::SCROLLING, "recentering!");
754 CursorSlice const & bot = dit.bottom();
755 TextMetrics & tm = d->text_metrics_[bot.text()];
757 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
758 int bot_pit = bot.pit();
759 if (bot_pit > max_pit) {
760 // FIXME: Why does this happen?
761 LYXERR0("bottom pit is greater that max pit: "
762 << bot_pit << " > " << max_pit);
766 if (bot_pit == tm.first().first - 1)
767 tm.newParMetricsUp();
768 else if (bot_pit == tm.last().first + 1)
769 tm.newParMetricsDown();
771 if (tm.has(bot_pit)) {
772 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
773 BOOST_ASSERT(!pm.rows().empty());
774 // FIXME: smooth scrolling doesn't work in mathed.
775 CursorSlice const & cs = dit.innerTextSlice();
776 int offset = coordOffset(dit, dit.boundary()).y_;
777 int ypos = pm.position() + offset;
778 Dimension const & row_dim =
779 pm.getRow(cs.pos(), dit.boundary()).dimension();
780 if (ypos - row_dim.ascent() < 0)
781 scrollUp(- ypos + row_dim.ascent());
782 else if (ypos + row_dim.descent() > height_)
783 scrollDown(ypos - height_ + row_dim.descent());
784 // else, nothing to do, the cursor is already visible so we just return.
788 // fix inline completion position
789 if (d->inlineCompletionPos.fixIfBroken())
790 d->inlineCompletionPos = DocIterator();
792 tm.redoParagraph(bot_pit);
793 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
794 int offset = coordOffset(dit, dit.boundary()).y_;
796 d->anchor_pit_ = bot_pit;
797 CursorSlice const & cs = dit.innerTextSlice();
798 Dimension const & row_dim =
799 pm.getRow(cs.pos(), dit.boundary()).dimension();
801 if (d->anchor_pit_ == 0)
802 d->anchor_ypos_ = offset + pm.ascent();
803 else if (d->anchor_pit_ == max_pit)
804 d->anchor_ypos_ = height_ - offset - row_dim.descent();
806 d->anchor_ypos_ = defaultRowHeight() * 2 - offset - row_dim.descent();
813 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
817 Cursor & cur = d->cursor_;
819 switch (cmd.action) {
822 flag.enabled(buffer_.undo().hasUndoStack());
825 flag.enabled(buffer_.undo().hasRedoStack());
827 case LFUN_FILE_INSERT:
828 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
829 case LFUN_FILE_INSERT_PLAINTEXT:
830 case LFUN_BOOKMARK_SAVE:
831 // FIXME: Actually, these LFUNS should be moved to Text
832 flag.enabled(cur.inTexted());
834 case LFUN_FONT_STATE:
835 case LFUN_LABEL_INSERT:
836 case LFUN_INFO_INSERT:
837 case LFUN_PARAGRAPH_GOTO:
839 case LFUN_REFERENCE_NEXT:
841 case LFUN_WORD_REPLACE:
844 case LFUN_MARK_TOGGLE:
845 case LFUN_SCREEN_RECENTER:
846 case LFUN_BIBTEX_DATABASE_ADD:
847 case LFUN_BIBTEX_DATABASE_DEL:
848 case LFUN_STATISTICS:
849 case LFUN_NEXT_INSET_TOGGLE:
853 case LFUN_LABEL_GOTO: {
854 flag.enabled(!cmd.argument().empty()
855 || getInsetByCode<InsetRef>(cur, REF_CODE));
859 case LFUN_CHANGES_TRACK:
861 flag.setOnOff(buffer_.params().trackChanges);
864 case LFUN_CHANGES_OUTPUT:
866 flag.setOnOff(buffer_.params().outputChanges);
869 case LFUN_CHANGES_MERGE:
870 case LFUN_CHANGE_NEXT:
871 case LFUN_ALL_CHANGES_ACCEPT:
872 case LFUN_ALL_CHANGES_REJECT:
873 // TODO: context-sensitive enabling of LFUNs
874 // In principle, these command should only be enabled if there
875 // is a change in the document. However, without proper
876 // optimizations, this will inevitably result in poor performance.
880 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
881 flag.setOnOff(buffer_.params().compressed);
885 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
886 flag.setOnOff(buffer_.params().embedded);
891 case LFUN_SCREEN_DOWN:
896 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
897 // everywhere else before this can enabled:
898 case LFUN_SCREEN_UP_SELECT:
899 case LFUN_SCREEN_DOWN_SELECT:
903 case LFUN_LAYOUT_TABULAR:
904 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
908 case LFUN_LAYOUT_PARAGRAPH:
909 flag.enabled(cur.inset().allowParagraphCustomization(cur.idx()));
912 case LFUN_INSET_SETTINGS: {
913 InsetCode code = cur.inset().lyxCode();
917 enable = cmd.argument() == "tabular";
920 enable = cmd.argument() == "ert";
923 enable = cmd.argument() == "float";
926 enable = cmd.argument() == "wrap";
929 enable = cmd.argument() == "note";
932 enable = cmd.argument() == "branch";
935 enable = cmd.argument() == "box";
938 enable = cmd.argument() == "listings";
943 flag.enabled(enable);
947 case LFUN_DIALOG_SHOW_NEW_INSET:
948 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
949 cur.inset().lyxCode() != LISTINGS_CODE);
950 if (cur.inset().lyxCode() == CAPTION_CODE) {
952 if (cur.inset().getStatus(cur, cmd, flag))
965 bool BufferView::dispatch(FuncRequest const & cmd)
967 //lyxerr << [ cmd = " << cmd << "]" << endl;
969 // Make sure that the cached BufferView is correct.
970 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
971 << " arg[" << to_utf8(cmd.argument()) << ']'
972 << " x[" << cmd.x << ']'
973 << " y[" << cmd.y << ']'
974 << " button[" << cmd.button() << ']');
976 Cursor & cur = d->cursor_;
978 switch (cmd.action) {
981 cur.message(_("Undo"));
982 cur.clearSelection();
984 cur.message(_("No further undo information"));
986 processUpdateFlags(Update::Force | Update::FitCursor);
990 cur.message(_("Redo"));
991 cur.clearSelection();
993 cur.message(_("No further redo information"));
995 processUpdateFlags(Update::Force | Update::FitCursor);
998 case LFUN_FONT_STATE:
999 cur.message(cur.currentState());
1002 case LFUN_BOOKMARK_SAVE:
1003 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1006 case LFUN_LABEL_GOTO: {
1007 docstring label = cmd.argument();
1008 if (label.empty()) {
1010 getInsetByCode<InsetRef>(d->cursor_,
1013 label = inset->getParam("reference");
1014 // persistent=false: use temp_bookmark
1024 case LFUN_PARAGRAPH_GOTO: {
1025 int const id = convert<int>(to_utf8(cmd.argument()));
1027 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1028 b = theBufferList().next(b)) {
1030 DocIterator dit = b->getParFromID(id);
1032 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1036 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1037 << " found in buffer `"
1038 << b->absFileName() << "'.");
1040 if (b == &buffer_) {
1043 processUpdateFlags(Update::Force | Update::FitCursor);
1045 // Switch to other buffer view and resend cmd
1046 theLyXFunc().dispatch(FuncRequest(
1047 LFUN_BUFFER_SWITCH, b->absFileName()));
1048 theLyXFunc().dispatch(cmd);
1055 case LFUN_NOTE_NEXT:
1056 gotoInset(this, NOTE_CODE, false);
1059 case LFUN_REFERENCE_NEXT: {
1060 vector<InsetCode> tmp;
1061 tmp.push_back(LABEL_CODE);
1062 tmp.push_back(REF_CODE);
1063 gotoInset(this, tmp, true);
1067 case LFUN_CHANGES_TRACK:
1068 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1071 case LFUN_CHANGES_OUTPUT:
1072 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1073 if (buffer_.params().outputChanges) {
1074 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1075 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1076 LaTeXFeatures::isAvailable("xcolor");
1078 if (!dvipost && !xcolorsoul) {
1079 Alert::warning(_("Changes not shown in LaTeX output"),
1080 _("Changes will not be highlighted in LaTeX output, "
1081 "because neither dvipost nor xcolor/soul are installed.\n"
1082 "Please install these packages or redefine "
1083 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1084 } else if (!xcolorsoul) {
1085 Alert::warning(_("Changes not shown in LaTeX output"),
1086 _("Changes will not be highlighted in LaTeX output "
1087 "when using pdflatex, because xcolor and soul are not installed.\n"
1088 "Please install both packages or redefine "
1089 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1094 case LFUN_CHANGE_NEXT:
1095 findNextChange(this);
1098 case LFUN_CHANGES_MERGE:
1099 if (findNextChange(this))
1100 showDialog("changes");
1103 case LFUN_ALL_CHANGES_ACCEPT:
1104 // select complete document
1105 d->cursor_.reset(buffer_.inset());
1106 d->cursor_.selHandle(true);
1107 buffer_.text().cursorBottom(d->cursor_);
1108 // accept everything in a single step to support atomic undo
1109 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1112 case LFUN_ALL_CHANGES_REJECT:
1113 // select complete document
1114 d->cursor_.reset(buffer_.inset());
1115 d->cursor_.selHandle(true);
1116 buffer_.text().cursorBottom(d->cursor_);
1117 // reject everything in a single step to support atomic undo
1118 // Note: reject does not work recursively; the user may have to repeat the operation
1119 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1122 case LFUN_WORD_FIND:
1123 if (find(this, cmd))
1126 message(_("String not found!"));
1129 case LFUN_WORD_REPLACE: {
1130 bool has_deleted = false;
1131 if (cur.selection()) {
1132 DocIterator beg = cur.selectionBegin();
1133 DocIterator end = cur.selectionEnd();
1134 if (beg.pit() == end.pit()) {
1135 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1136 if (cur.paragraph().isDeleted(p))
1141 replace(this, cmd, has_deleted);
1146 cur.clearSelection();
1148 cur.message(from_utf8(N_("Mark off")));
1152 cur.clearSelection();
1155 cur.message(from_utf8(N_("Mark on")));
1158 case LFUN_MARK_TOGGLE:
1159 cur.clearSelection();
1162 cur.message(from_utf8(N_("Mark removed")));
1165 cur.message(from_utf8(N_("Mark set")));
1170 case LFUN_SCREEN_RECENTER:
1174 case LFUN_BIBTEX_DATABASE_ADD: {
1175 Cursor tmpcur = d->cursor_;
1176 findInset(tmpcur, BIBTEX_CODE, false);
1177 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1180 if (inset->addDatabase(to_utf8(cmd.argument())))
1181 buffer_.updateBibfilesCache();
1186 case LFUN_BIBTEX_DATABASE_DEL: {
1187 Cursor tmpcur = d->cursor_;
1188 findInset(tmpcur, BIBTEX_CODE, false);
1189 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1192 if (inset->delDatabase(to_utf8(cmd.argument())))
1193 buffer_.updateBibfilesCache();
1198 case LFUN_STATISTICS: {
1199 DocIterator from, to;
1200 if (cur.selection()) {
1201 from = cur.selectionBegin();
1202 to = cur.selectionEnd();
1204 from = doc_iterator_begin(buffer_.inset());
1205 to = doc_iterator_end(buffer_.inset());
1207 int const words = countWords(from, to);
1208 int const chars = countChars(from, to, false);
1209 int const chars_blanks = countChars(from, to, true);
1211 if (cur.selection())
1212 message = _("Statistics for the selection:");
1214 message = _("Statistics for the document:");
1217 message += bformat(_("%1$d words"), words);
1219 message += _("One word");
1221 if (chars_blanks != 1)
1222 message += bformat(_("%1$d characters (including blanks)"),
1225 message += _("One character (including blanks)");
1228 message += bformat(_("%1$d characters (excluding blanks)"),
1231 message += _("One character (excluding blanks)");
1233 Alert::information(_("Statistics"), message);
1237 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1238 // turn compression on/off
1239 buffer_.params().compressed = !buffer_.params().compressed;
1242 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
1243 // turn embedding on/off
1245 buffer_.embeddedFiles().enable(!buffer_.params().embedded, buffer_);
1246 } catch (ExceptionMessage const & message) {
1247 Alert::error(message.title_, message.details_);
1252 case LFUN_NEXT_INSET_TOGGLE: {
1253 // this is the real function we want to invoke
1254 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1255 // if there is an inset at cursor, see whether it
1257 Inset * inset = cur.nextInset();
1259 if (inset->isActive()) {
1260 Cursor tmpcur = cur;
1261 tmpcur.pushBackward(*inset);
1262 inset->dispatch(tmpcur, tmpcmd);
1263 if (tmpcur.result().dispatched()) {
1266 } else if (inset->editable() == Inset::IS_EDITABLE) {
1267 inset->edit(cur, true);
1270 // if it did not work, try the underlying inset.
1271 if (!cur.result().dispatched())
1272 cur.dispatch(tmpcmd);
1274 if (!cur.result().dispatched())
1275 // It did not work too; no action needed.
1277 cur.clearSelection();
1278 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1282 case LFUN_SCREEN_UP:
1283 case LFUN_SCREEN_DOWN: {
1284 Point p = getPos(cur, cur.boundary());
1285 if (p.y_ < 0 || p.y_ > height_) {
1286 // The cursor is off-screen so recenter before proceeding.
1288 p = getPos(cur, cur.boundary());
1290 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1291 cur.reset(buffer_.inset());
1292 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1293 //FIXME: what to do with cur.x_target()?
1302 case LFUN_SCREEN_UP_SELECT:
1303 case LFUN_SCREEN_DOWN_SELECT: {
1304 // Those two are not ready yet for consumption.
1307 cur.selHandle(true);
1308 size_t initial_depth = cur.depth();
1309 Point const p = getPos(cur, cur.boundary());
1310 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1311 // FIXME: We need to verify if the cursor stayed within an inset...
1312 //cur.reset(buffer_.inset());
1313 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1315 while (cur.depth() > initial_depth) {
1318 // FIXME: we need to do a redraw again because of the selection
1319 // But no screen update is needed.
1320 d->update_strategy_ = NoScreenUpdate;
1333 docstring const BufferView::requestSelection()
1335 Cursor & cur = d->cursor_;
1337 if (!cur.selection()) {
1338 d->xsel_cache_.set = false;
1342 if (!d->xsel_cache_.set ||
1343 cur.top() != d->xsel_cache_.cursor ||
1344 cur.anchor_.top() != d->xsel_cache_.anchor)
1346 d->xsel_cache_.cursor = cur.top();
1347 d->xsel_cache_.anchor = cur.anchor_.top();
1348 d->xsel_cache_.set = cur.selection();
1349 return cur.selectionAsString(false);
1355 void BufferView::clearSelection()
1357 d->cursor_.clearSelection();
1358 // Clear the selection buffer. Otherwise a subsequent
1359 // middle-mouse-button paste would use the selection buffer,
1360 // not the more current external selection.
1361 cap::clearSelection();
1362 d->xsel_cache_.set = false;
1363 // The buffer did not really change, but this causes the
1364 // redraw we need because we cleared the selection above.
1369 void BufferView::resize(int width, int height)
1371 // Update from work area
1375 // Clear the paragraph height cache.
1376 d->par_height_.clear();
1377 // Redo the metrics.
1382 Inset const * BufferView::getCoveringInset(Text const & text,
1385 TextMetrics & tm = d->text_metrics_[&text];
1386 Inset * inset = tm.checkInsetHit(x, y);
1390 if (!inset->descendable())
1391 // No need to go further down if the inset is not
1395 size_t cell_number = inset->nargs();
1396 // Check all the inner cell.
1397 for (size_t i = 0; i != cell_number; ++i) {
1398 Text const * inner_text = inset->getText(i);
1401 Inset const * inset_deeper =
1402 getCoveringInset(*inner_text, x, y);
1404 return inset_deeper;
1412 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1414 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1416 // This is only called for mouse related events including
1417 // LFUN_FILE_OPEN generated by drag-and-drop.
1418 FuncRequest cmd = cmd0;
1421 cur.push(buffer_.inset());
1422 cur.selection() = d->cursor_.selection();
1424 // Either the inset under the cursor or the
1425 // surrounding Text will handle this event.
1427 // make sure we stay within the screen...
1428 cmd.y = min(max(cmd.y, -1), height_);
1430 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1432 // Get inset under mouse, if there is one.
1433 Inset const * covering_inset =
1434 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1435 if (covering_inset == d->last_inset_)
1436 // Same inset, no need to do anything...
1439 bool need_redraw = false;
1440 // const_cast because of setMouseHover().
1441 Inset * inset = const_cast<Inset *>(covering_inset);
1443 // Remove the hint on the last hovered inset (if any).
1444 need_redraw |= d->last_inset_->setMouseHover(false);
1446 // Highlighted the newly hovered inset (if any).
1447 need_redraw |= inset->setMouseHover(true);
1448 d->last_inset_ = inset;
1452 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1453 << cmd.x << ", " << cmd.y << ")");
1455 d->update_strategy_ = DecorationUpdate;
1457 // This event (moving without mouse click) is not passed further.
1458 // This should be changed if it is further utilized.
1463 // Build temporary cursor.
1464 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1466 // Put anchor at the same position.
1469 // Try to dispatch to an non-editable inset near this position
1470 // via the temp cursor. If the inset wishes to change the real
1471 // cursor it has to do so explicitly by using
1472 // cur.bv().cursor() = cur; (or similar)
1474 inset->dispatch(cur, cmd);
1476 // Now dispatch to the temporary cursor. If the real cursor should
1477 // be modified, the inset's dispatch has to do so explicitly.
1478 if (!cur.result().dispatched())
1481 //Do we have a selection?
1482 theSelection().haveSelection(cursor().selection());
1484 // If the command has been dispatched,
1485 if (cur.result().dispatched()
1486 // an update is asked,
1487 && cur.result().update())
1488 processUpdateFlags(cur.result().update());
1492 void BufferView::lfunScroll(FuncRequest const & cmd)
1494 string const scroll_type = cmd.getArg(0);
1495 int const scroll_step =
1496 (scroll_type == "line")? d->scrollbarParameters_.single_step
1497 : (scroll_type == "page")? d->scrollbarParameters_.page_step : 0;
1498 if (scroll_step == 0)
1500 string const scroll_quantity = cmd.getArg(1);
1501 if (scroll_quantity == "up")
1502 scrollUp(scroll_step);
1503 else if (scroll_quantity == "down")
1504 scrollDown(scroll_step);
1506 int const scroll_value = convert<int>(scroll_quantity);
1508 scroll(scroll_step * scroll_value);
1513 void BufferView::scroll(int y)
1522 void BufferView::scrollDown(int offset)
1524 Text * text = &buffer_.text();
1525 TextMetrics & tm = d->text_metrics_[text];
1526 int ymax = height_ + offset;
1528 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1529 int bottom_pos = last.second->position() + last.second->descent();
1530 if (last.first + 1 == int(text->paragraphs().size())) {
1531 if (bottom_pos <= height_)
1533 offset = min(offset, bottom_pos - height_);
1536 if (bottom_pos > ymax)
1538 tm.newParMetricsDown();
1540 d->anchor_ypos_ -= offset;
1546 void BufferView::scrollUp(int offset)
1548 Text * text = &buffer_.text();
1549 TextMetrics & tm = d->text_metrics_[text];
1550 int ymin = - offset;
1552 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1553 int top_pos = first.second->position() - first.second->ascent();
1554 if (first.first == 0) {
1557 offset = min(offset, - top_pos);
1562 tm.newParMetricsUp();
1564 d->anchor_ypos_ += offset;
1570 void BufferView::setCursorFromRow(int row)
1575 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1577 d->cursor_.reset(buffer_.inset());
1579 buffer_.text().setCursor(d->cursor_, 0, 0);
1581 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1585 void BufferView::gotoLabel(docstring const & label)
1587 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1588 vector<docstring> labels;
1589 it->getLabelList(buffer_, labels);
1590 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1599 TextMetrics const & BufferView::textMetrics(Text const * t) const
1601 return const_cast<BufferView *>(this)->textMetrics(t);
1605 TextMetrics & BufferView::textMetrics(Text const * t)
1607 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1608 if (tmc_it == d->text_metrics_.end()) {
1609 tmc_it = d->text_metrics_.insert(
1610 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1612 return tmc_it->second;
1616 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1619 return textMetrics(t).parMetrics(pit);
1623 int BufferView::workHeight() const
1629 void BufferView::setCursor(DocIterator const & dit)
1631 size_t const n = dit.depth();
1632 for (size_t i = 0; i < n; ++i)
1633 dit[i].inset().edit(d->cursor_, true);
1635 d->cursor_.setCursor(dit);
1636 d->cursor_.selection() = false;
1640 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1642 // Would be wrong to delete anything if we have a selection.
1643 if (cur.selection())
1646 bool need_anchor_change = false;
1647 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1648 need_anchor_change);
1650 if (need_anchor_change)
1658 updateLabels(buffer_);
1666 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1668 BOOST_ASSERT(&cur.bv() == this);
1671 // this event will clear selection so we save selection for
1672 // persistent selection
1673 cap::saveSelection(cursor());
1675 // Has the cursor just left the inset?
1676 bool badcursor = false;
1677 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1679 badcursor = notifyCursorLeaves(d->cursor_, cur);
1681 // FIXME: shift-mouse selection doesn't work well across insets.
1682 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1684 // do the dEPM magic if needed
1685 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1686 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1687 // the leftinset bool would not be necessary (badcursor instead).
1688 bool update = leftinset;
1689 if (!do_selection && !badcursor && d->cursor_.inTexted())
1690 update |= checkDepm(cur, d->cursor_);
1692 // if the cursor was in an empty script inset and the new
1693 // position is in the nucleus of the inset, notifyCursorLeaves
1694 // will kill the script inset itself. So we check all the
1695 // elements of the cursor to make sure that they are correct.
1696 // For an example, see bug 2933:
1697 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1698 // The code below could maybe be moved to a DocIterator method.
1699 //lyxerr << "cur before " << cur << endl;
1700 DocIterator dit = doc_iterator_begin(cur.inset());
1701 dit.bottom() = cur.bottom();
1703 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1704 dit.push_back(cur[i]);
1707 //lyxerr << "5 cur after" << dit <<endl;
1709 d->cursor_.setCursor(dit);
1710 d->cursor_.boundary(cur.boundary());
1712 d->cursor_.setSelection();
1714 d->cursor_.clearSelection();
1716 d->cursor_.finishUndo();
1717 d->cursor_.setCurrentFont();
1722 void BufferView::putSelectionAt(DocIterator const & cur,
1723 int length, bool backwards)
1725 d->cursor_.clearSelection();
1731 d->cursor_.pos() += length;
1732 d->cursor_.setSelection(d->cursor_, -length);
1734 d->cursor_.setSelection(d->cursor_, length);
1736 // Ensure a redraw happens in any case because the new selection could
1737 // possibly be on the same screen as the previous selection.
1738 processUpdateFlags(Update::Force | Update::FitCursor);
1742 Cursor & BufferView::cursor()
1748 Cursor const & BufferView::cursor() const
1754 pit_type BufferView::anchor_ref() const
1756 return d->anchor_pit_;
1760 bool BufferView::singleParUpdate()
1762 Text & buftext = buffer_.text();
1763 pit_type const bottom_pit = d->cursor_.bottom().pit();
1764 TextMetrics & tm = textMetrics(&buftext);
1765 int old_height = tm.parMetrics(bottom_pit).height();
1767 // make sure inline completion pointer is ok
1768 if (d->inlineCompletionPos.fixIfBroken())
1769 d->inlineCompletionPos = DocIterator();
1771 // In Single Paragraph mode, rebreak only
1772 // the (main text, not inset!) paragraph containing the cursor.
1773 // (if this paragraph contains insets etc., rebreaking will
1774 // recursively descend)
1775 tm.redoParagraph(bottom_pit);
1776 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1777 if (pm.height() != old_height)
1778 // Paragraph height has changed so we cannot proceed to
1779 // the singlePar optimisation.
1782 d->update_strategy_ = SingleParUpdate;
1784 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1785 << " y2: " << pm.position() + pm.descent()
1786 << " pit: " << bottom_pit
1787 << " singlepar: 1");
1792 void BufferView::updateMetrics()
1794 Text & buftext = buffer_.text();
1795 pit_type const npit = int(buftext.paragraphs().size());
1797 // Clear out the position cache in case of full screen redraw,
1798 d->coord_cache_.clear();
1800 // Clear out paragraph metrics to avoid having invalid metrics
1801 // in the cache from paragraphs not relayouted below
1802 // The complete text metrics will be redone.
1803 d->text_metrics_.clear();
1805 TextMetrics & tm = textMetrics(&buftext);
1807 // make sure inline completion pointer is ok
1808 if (d->inlineCompletionPos.fixIfBroken())
1809 d->inlineCompletionPos = DocIterator();
1811 // Rebreak anchor paragraph.
1812 tm.redoParagraph(d->anchor_pit_);
1813 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1816 if (d->anchor_pit_ == 0) {
1817 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
1819 // Complete buffer visible? Then it's easy.
1820 if (scrollRange == 0)
1821 d->anchor_ypos_ = anchor_pm.ascent();
1823 // FIXME: Some clever handling needed to show
1824 // the _first_ paragraph up to the top if the cursor is
1825 // in the first line.
1827 anchor_pm.setPosition(d->anchor_ypos_);
1829 LYXERR(Debug::PAINTING, "metrics: "
1830 << " anchor pit = " << d->anchor_pit_
1831 << " anchor ypos = " << d->anchor_ypos_);
1833 // Redo paragraphs above anchor if necessary.
1834 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1835 // We are now just above the anchor paragraph.
1836 pit_type pit1 = d->anchor_pit_ - 1;
1837 for (; pit1 >= 0 && y1 >= 0; --pit1) {
1838 tm.redoParagraph(pit1);
1839 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1841 // Save the paragraph position in the cache.
1846 // Redo paragraphs below the anchor if necessary.
1847 int y2 = d->anchor_ypos_ + anchor_pm.descent();
1848 // We are now just below the anchor paragraph.
1849 pit_type pit2 = d->anchor_pit_ + 1;
1850 for (; pit2 < npit && y2 <= height_; ++pit2) {
1851 tm.redoParagraph(pit2);
1852 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1854 // Save the paragraph position in the cache.
1859 LYXERR(Debug::PAINTING, "Metrics: "
1860 << " anchor pit = " << d->anchor_pit_
1861 << " anchor ypos = " << d->anchor_ypos_
1864 << " pit1 = " << pit1
1865 << " pit2 = " << pit2);
1867 d->update_strategy_ = FullScreenUpdate;
1869 if (lyxerr.debugging(Debug::WORKAREA)) {
1870 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1871 d->coord_cache_.dump();
1876 void BufferView::insertLyXFile(FileName const & fname)
1878 BOOST_ASSERT(d->cursor_.inTexted());
1880 // Get absolute path of file and add ".lyx"
1881 // to the filename if necessary
1882 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1884 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1885 // emit message signal.
1886 message(bformat(_("Inserting document %1$s..."), disp_fn));
1889 Buffer buf("", false);
1890 if (buf.loadLyXFile(filename)) {
1891 ErrorList & el = buffer_.errorList("Parse");
1892 // Copy the inserted document error list into the current buffer one.
1893 el = buf.errorList("Parse");
1894 buffer_.undo().recordUndo(d->cursor_);
1895 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1896 buf.params().getTextClassPtr(), el);
1897 res = _("Document %1$s inserted.");
1899 res = _("Could not insert document %1$s");
1904 // emit message signal.
1905 message(bformat(res, disp_fn));
1906 buffer_.errors("Parse");
1910 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1916 // Addup contribution of nested insets, from inside to outside,
1917 // keeping the outer paragraph for a special handling below
1918 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1919 CursorSlice const & sl = dit[i];
1923 // get relative position inside sl.inset()
1924 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1926 // Make relative position inside of the edited inset relative to sl.inset()
1930 // In case of an RTL inset, the edited inset will be positioned to the left
1933 bool boundary_i = boundary && i + 1 == dit.depth();
1934 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1939 // remember width for the case that sl.inset() is positioned in an RTL inset
1940 if (i && dit[i - 1].text()) {
1941 // If this Inset is inside a Text Inset, retrieve the Dimension
1942 // from the containing text instead of using Inset::dimension() which
1943 // might not be implemented.
1944 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1945 // elimination of Inset::dim_ cache. This coordOffset() method needs
1946 // to be rewritten in light of the new design.
1947 Dimension const & dim = parMetrics(dit[i - 1].text(),
1948 dit[i - 1].pit()).insetDimension(&sl.inset());
1951 Dimension const dim = sl.inset().dimension(*this);
1955 //lyxerr << "Cursor::getPos, i: "
1956 // << i << " x: " << xx << " y: " << y << endl;
1959 // Add contribution of initial rows of outermost paragraph
1960 CursorSlice const & sl = dit[0];
1961 TextMetrics const & tm = textMetrics(sl.text());
1962 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1963 BOOST_ASSERT(!pm.rows().empty());
1964 y -= pm.rows()[0].ascent();
1966 // FIXME: document this mess
1968 if (sl.pos() > 0 && dit.depth() == 1) {
1970 if (pos && boundary)
1972 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
1973 rend = pm.pos2row(pos);
1975 rend = pm.pos2row(sl.pos());
1977 size_t rend = pm.pos2row(sl.pos());
1979 for (size_t rit = 0; rit != rend; ++rit)
1980 y += pm.rows()[rit].height();
1981 y += pm.rows()[rend].ascent();
1983 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1985 // Make relative position from the nested inset now bufferview absolute.
1986 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1989 // In the RTL case place the nested inset at the left of the cursor in
1990 // the outer paragraph
1991 bool boundary_1 = boundary && 1 == dit.depth();
1992 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2000 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2002 CursorSlice const & bot = dit.bottom();
2003 TextMetrics const & tm = textMetrics(bot.text());
2004 if (!tm.has(bot.pit()))
2005 return Point(-1, -1);
2007 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2008 p.y_ += tm.parMetrics(bot.pit()).position();
2013 void BufferView::draw(frontend::Painter & pain)
2015 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2016 Text & text = buffer_.text();
2017 TextMetrics const & tm = d->text_metrics_[&text];
2018 int const y = tm.first().second->position();
2019 PainterInfo pi(this, pain);
2021 switch (d->update_strategy_) {
2023 case NoScreenUpdate:
2024 // If no screen painting is actually needed, only some the different
2025 // coordinates of insets and paragraphs needs to be updated.
2026 pi.full_repaint = true;
2027 pi.pain.setDrawingEnabled(false);
2031 case SingleParUpdate:
2032 pi.full_repaint = false;
2033 // In general, only the current row of the outermost paragraph
2034 // will be redrawn. Particular cases where selection spans
2035 // multiple paragraph are correctly detected in TextMetrics.
2039 case DecorationUpdate:
2040 // FIXME: We should also distinguish DecorationUpdate to avoid text
2041 // drawing if possible. This is not possible to do easily right now
2042 // because of the single backing pixmap.
2044 case FullScreenUpdate:
2045 // The whole screen, including insets, will be refreshed.
2046 pi.full_repaint = true;
2048 // Clear background.
2049 pain.fillRectangle(0, 0, width_, height_,
2050 buffer_.inset().backgroundColor());
2055 // and possibly grey out below
2056 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2057 int const y2 = lastpm.second->position() + lastpm.second->descent();
2059 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2062 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2064 // The scrollbar needs an update.
2067 // Normalize anchor for next time
2068 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2069 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2070 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2071 ParagraphMetrics const & pm = tm.parMetrics(pit);
2072 if (pm.position() + pm.descent() > 0) {
2073 d->anchor_pit_ = pit;
2074 d->anchor_ypos_ = pm.position();
2078 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2079 << " anchor ypos = " << d->anchor_ypos_);
2083 void BufferView::message(docstring const & msg)
2086 d->gui_->message(msg);
2090 void BufferView::showDialog(string const & name)
2093 d->gui_->showDialog(name, string());
2097 void BufferView::showDialog(string const & name,
2098 string const & data, Inset * inset)
2101 d->gui_->showDialog(name, data, inset);
2105 void BufferView::updateDialog(string const & name, string const & data)
2108 d->gui_->updateDialog(name, data);
2112 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2118 // FIXME: Move this out of BufferView again
2119 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2121 if (!fname.isReadableFile()) {
2122 docstring const error = from_ascii(strerror(errno));
2123 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2124 docstring const text =
2125 bformat(_("Could not read the specified document\n"
2126 "%1$s\ndue to the error: %2$s"), file, error);
2127 Alert::error(_("Could not read file"), text);
2131 if (!fname.isReadableFile()) {
2132 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2133 docstring const text =
2134 bformat(_("%1$s\n is not readable."), file);
2135 Alert::error(_("Could not open file"), text);
2139 // FIXME UNICODE: We don't know the encoding of the file
2140 docstring file_content = fname.fileContents("UTF-8");
2141 if (file_content.empty()) {
2142 Alert::error(_("Reading not UTF-8 encoded file"),
2143 _("The file is not UTF-8 encoded.\n"
2144 "It will be read as local 8Bit-encoded.\n"
2145 "If this does not give the correct result\n"
2146 "then please change the encoding of the file\n"
2147 "to UTF-8 with a program other than LyX.\n"));
2148 file_content = fname.fileContents("local8bit");
2151 return normalize_c(file_content);
2155 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2157 docstring const tmpstr = contentsOfPlaintextFile(f);
2162 Cursor & cur = cursor();
2163 cap::replaceSelection(cur);
2164 buffer_.undo().recordUndo(cur);
2166 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2168 cur.innerText()->insertStringAsLines(cur, tmpstr);
2175 docstring const & BufferView::inlineCompletion() const
2177 return d->inlineCompletion;
2181 size_t const & BufferView::inlineCompletionUniqueChars() const
2183 return d->inlineCompletionUniqueChars;
2187 DocIterator const & BufferView::inlineCompletionPos() const
2189 return d->inlineCompletionPos;
2193 bool samePar(DocIterator const & a, DocIterator const & b)
2195 if (a.empty() && b.empty())
2197 if (a.empty() || b.empty())
2199 return &a.innerParagraph() == &b.innerParagraph();
2203 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2204 docstring const & completion, size_t uniqueChars)
2206 uniqueChars = min(completion.size(), uniqueChars);
2207 bool changed = d->inlineCompletion != completion
2208 || d->inlineCompletionUniqueChars != uniqueChars;
2209 bool singlePar = true;
2210 d->inlineCompletion = completion;
2211 d->inlineCompletionUniqueChars = min(completion.size(), uniqueChars);
2213 lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2216 DocIterator const & old = d->inlineCompletionPos;
2218 lyxerr << "inlineCompletionPos changed" << std::endl;
2219 // old or pos are in another paragraph?
2220 if ((!samePar(cur, pos) && !pos.empty())
2221 || (!samePar(cur, old) && !old.empty())) {
2223 lyxerr << "different paragraph" << std::endl;
2225 d->inlineCompletionPos = pos;
2230 lyxerr << "inlineCompletion changed" << std::endl;
2233 = cur.disp_.update() | Update::Force;
2234 if (singlePar && !(flags | Update::SinglePar))
2235 flags = flags | Update::SinglePar;
2236 cur.updateFlags(flags);