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_;
241 /// keyboard mapping object.
244 /// last visited inset.
245 /** kept to send setMouseHover(false).
246 * Not owned, so don't delete.
250 mutable TextMetricsCache text_metrics_;
253 /** Not owned, so don't delete.
255 frontend::GuiBufferViewDelegate * gui_;
259 BufferView::BufferView(Buffer & buf)
260 : width_(0), height_(0), full_screen_(false), buffer_(buf), d(new Private(*this))
262 d->xsel_cache_.set = false;
263 d->intl_.initKeyMapper(lyxrc.use_kbmap);
265 d->cursor_.push(buffer_.inset());
266 d->cursor_.resetAnchor();
267 d->cursor_.setCurrentFont();
269 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
270 graphics::Previews::get().generateBufferPreviews(buffer_);
274 BufferView::~BufferView()
276 // current buffer is going to be switched-off, save cursor pos
277 // Ideally, the whole cursor stack should be saved, but session
278 // currently can only handle bottom (whole document) level pit and pos.
279 // That is to say, if a cursor is in a nested inset, it will be
280 // restore to the left of the top level inset.
281 LastFilePosSection::FilePos fp;
282 fp.pit = d->cursor_.bottom().pit();
283 fp.pos = d->cursor_.bottom().pos();
284 LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
289 // Put this user variable in lyxrc or pass it through setFullScreen()
290 static int const max_row_width = 700;
292 int BufferView::rightMargin() const
294 if (!full_screen_ || width_ < max_row_width + 20)
297 return (width_ - max_row_width) / 2;
301 int BufferView::leftMargin() const
303 return rightMargin();
307 Intl & BufferView::getIntl()
313 Intl const & BufferView::getIntl() const
319 CoordCache & BufferView::coordCache()
321 return d->coord_cache_;
325 CoordCache const & BufferView::coordCache() const
327 return d->coord_cache_;
331 Buffer & BufferView::buffer()
337 Buffer const & BufferView::buffer() const
343 bool BufferView::fitCursor()
345 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
346 frontend::FontMetrics const & fm =
347 theFontMetrics(d->cursor_.getFont().fontInfo());
348 int const asc = fm.maxAscent();
349 int const des = fm.maxDescent();
350 Point const p = getPos(d->cursor_, d->cursor_.boundary());
351 if (p.y_ - asc >= 0 && p.y_ + des < height_)
358 void BufferView::processUpdateFlags(Update::flags flags)
360 // last_inset_ points to the last visited inset. This pointer may become
361 // invalid because of keyboard editing. Since all such operations
362 // causes screen update(), I reset last_inset_ to avoid such a problem.
364 // This is close to a hot-path.
365 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
366 << "[fitcursor = " << (flags & Update::FitCursor)
367 << ", forceupdate = " << (flags & Update::Force)
368 << ", singlepar = " << (flags & Update::SinglePar)
369 << "] buffer: " << &buffer_);
371 buffer_.updateMacros();
373 // Now do the first drawing step if needed. This consists on updating
374 // the CoordCache in updateMetrics().
375 // The second drawing step is done in WorkArea::redraw() if needed.
377 // Case when no explicit update is requested.
379 // no need to redraw anything.
380 d->update_strategy_ = NoScreenUpdate;
384 if (flags == Update::Decoration) {
385 d->update_strategy_ = DecorationUpdate;
390 if (flags == Update::FitCursor
391 || flags == (Update::Decoration | Update::FitCursor)) {
392 // tell the frontend to update the screen if needed.
397 if (flags & Update::Decoration) {
398 d->update_strategy_ = DecorationUpdate;
402 // no screen update is needed.
403 d->update_strategy_ = NoScreenUpdate;
407 bool const full_metrics = flags & Update::Force || !singleParUpdate();
410 // We have to update the full screen metrics.
413 if (!(flags & Update::FitCursor)) {
414 // Nothing to do anymore. Trigger a redraw and return
419 // updateMetrics() does not update paragraph position
420 // This is done at draw() time. So we need a redraw!
424 // The cursor is off screen so ensure it is visible.
431 void BufferView::updateScrollbar()
436 // We prefer fixed size line scrolling.
437 d->scrollbarParameters_.single_step = defaultRowHeight();
438 // We prefer full screen page scrolling.
439 d->scrollbarParameters_.page_step = height_;
441 Text & t = buffer_.text();
442 TextMetrics & tm = d->text_metrics_[&t];
444 LYXERR(Debug::GUI, " Updating scrollbar: height: "
445 << t.paragraphs().size()
446 << " curr par: " << d->cursor_.bottom().pit()
447 << " default height " << defaultRowHeight());
449 size_t const parsize = t.paragraphs().size();
450 if (d->par_height_.size() != parsize) {
451 d->par_height_.clear();
452 // FIXME: We assume a default paragraph height of 2 rows. This
453 // should probably be pondered with the screen width.
454 d->par_height_.resize(parsize, defaultRowHeight() * 2);
457 // Look at paragraph heights on-screen
458 pair<pit_type, ParagraphMetrics const *> first = tm.first();
459 pair<pit_type, ParagraphMetrics const *> last = tm.last();
460 for (pit_type pit = first.first; pit <= last.first; ++pit) {
461 d->par_height_[pit] = tm.parMetrics(pit).height();
462 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
463 << d->par_height_[pit]);
466 int top_pos = first.second->position() - first.second->ascent();
467 int bottom_pos = last.second->position() + last.second->descent();
468 bool first_visible = first.first == 0 && top_pos >= 0;
469 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
470 if (first_visible && last_visible) {
471 d->scrollbarParameters_.min = 0;
472 d->scrollbarParameters_.max = 0;
476 d->scrollbarParameters_.min = top_pos;
477 for (size_t i = 0; i != size_t(first.first); ++i)
478 d->scrollbarParameters_.min -= d->par_height_[i];
479 d->scrollbarParameters_.max = bottom_pos;
480 for (size_t i = last.first + 1; i != parsize; ++i)
481 d->scrollbarParameters_.max += d->par_height_[i];
483 d->scrollbarParameters_.position = 0;
484 // The reference is the top position so we remove one page.
485 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
489 ScrollbarParameters const & BufferView::scrollbarParameters() const
491 return d->scrollbarParameters_;
495 docstring BufferView::toolTip(int x, int y) const
497 // Get inset under mouse, if there is one.
498 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
500 // No inset, no tooltip...
502 return covering_inset->toolTip(*this, x, y);
506 docstring BufferView::contextMenu(int x, int y) const
508 // Get inset under mouse, if there is one.
509 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
511 return covering_inset->contextMenu(*this, x, y);
513 // FIXME: Do something more elaborate here.
514 return from_ascii("edit");
518 void BufferView::scrollDocView(int value)
520 int const offset = value - d->scrollbarParameters_.position;
521 // If the offset is less than 2 screen height, prefer to scroll instead.
522 if (abs(offset) <= 2 * height_) {
527 // cut off at the top
528 if (value <= d->scrollbarParameters_.min) {
529 DocIterator dit = doc_iterator_begin(buffer_.inset());
531 LYXERR(Debug::SCROLLING, "scroll to top");
535 // cut off at the bottom
536 if (value >= d->scrollbarParameters_.max) {
537 DocIterator dit = doc_iterator_end(buffer_.inset());
540 LYXERR(Debug::SCROLLING, "scroll to bottom");
544 // find paragraph at target position
545 int par_pos = d->scrollbarParameters_.min;
547 for (; i != int(d->par_height_.size()); ++i) {
548 par_pos += d->par_height_[i];
549 if (par_pos >= value)
553 if (par_pos < value) {
554 // It seems we didn't find the correct pit so stay on the safe side and
556 LYXERR0("scrolling position not found!");
557 scrollDocView(d->scrollbarParameters_.max);
561 DocIterator dit = doc_iterator_begin(buffer_.inset());
563 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
568 // FIXME: this method is not working well.
569 void BufferView::setCursorFromScrollbar()
571 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
573 int const height = 2 * defaultRowHeight();
574 int const first = height;
575 int const last = height_ - height;
576 Cursor & cur = d->cursor_;
578 switch (cursorStatus(cur)) {
580 // We reset the cursor because cursorStatus() does not
581 // work when the cursor is within mathed.
582 cur.reset(buffer_.inset());
583 tm.setCursorFromCoordinates(cur, 0, first);
584 cur.clearSelection();
587 // We reset the cursor because cursorStatus() does not
588 // work when the cursor is within mathed.
589 cur.reset(buffer_.inset());
590 tm.setCursorFromCoordinates(cur, 0, last);
591 cur.clearSelection();
594 int const y = getPos(cur, cur.boundary()).y_;
595 int const newy = min(last, max(y, first));
597 cur.reset(buffer_.inset());
598 tm.setCursorFromCoordinates(cur, 0, newy);
604 Change const BufferView::getCurrentChange() const
606 if (!d->cursor_.selection())
607 return Change(Change::UNCHANGED);
609 DocIterator dit = d->cursor_.selectionBegin();
610 return dit.paragraph().lookupChange(dit.pos());
614 // this could be used elsewhere as well?
615 // FIXME: This does not work within mathed!
616 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
618 Point const p = getPos(dit, dit.boundary());
621 if (p.y_ > workHeight())
627 void BufferView::saveBookmark(unsigned int idx)
629 // tenatively save bookmark, id and pos will be used to
630 // acturately locate a bookmark in a 'live' lyx session.
631 // pit and pos will be updated with bottom level pit/pos
633 LyX::ref().session().bookmarks().save(
635 d->cursor_.bottom().pit(),
636 d->cursor_.bottom().pos(),
637 d->cursor_.paragraph().id(),
642 // emit message signal.
643 message(_("Save bookmark"));
647 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
648 int top_id, pos_type top_pos)
650 bool success = false;
653 d->cursor_.clearSelection();
655 // if a valid par_id is given, try it first
656 // This is the case for a 'live' bookmark when unique paragraph ID
657 // is used to track bookmarks.
659 dit = buffer_.getParFromID(top_id);
661 dit.pos() = min(dit.paragraph().size(), top_pos);
662 // Some slices of the iterator may not be
663 // reachable (e.g. closed collapsable inset)
664 // so the dociterator may need to be
665 // shortened. Otherwise, setCursor may crash
666 // lyx when the cursor can not be set to these
668 size_t const n = dit.depth();
669 for (size_t i = 0; i < n; ++i)
670 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
678 // if top_id == 0, or searching through top_id failed
679 // This is the case for a 'restored' bookmark when only bottom
680 // (document level) pit was saved. Because of this, bookmark
681 // restoration is inaccurate. If a bookmark was within an inset,
682 // it will be restored to the left of the outmost inset that contains
684 if (bottom_pit < int(buffer_.paragraphs().size())) {
685 dit = doc_iterator_begin(buffer_.inset());
687 dit.pit() = bottom_pit;
688 dit.pos() = min(bottom_pos, dit.paragraph().size());
693 // Note: only bottom (document) level pit is set.
695 // set the current font.
696 d->cursor_.setCurrentFont();
697 // To center the screen on this new position we need the
698 // paragraph position which is computed at draw() time.
699 // So we need a redraw!
709 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
711 if (lyxrc.rtl_support) {
712 if (d->cursor_.real_current_font.isRightToLeft()) {
713 if (d->intl_.keymap == Intl::PRIMARY)
714 d->intl_.keyMapSec();
716 if (d->intl_.keymap == Intl::SECONDARY)
717 d->intl_.keyMapPrim();
721 d->intl_.getTransManager().translateAndInsert(c, t, cur);
725 int BufferView::workWidth() const
731 void BufferView::showCursor()
733 showCursor(d->cursor_);
737 void BufferView::showCursor(DocIterator const & dit)
739 // We are not properly started yet, delay until resizing is
744 LYXERR(Debug::SCROLLING, "recentering!");
746 CursorSlice const & bot = dit.bottom();
747 TextMetrics & tm = d->text_metrics_[bot.text()];
749 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
750 int bot_pit = bot.pit();
751 if (bot_pit > max_pit) {
752 // FIXME: Why does this happen?
753 LYXERR0("bottom pit is greater that max pit: "
754 << bot_pit << " > " << max_pit);
758 if (bot_pit == tm.first().first - 1)
759 tm.newParMetricsUp();
760 else if (bot_pit == tm.last().first + 1)
761 tm.newParMetricsDown();
763 if (tm.has(bot_pit)) {
764 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
765 BOOST_ASSERT(!pm.rows().empty());
766 // FIXME: smooth scrolling doesn't work in mathed.
767 CursorSlice const & cs = dit.innerTextSlice();
768 int offset = coordOffset(dit, dit.boundary()).y_;
769 int ypos = pm.position() + offset;
770 Dimension const & row_dim =
771 pm.getRow(cs.pos(), dit.boundary()).dimension();
772 if (ypos - row_dim.ascent() < 0)
773 scrollUp(- ypos + row_dim.ascent());
774 else if (ypos + row_dim.descent() > height_)
775 scrollDown(ypos - height_ + row_dim.descent());
776 // else, nothing to do, the cursor is already visible so we just return.
780 tm.redoParagraph(bot_pit);
781 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
782 int offset = coordOffset(dit, dit.boundary()).y_;
784 d->anchor_pit_ = bot_pit;
785 CursorSlice const & cs = dit.innerTextSlice();
786 Dimension const & row_dim =
787 pm.getRow(cs.pos(), dit.boundary()).dimension();
789 if (d->anchor_pit_ == 0)
790 d->anchor_ypos_ = offset + pm.ascent();
791 else if (d->anchor_pit_ == max_pit)
792 d->anchor_ypos_ = height_ - offset - row_dim.descent();
794 d->anchor_ypos_ = defaultRowHeight() * 2 - offset - row_dim.descent();
801 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
805 Cursor & cur = d->cursor_;
807 switch (cmd.action) {
810 flag.enabled(buffer_.undo().hasUndoStack());
813 flag.enabled(buffer_.undo().hasRedoStack());
815 case LFUN_FILE_INSERT:
816 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
817 case LFUN_FILE_INSERT_PLAINTEXT:
818 case LFUN_BOOKMARK_SAVE:
819 // FIXME: Actually, these LFUNS should be moved to Text
820 flag.enabled(cur.inTexted());
822 case LFUN_FONT_STATE:
823 case LFUN_LABEL_INSERT:
824 case LFUN_INFO_INSERT:
825 case LFUN_PARAGRAPH_GOTO:
827 case LFUN_REFERENCE_NEXT:
829 case LFUN_WORD_REPLACE:
832 case LFUN_MARK_TOGGLE:
833 case LFUN_SCREEN_RECENTER:
834 case LFUN_BIBTEX_DATABASE_ADD:
835 case LFUN_BIBTEX_DATABASE_DEL:
836 case LFUN_STATISTICS:
837 case LFUN_NEXT_INSET_TOGGLE:
841 case LFUN_LABEL_GOTO: {
842 flag.enabled(!cmd.argument().empty()
843 || getInsetByCode<InsetRef>(cur, REF_CODE));
847 case LFUN_CHANGES_TRACK:
849 flag.setOnOff(buffer_.params().trackChanges);
852 case LFUN_CHANGES_OUTPUT:
854 flag.setOnOff(buffer_.params().outputChanges);
857 case LFUN_CHANGES_MERGE:
858 case LFUN_CHANGE_NEXT:
859 case LFUN_ALL_CHANGES_ACCEPT:
860 case LFUN_ALL_CHANGES_REJECT:
861 // TODO: context-sensitive enabling of LFUNs
862 // In principle, these command should only be enabled if there
863 // is a change in the document. However, without proper
864 // optimizations, this will inevitably result in poor performance.
868 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
869 flag.setOnOff(buffer_.params().compressed);
873 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
874 flag.setOnOff(buffer_.params().embedded);
879 case LFUN_SCREEN_DOWN:
884 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
885 // everywhere else before this can enabled:
886 case LFUN_SCREEN_UP_SELECT:
887 case LFUN_SCREEN_DOWN_SELECT:
891 case LFUN_LAYOUT_TABULAR:
892 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
896 case LFUN_LAYOUT_PARAGRAPH:
897 flag.enabled(cur.inset().allowParagraphCustomization(cur.idx()));
900 case LFUN_INSET_SETTINGS: {
901 InsetCode code = cur.inset().lyxCode();
905 enable = cmd.argument() == "tabular";
908 enable = cmd.argument() == "ert";
911 enable = cmd.argument() == "float";
914 enable = cmd.argument() == "wrap";
917 enable = cmd.argument() == "note";
920 enable = cmd.argument() == "branch";
923 enable = cmd.argument() == "box";
926 enable = cmd.argument() == "listings";
931 flag.enabled(enable);
935 case LFUN_DIALOG_SHOW_NEW_INSET:
936 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
937 cur.inset().lyxCode() != LISTINGS_CODE);
938 if (cur.inset().lyxCode() == CAPTION_CODE) {
940 if (cur.inset().getStatus(cur, cmd, flag))
953 bool BufferView::dispatch(FuncRequest const & cmd)
955 //lyxerr << [ cmd = " << cmd << "]" << endl;
957 // Make sure that the cached BufferView is correct.
958 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
959 << " arg[" << to_utf8(cmd.argument()) << ']'
960 << " x[" << cmd.x << ']'
961 << " y[" << cmd.y << ']'
962 << " button[" << cmd.button() << ']');
964 Cursor & cur = d->cursor_;
966 switch (cmd.action) {
969 cur.message(_("Undo"));
970 cur.clearSelection();
972 cur.message(_("No further undo information"));
974 processUpdateFlags(Update::Force | Update::FitCursor);
978 cur.message(_("Redo"));
979 cur.clearSelection();
981 cur.message(_("No further redo information"));
983 processUpdateFlags(Update::Force | Update::FitCursor);
986 case LFUN_FONT_STATE:
987 cur.message(cur.currentState());
990 case LFUN_BOOKMARK_SAVE:
991 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
994 case LFUN_LABEL_GOTO: {
995 docstring label = cmd.argument();
998 getInsetByCode<InsetRef>(d->cursor_,
1001 label = inset->getParam("reference");
1002 // persistent=false: use temp_bookmark
1012 case LFUN_PARAGRAPH_GOTO: {
1013 int const id = convert<int>(to_utf8(cmd.argument()));
1015 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1016 b = theBufferList().next(b)) {
1018 DocIterator dit = b->getParFromID(id);
1020 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1024 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1025 << " found in buffer `"
1026 << b->absFileName() << "'.");
1028 if (b == &buffer_) {
1031 processUpdateFlags(Update::Force | Update::FitCursor);
1033 // Switch to other buffer view and resend cmd
1034 theLyXFunc().dispatch(FuncRequest(
1035 LFUN_BUFFER_SWITCH, b->absFileName()));
1036 theLyXFunc().dispatch(cmd);
1043 case LFUN_NOTE_NEXT:
1044 gotoInset(this, NOTE_CODE, false);
1047 case LFUN_REFERENCE_NEXT: {
1048 vector<InsetCode> tmp;
1049 tmp.push_back(LABEL_CODE);
1050 tmp.push_back(REF_CODE);
1051 gotoInset(this, tmp, true);
1055 case LFUN_CHANGES_TRACK:
1056 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1059 case LFUN_CHANGES_OUTPUT:
1060 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1061 if (buffer_.params().outputChanges) {
1062 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1063 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1064 LaTeXFeatures::isAvailable("xcolor");
1066 if (!dvipost && !xcolorsoul) {
1067 Alert::warning(_("Changes not shown in LaTeX output"),
1068 _("Changes will not be highlighted in LaTeX output, "
1069 "because neither dvipost nor xcolor/soul are installed.\n"
1070 "Please install these packages or redefine "
1071 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1072 } else if (!xcolorsoul) {
1073 Alert::warning(_("Changes not shown in LaTeX output"),
1074 _("Changes will not be highlighted in LaTeX output "
1075 "when using pdflatex, because xcolor and soul are not installed.\n"
1076 "Please install both packages or redefine "
1077 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1082 case LFUN_CHANGE_NEXT:
1083 findNextChange(this);
1086 case LFUN_CHANGES_MERGE:
1087 if (findNextChange(this))
1088 showDialog("changes");
1091 case LFUN_ALL_CHANGES_ACCEPT:
1092 // select complete document
1093 d->cursor_.reset(buffer_.inset());
1094 d->cursor_.selHandle(true);
1095 buffer_.text().cursorBottom(d->cursor_);
1096 // accept everything in a single step to support atomic undo
1097 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1100 case LFUN_ALL_CHANGES_REJECT:
1101 // select complete document
1102 d->cursor_.reset(buffer_.inset());
1103 d->cursor_.selHandle(true);
1104 buffer_.text().cursorBottom(d->cursor_);
1105 // reject everything in a single step to support atomic undo
1106 // Note: reject does not work recursively; the user may have to repeat the operation
1107 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1110 case LFUN_WORD_FIND:
1111 if (find(this, cmd))
1114 message(_("String not found!"));
1117 case LFUN_WORD_REPLACE: {
1118 bool has_deleted = false;
1119 if (cur.selection()) {
1120 DocIterator beg = cur.selectionBegin();
1121 DocIterator end = cur.selectionEnd();
1122 if (beg.pit() == end.pit()) {
1123 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1124 if (cur.paragraph().isDeleted(p))
1129 replace(this, cmd, has_deleted);
1134 cur.clearSelection();
1136 cur.message(from_utf8(N_("Mark off")));
1140 cur.clearSelection();
1143 cur.message(from_utf8(N_("Mark on")));
1146 case LFUN_MARK_TOGGLE:
1147 cur.clearSelection();
1150 cur.message(from_utf8(N_("Mark removed")));
1153 cur.message(from_utf8(N_("Mark set")));
1158 case LFUN_SCREEN_RECENTER:
1162 case LFUN_BIBTEX_DATABASE_ADD: {
1163 Cursor tmpcur = d->cursor_;
1164 findInset(tmpcur, BIBTEX_CODE, false);
1165 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1168 if (inset->addDatabase(to_utf8(cmd.argument())))
1169 buffer_.updateBibfilesCache();
1174 case LFUN_BIBTEX_DATABASE_DEL: {
1175 Cursor tmpcur = d->cursor_;
1176 findInset(tmpcur, BIBTEX_CODE, false);
1177 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1180 if (inset->delDatabase(to_utf8(cmd.argument())))
1181 buffer_.updateBibfilesCache();
1186 case LFUN_STATISTICS: {
1187 DocIterator from, to;
1188 if (cur.selection()) {
1189 from = cur.selectionBegin();
1190 to = cur.selectionEnd();
1192 from = doc_iterator_begin(buffer_.inset());
1193 to = doc_iterator_end(buffer_.inset());
1195 int const words = countWords(from, to);
1196 int const chars = countChars(from, to, false);
1197 int const chars_blanks = countChars(from, to, true);
1199 if (cur.selection())
1200 message = _("Statistics for the selection:");
1202 message = _("Statistics for the document:");
1205 message += bformat(_("%1$d words"), words);
1207 message += _("One word");
1209 if (chars_blanks != 1)
1210 message += bformat(_("%1$d characters (including blanks)"),
1213 message += _("One character (including blanks)");
1216 message += bformat(_("%1$d characters (excluding blanks)"),
1219 message += _("One character (excluding blanks)");
1221 Alert::information(_("Statistics"), message);
1225 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1226 // turn compression on/off
1227 buffer_.params().compressed = !buffer_.params().compressed;
1230 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
1231 // turn embedding on/off
1233 buffer_.embeddedFiles().enable(!buffer_.params().embedded, buffer_);
1234 } catch (ExceptionMessage const & message) {
1235 Alert::error(message.title_, message.details_);
1240 case LFUN_NEXT_INSET_TOGGLE: {
1241 // this is the real function we want to invoke
1242 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1243 // if there is an inset at cursor, see whether it
1245 Inset * inset = cur.nextInset();
1247 if (inset->isActive()) {
1248 Cursor tmpcur = cur;
1249 tmpcur.pushBackward(*inset);
1250 inset->dispatch(tmpcur, tmpcmd);
1251 if (tmpcur.result().dispatched()) {
1254 } else if (inset->editable() == Inset::IS_EDITABLE) {
1255 inset->edit(cur, true);
1258 // if it did not work, try the underlying inset.
1259 if (!cur.result().dispatched())
1260 cur.dispatch(tmpcmd);
1262 if (!cur.result().dispatched())
1263 // It did not work too; no action needed.
1265 cur.clearSelection();
1266 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1270 case LFUN_SCREEN_UP:
1271 case LFUN_SCREEN_DOWN: {
1272 Point p = getPos(cur, cur.boundary());
1273 if (p.y_ < 0 || p.y_ > height_) {
1274 // The cursor is off-screen so recenter before proceeding.
1276 p = getPos(cur, cur.boundary());
1278 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1279 cur.reset(buffer_.inset());
1280 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1281 //FIXME: what to do with cur.x_target()?
1290 case LFUN_SCREEN_UP_SELECT:
1291 case LFUN_SCREEN_DOWN_SELECT: {
1292 // Those two are not ready yet for consumption.
1295 cur.selHandle(true);
1296 size_t initial_depth = cur.depth();
1297 Point const p = getPos(cur, cur.boundary());
1298 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1299 // FIXME: We need to verify if the cursor stayed within an inset...
1300 //cur.reset(buffer_.inset());
1301 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1303 while (cur.depth() > initial_depth) {
1306 // FIXME: we need to do a redraw again because of the selection
1307 // But no screen update is needed.
1308 d->update_strategy_ = NoScreenUpdate;
1321 docstring const BufferView::requestSelection()
1323 Cursor & cur = d->cursor_;
1325 if (!cur.selection()) {
1326 d->xsel_cache_.set = false;
1330 if (!d->xsel_cache_.set ||
1331 cur.top() != d->xsel_cache_.cursor ||
1332 cur.anchor_.top() != d->xsel_cache_.anchor)
1334 d->xsel_cache_.cursor = cur.top();
1335 d->xsel_cache_.anchor = cur.anchor_.top();
1336 d->xsel_cache_.set = cur.selection();
1337 return cur.selectionAsString(false);
1343 void BufferView::clearSelection()
1345 d->cursor_.clearSelection();
1346 // Clear the selection buffer. Otherwise a subsequent
1347 // middle-mouse-button paste would use the selection buffer,
1348 // not the more current external selection.
1349 cap::clearSelection();
1350 d->xsel_cache_.set = false;
1351 // The buffer did not really change, but this causes the
1352 // redraw we need because we cleared the selection above.
1357 void BufferView::resize(int width, int height)
1359 bool initialResize = (height_ == 0);
1361 // Update from work area
1365 // Clear the paragraph height cache.
1366 d->par_height_.clear();
1370 // view got his initial size, make sure that
1371 // the cursor has a proper position
1372 if (initialResize) {
1379 Inset const * BufferView::getCoveringInset(Text const & text,
1382 TextMetrics & tm = d->text_metrics_[&text];
1383 Inset * inset = tm.checkInsetHit(x, y);
1387 if (!inset->descendable())
1388 // No need to go further down if the inset is not
1392 size_t cell_number = inset->nargs();
1393 // Check all the inner cell.
1394 for (size_t i = 0; i != cell_number; ++i) {
1395 Text const * inner_text = inset->getText(i);
1398 Inset const * inset_deeper =
1399 getCoveringInset(*inner_text, x, y);
1401 return inset_deeper;
1409 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1411 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1413 // This is only called for mouse related events including
1414 // LFUN_FILE_OPEN generated by drag-and-drop.
1415 FuncRequest cmd = cmd0;
1418 cur.push(buffer_.inset());
1419 cur.selection() = d->cursor_.selection();
1421 // Either the inset under the cursor or the
1422 // surrounding Text will handle this event.
1424 // make sure we stay within the screen...
1425 cmd.y = min(max(cmd.y, -1), height_);
1427 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1429 // Get inset under mouse, if there is one.
1430 Inset const * covering_inset =
1431 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1432 if (covering_inset == d->last_inset_)
1433 // Same inset, no need to do anything...
1436 bool need_redraw = false;
1437 // const_cast because of setMouseHover().
1438 Inset * inset = const_cast<Inset *>(covering_inset);
1440 // Remove the hint on the last hovered inset (if any).
1441 need_redraw |= d->last_inset_->setMouseHover(false);
1443 // Highlighted the newly hovered inset (if any).
1444 need_redraw |= inset->setMouseHover(true);
1445 d->last_inset_ = inset;
1449 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1450 << cmd.x << ", " << cmd.y << ")");
1452 d->update_strategy_ = DecorationUpdate;
1454 // This event (moving without mouse click) is not passed further.
1455 // This should be changed if it is further utilized.
1460 // Build temporary cursor.
1461 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1463 // Put anchor at the same position.
1466 // Try to dispatch to an non-editable inset near this position
1467 // via the temp cursor. If the inset wishes to change the real
1468 // cursor it has to do so explicitly by using
1469 // cur.bv().cursor() = cur; (or similar)
1471 inset->dispatch(cur, cmd);
1473 // Now dispatch to the temporary cursor. If the real cursor should
1474 // be modified, the inset's dispatch has to do so explicitly.
1475 if (!cur.result().dispatched())
1478 //Do we have a selection?
1479 theSelection().haveSelection(cursor().selection());
1481 // If the command has been dispatched,
1482 if (cur.result().dispatched()
1483 // an update is asked,
1484 && cur.result().update())
1485 processUpdateFlags(cur.result().update());
1489 void BufferView::lfunScroll(FuncRequest const & cmd)
1491 string const scroll_type = cmd.getArg(0);
1492 int const scroll_step =
1493 (scroll_type == "line")? d->scrollbarParameters_.single_step
1494 : (scroll_type == "page")? d->scrollbarParameters_.page_step : 0;
1495 if (scroll_step == 0)
1497 string const scroll_quantity = cmd.getArg(1);
1498 if (scroll_quantity == "up")
1499 scrollUp(scroll_step);
1500 else if (scroll_quantity == "down")
1501 scrollDown(scroll_step);
1503 int const scroll_value = convert<int>(scroll_quantity);
1505 scroll(scroll_step * scroll_value);
1510 void BufferView::scroll(int y)
1519 void BufferView::scrollDown(int offset)
1521 Text * text = &buffer_.text();
1522 TextMetrics & tm = d->text_metrics_[text];
1523 int ymax = height_ + offset;
1525 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1526 int bottom_pos = last.second->position() + last.second->descent();
1527 if (last.first + 1 == int(text->paragraphs().size())) {
1528 if (bottom_pos <= height_)
1530 offset = min(offset, bottom_pos - height_);
1533 if (bottom_pos > ymax)
1535 tm.newParMetricsDown();
1537 d->anchor_ypos_ -= offset;
1543 void BufferView::scrollUp(int offset)
1545 Text * text = &buffer_.text();
1546 TextMetrics & tm = d->text_metrics_[text];
1547 int ymin = - offset;
1549 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1550 int top_pos = first.second->position() - first.second->ascent();
1551 if (first.first == 0) {
1554 offset = min(offset, - top_pos);
1559 tm.newParMetricsUp();
1561 d->anchor_ypos_ += offset;
1567 void BufferView::setCursorFromRow(int row)
1572 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1574 d->cursor_.reset(buffer_.inset());
1576 buffer_.text().setCursor(d->cursor_, 0, 0);
1578 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1582 void BufferView::gotoLabel(docstring const & label)
1584 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1585 vector<docstring> labels;
1586 it->getLabelList(buffer_, labels);
1587 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1596 TextMetrics const & BufferView::textMetrics(Text const * t) const
1598 return const_cast<BufferView *>(this)->textMetrics(t);
1602 TextMetrics & BufferView::textMetrics(Text const * t)
1604 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1605 if (tmc_it == d->text_metrics_.end()) {
1606 tmc_it = d->text_metrics_.insert(
1607 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1609 return tmc_it->second;
1613 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1616 return textMetrics(t).parMetrics(pit);
1620 int BufferView::workHeight() const
1626 void BufferView::setCursor(DocIterator const & dit)
1628 size_t const n = dit.depth();
1629 for (size_t i = 0; i < n; ++i)
1630 dit[i].inset().edit(d->cursor_, true);
1632 d->cursor_.setCursor(dit);
1633 d->cursor_.selection() = false;
1637 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1639 // Would be wrong to delete anything if we have a selection.
1640 if (cur.selection())
1643 bool need_anchor_change = false;
1644 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1645 need_anchor_change);
1647 if (need_anchor_change)
1655 updateLabels(buffer_);
1663 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1665 BOOST_ASSERT(&cur.bv() == this);
1668 // this event will clear selection so we save selection for
1669 // persistent selection
1670 cap::saveSelection(cursor());
1672 // Has the cursor just left the inset?
1673 bool badcursor = false;
1674 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1676 badcursor = notifyCursorLeaves(d->cursor_, cur);
1678 // FIXME: shift-mouse selection doesn't work well across insets.
1679 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1681 // do the dEPM magic if needed
1682 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1683 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1684 // the leftinset bool would not be necessary (badcursor instead).
1685 bool update = leftinset;
1686 if (!do_selection && !badcursor && d->cursor_.inTexted())
1687 update |= checkDepm(cur, d->cursor_);
1689 // if the cursor was in an empty script inset and the new
1690 // position is in the nucleus of the inset, notifyCursorLeaves
1691 // will kill the script inset itself. So we check all the
1692 // elements of the cursor to make sure that they are correct.
1693 // For an example, see bug 2933:
1694 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1695 // The code below could maybe be moved to a DocIterator method.
1696 //lyxerr << "cur before " << cur << endl;
1697 DocIterator dit = doc_iterator_begin(cur.inset());
1698 dit.bottom() = cur.bottom();
1700 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1701 dit.push_back(cur[i]);
1704 //lyxerr << "5 cur after" << dit <<endl;
1706 d->cursor_.setCursor(dit);
1707 d->cursor_.boundary(cur.boundary());
1709 d->cursor_.setSelection();
1711 d->cursor_.clearSelection();
1713 d->cursor_.finishUndo();
1714 d->cursor_.setCurrentFont();
1719 void BufferView::putSelectionAt(DocIterator const & cur,
1720 int length, bool backwards)
1722 d->cursor_.clearSelection();
1728 d->cursor_.pos() += length;
1729 d->cursor_.setSelection(d->cursor_, -length);
1731 d->cursor_.setSelection(d->cursor_, length);
1733 // Ensure a redraw happens in any case because the new selection could
1734 // possibly be on the same screen as the previous selection.
1735 processUpdateFlags(Update::Force | Update::FitCursor);
1739 Cursor & BufferView::cursor()
1745 Cursor const & BufferView::cursor() const
1751 pit_type BufferView::anchor_ref() const
1753 return d->anchor_pit_;
1757 bool BufferView::singleParUpdate()
1759 Text & buftext = buffer_.text();
1760 pit_type const bottom_pit = d->cursor_.bottom().pit();
1761 TextMetrics & tm = textMetrics(&buftext);
1762 int old_height = tm.parMetrics(bottom_pit).height();
1764 // In Single Paragraph mode, rebreak only
1765 // the (main text, not inset!) paragraph containing the cursor.
1766 // (if this paragraph contains insets etc., rebreaking will
1767 // recursively descend)
1768 tm.redoParagraph(bottom_pit);
1769 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1770 if (pm.height() != old_height)
1771 // Paragraph height has changed so we cannot proceed to
1772 // the singlePar optimisation.
1775 d->update_strategy_ = SingleParUpdate;
1777 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1778 << " y2: " << pm.position() + pm.descent()
1779 << " pit: " << bottom_pit
1780 << " singlepar: 1");
1785 void BufferView::updateMetrics()
1787 Text & buftext = buffer_.text();
1788 pit_type const npit = int(buftext.paragraphs().size());
1790 // Clear out the position cache in case of full screen redraw,
1791 d->coord_cache_.clear();
1793 // Clear out paragraph metrics to avoid having invalid metrics
1794 // in the cache from paragraphs not relayouted below
1795 // The complete text metrics will be redone.
1796 d->text_metrics_.clear();
1798 TextMetrics & tm = textMetrics(&buftext);
1800 // Rebreak anchor paragraph.
1801 tm.redoParagraph(d->anchor_pit_);
1802 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1805 if (d->anchor_pit_ == 0) {
1806 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
1808 // Complete buffer visible? Then it's easy.
1809 if (scrollRange == 0)
1810 d->anchor_ypos_ = anchor_pm.ascent();
1812 // FIXME: Some clever handling needed to show
1813 // the _first_ paragraph up to the top if the cursor is
1814 // in the first line.
1816 anchor_pm.setPosition(d->anchor_ypos_);
1818 LYXERR(Debug::PAINTING, "metrics: "
1819 << " anchor pit = " << d->anchor_pit_
1820 << " anchor ypos = " << d->anchor_ypos_);
1822 // Redo paragraphs above anchor if necessary.
1823 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1824 // We are now just above the anchor paragraph.
1825 pit_type pit1 = d->anchor_pit_ - 1;
1826 for (; pit1 >= 0 && y1 >= 0; --pit1) {
1827 tm.redoParagraph(pit1);
1828 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1830 // Save the paragraph position in the cache.
1835 // Redo paragraphs below the anchor if necessary.
1836 int y2 = d->anchor_ypos_ + anchor_pm.descent();
1837 // We are now just below the anchor paragraph.
1838 pit_type pit2 = d->anchor_pit_ + 1;
1839 for (; pit2 < npit && y2 <= height_; ++pit2) {
1840 tm.redoParagraph(pit2);
1841 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1843 // Save the paragraph position in the cache.
1848 LYXERR(Debug::PAINTING, "Metrics: "
1849 << " anchor pit = " << d->anchor_pit_
1850 << " anchor ypos = " << d->anchor_ypos_
1853 << " pit1 = " << pit1
1854 << " pit2 = " << pit2);
1856 d->update_strategy_ = FullScreenUpdate;
1858 if (lyxerr.debugging(Debug::WORKAREA)) {
1859 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1860 d->coord_cache_.dump();
1865 void BufferView::insertLyXFile(FileName const & fname)
1867 BOOST_ASSERT(d->cursor_.inTexted());
1869 // Get absolute path of file and add ".lyx"
1870 // to the filename if necessary
1871 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1873 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1874 // emit message signal.
1875 message(bformat(_("Inserting document %1$s..."), disp_fn));
1878 Buffer buf("", false);
1879 if (buf.loadLyXFile(filename)) {
1880 ErrorList & el = buffer_.errorList("Parse");
1881 // Copy the inserted document error list into the current buffer one.
1882 el = buf.errorList("Parse");
1883 buffer_.undo().recordUndo(d->cursor_);
1884 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1885 buf.params().getTextClassPtr(), el);
1886 res = _("Document %1$s inserted.");
1888 res = _("Could not insert document %1$s");
1893 // emit message signal.
1894 message(bformat(res, disp_fn));
1895 buffer_.errors("Parse");
1899 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1905 // Addup contribution of nested insets, from inside to outside,
1906 // keeping the outer paragraph for a special handling below
1907 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1908 CursorSlice const & sl = dit[i];
1912 // get relative position inside sl.inset()
1913 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1915 // Make relative position inside of the edited inset relative to sl.inset()
1919 // In case of an RTL inset, the edited inset will be positioned to the left
1922 bool boundary_i = boundary && i + 1 == dit.depth();
1923 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1928 // remember width for the case that sl.inset() is positioned in an RTL inset
1929 if (i && dit[i - 1].text()) {
1930 // If this Inset is inside a Text Inset, retrieve the Dimension
1931 // from the containing text instead of using Inset::dimension() which
1932 // might not be implemented.
1933 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1934 // elimination of Inset::dim_ cache. This coordOffset() method needs
1935 // to be rewritten in light of the new design.
1936 Dimension const & dim = parMetrics(dit[i - 1].text(),
1937 dit[i - 1].pit()).insetDimension(&sl.inset());
1940 Dimension const dim = sl.inset().dimension(*this);
1944 //lyxerr << "Cursor::getPos, i: "
1945 // << i << " x: " << xx << " y: " << y << endl;
1948 // Add contribution of initial rows of outermost paragraph
1949 CursorSlice const & sl = dit[0];
1950 TextMetrics const & tm = textMetrics(sl.text());
1951 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1952 BOOST_ASSERT(!pm.rows().empty());
1953 y -= pm.rows()[0].ascent();
1955 // FIXME: document this mess
1957 if (sl.pos() > 0 && dit.depth() == 1) {
1959 if (pos && boundary)
1961 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
1962 rend = pm.pos2row(pos);
1964 rend = pm.pos2row(sl.pos());
1966 size_t rend = pm.pos2row(sl.pos());
1968 for (size_t rit = 0; rit != rend; ++rit)
1969 y += pm.rows()[rit].height();
1970 y += pm.rows()[rend].ascent();
1972 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1974 // Make relative position from the nested inset now bufferview absolute.
1975 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1978 // In the RTL case place the nested inset at the left of the cursor in
1979 // the outer paragraph
1980 bool boundary_1 = boundary && 1 == dit.depth();
1981 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1989 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1991 CursorSlice const & bot = dit.bottom();
1992 TextMetrics const & tm = textMetrics(bot.text());
1993 if (!tm.has(bot.pit()))
1994 return Point(-1, -1);
1996 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1997 p.y_ += tm.parMetrics(bot.pit()).position();
2002 void BufferView::draw(frontend::Painter & pain)
2004 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2005 Text & text = buffer_.text();
2006 TextMetrics const & tm = d->text_metrics_[&text];
2007 int const y = tm.first().second->position();
2008 PainterInfo pi(this, pain);
2010 switch (d->update_strategy_) {
2012 case NoScreenUpdate:
2013 // If no screen painting is actually needed, only some the different
2014 // coordinates of insets and paragraphs needs to be updated.
2015 pi.full_repaint = true;
2016 pi.pain.setDrawingEnabled(false);
2020 case SingleParUpdate:
2021 pi.full_repaint = false;
2022 // In general, only the current row of the outermost paragraph
2023 // will be redrawn. Particular cases where selection spans
2024 // multiple paragraph are correctly detected in TextMetrics.
2028 case DecorationUpdate:
2029 // FIXME: We should also distinguish DecorationUpdate to avoid text
2030 // drawing if possible. This is not possible to do easily right now
2031 // because of the single backing pixmap.
2033 case FullScreenUpdate:
2034 // The whole screen, including insets, will be refreshed.
2035 pi.full_repaint = true;
2037 // Clear background.
2038 pain.fillRectangle(0, 0, width_, height_,
2039 buffer_.inset().backgroundColor());
2044 // and possibly grey out below
2045 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2046 int const y2 = lastpm.second->position() + lastpm.second->descent();
2048 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2051 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2053 // The scrollbar needs an update.
2056 // Normalize anchor for next time
2057 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2058 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2059 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2060 ParagraphMetrics const & pm = tm.parMetrics(pit);
2061 if (pm.position() + pm.descent() > 0) {
2062 d->anchor_pit_ = pit;
2063 d->anchor_ypos_ = pm.position();
2067 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2068 << " anchor ypos = " << d->anchor_ypos_);
2072 void BufferView::message(docstring const & msg)
2075 d->gui_->message(msg);
2079 void BufferView::showDialog(string const & name)
2082 d->gui_->showDialog(name, string());
2086 void BufferView::showDialog(string const & name,
2087 string const & data, Inset * inset)
2090 d->gui_->showDialog(name, data, inset);
2094 void BufferView::updateDialog(string const & name, string const & data)
2097 d->gui_->updateDialog(name, data);
2101 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2107 // FIXME: Move this out of BufferView again
2108 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2110 if (!fname.isReadableFile()) {
2111 docstring const error = from_ascii(strerror(errno));
2112 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2113 docstring const text =
2114 bformat(_("Could not read the specified document\n"
2115 "%1$s\ndue to the error: %2$s"), file, error);
2116 Alert::error(_("Could not read file"), text);
2120 if (!fname.isReadableFile()) {
2121 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2122 docstring const text =
2123 bformat(_("%1$s\n is not readable."), file);
2124 Alert::error(_("Could not open file"), text);
2128 // FIXME UNICODE: We don't know the encoding of the file
2129 docstring file_content = fname.fileContents("UTF-8");
2130 if (file_content.empty()) {
2131 Alert::error(_("Reading not UTF-8 encoded file"),
2132 _("The file is not UTF-8 encoded.\n"
2133 "It will be read as local 8Bit-encoded.\n"
2134 "If this does not give the correct result\n"
2135 "then please change the encoding of the file\n"
2136 "to UTF-8 with a program other than LyX.\n"));
2137 file_content = fname.fileContents("local8bit");
2140 return normalize_c(file_content);
2144 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2146 docstring const tmpstr = contentsOfPlaintextFile(f);
2151 Cursor & cur = cursor();
2152 cap::replaceSelection(cur);
2153 buffer_.undo().recordUndo(cur);
2155 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2157 cur.innerText()->insertStringAsLines(cur, tmpstr);