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/Delegates.h"
62 #include "frontends/FontMetrics.h"
63 #include "frontends/Painter.h"
64 #include "frontends/Selection.h"
66 #include "graphics/Previews.h"
68 #include "support/convert.h"
69 #include "support/debug.h"
70 #include "support/FileFilterList.h"
71 #include "support/filetools.h"
72 #include "support/gettext.h"
73 #include "support/lstrings.h"
74 #include "support/Package.h"
75 #include "support/types.h"
87 using support::addPath;
88 using support::bformat;
89 using support::FileFilterList;
90 using support::FileName;
91 using support::fileSearch;
92 using support::makeDisplayPath;
93 using support::makeAbsPath;
94 using support::package;
96 namespace Alert = frontend::Alert;
100 /// Return an inset of this class if it exists at the current cursor position
102 T * getInsetByCode(Cursor const & cur, InsetCode code)
104 DocIterator it = cur;
105 Inset * inset = it.nextInset();
106 if (inset && inset->lyxCode() == code)
107 return static_cast<T*>(inset);
112 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
115 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
116 docstring const & contents)
118 DocIterator tmpdit = dit;
121 Inset const * inset = tmpdit.nextInset();
123 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
124 && (contents.empty() ||
125 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
129 tmpdit.forwardInset();
136 /// Looks for next inset with one of the given codes.
137 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
141 DocIterator tmpdit = dit;
142 tmpdit.forwardInset();
147 Inset const * inset = tmpdit.nextInset();
149 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
150 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
154 if (!findNextInset(tmpdit, codes, contents)) {
155 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
156 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
157 if (!findNextInset(tmpdit, codes, contents))
168 /// Looks for next inset with the given code
169 void findInset(DocIterator & dit, InsetCode code, bool same_content)
171 findInset(dit, vector<InsetCode>(1, code), same_content);
175 /// Moves cursor to the next inset with one of the given codes.
176 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
179 Cursor tmpcur = bv->cursor();
180 if (!findInset(tmpcur, codes, same_content)) {
181 bv->cursor().message(_("No more insets"));
185 tmpcur.clearSelection();
186 bv->setCursor(tmpcur);
190 /// Moves cursor to the next inset with given code.
191 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
193 gotoInset(bv, vector<InsetCode>(1, code), same_content);
197 /// A map from a Text to the associated text metrics
198 typedef std::map<Text const *, TextMetrics> TextMetricsCache;
200 enum ScreenUpdateStrategy {
210 /////////////////////////////////////////////////////////////////////
214 /////////////////////////////////////////////////////////////////////
216 struct BufferView::Private
218 Private(BufferView & bv): wh_(0), cursor_(bv),
219 anchor_ref_(0), offset_ref_(0), need_centering_(false),
220 last_inset_(0), gui_(0)
224 ScrollbarParameters scrollbarParameters_;
226 ScreenUpdateStrategy update_strategy_;
228 CoordCache coord_cache_;
230 /// Estimated average par height for scrollbar.
232 /// this is used to handle XSelection events in the right manner.
241 pit_type anchor_ref_;
245 bool need_centering_;
247 /// keyboard mapping object.
250 /// last visited inset.
251 /** kept to send setMouseHover(false).
252 * Not owned, so don't delete.
256 mutable TextMetricsCache text_metrics_;
259 /** Not owned, so don't delete.
261 frontend::GuiBufferViewDelegate * gui_;
265 BufferView::BufferView(Buffer & buf)
266 : width_(0), height_(0), buffer_(buf), d(new Private(*this))
268 d->xsel_cache_.set = false;
269 d->intl_.initKeyMapper(lyxrc.use_kbmap);
271 d->cursor_.push(buffer_.inset());
272 d->cursor_.resetAnchor();
273 d->cursor_.setCurrentFont();
275 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
276 graphics::Previews::get().generateBufferPreviews(buffer_);
280 BufferView::~BufferView()
282 // current buffer is going to be switched-off, save cursor pos
283 // Ideally, the whole cursor stack should be saved, but session
284 // currently can only handle bottom (whole document) level pit and pos.
285 // That is to say, if a cursor is in a nested inset, it will be
286 // restore to the left of the top level inset.
287 LastFilePosSection::FilePos fp;
288 fp.pit = d->cursor_.bottom().pit();
289 fp.pos = d->cursor_.bottom().pos();
290 LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
296 Intl & BufferView::getIntl()
302 Intl const & BufferView::getIntl() const
308 CoordCache & BufferView::coordCache()
310 return d->coord_cache_;
314 CoordCache const & BufferView::coordCache() const
316 return d->coord_cache_;
320 Buffer & BufferView::buffer()
326 Buffer const & BufferView::buffer() const
332 bool BufferView::fitCursor()
334 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
335 frontend::FontMetrics const & fm =
336 theFontMetrics(d->cursor_.getFont().fontInfo());
337 int const asc = fm.maxAscent();
338 int const des = fm.maxDescent();
339 Point const p = getPos(d->cursor_, d->cursor_.boundary());
340 if (p.y_ - asc >= 0 && p.y_ + des < height_)
348 void BufferView::processUpdateFlags(Update::flags flags)
350 // last_inset_ points to the last visited inset. This pointer may become
351 // invalid because of keyboard editing. Since all such operations
352 // causes screen update(), I reset last_inset_ to avoid such a problem.
354 // This is close to a hot-path.
355 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
356 << "[fitcursor = " << (flags & Update::FitCursor)
357 << ", forceupdate = " << (flags & Update::Force)
358 << ", singlepar = " << (flags & Update::SinglePar)
359 << "] buffer: " << &buffer_);
361 // Update macro store
362 if (!(cursor().inMathed() && cursor().inMacroMode()))
363 buffer_.updateMacros();
365 // Now do the first drawing step if needed. This consists on updating
366 // the CoordCache in updateMetrics().
367 // The second drawing step is done in WorkArea::redraw() if needed.
369 // Case when no explicit update is requested.
371 // no need to redraw anything.
372 d->update_strategy_ = NoScreenUpdate;
376 if (flags == Update::Decoration) {
377 d->update_strategy_ = DecorationUpdate;
382 if (flags == Update::FitCursor
383 || flags == (Update::Decoration | Update::FitCursor)) {
384 bool const fit_cursor = fitCursor();
385 // tell the frontend to update the screen if needed.
391 if (flags & Update::Decoration) {
392 d->update_strategy_ = DecorationUpdate;
396 // no screen update is needed.
397 d->update_strategy_ = NoScreenUpdate;
401 bool const full_metrics = flags & Update::Force;
403 if (full_metrics || !singleParUpdate())
404 // We have to update the full screen metrics.
407 if (!(flags & Update::FitCursor)) {
412 //FIXME: updateMetrics() does not update paragraph position
413 // This is done at draw() time. So we need a redraw!
416 // The screen has already been updated thanks to the
417 // 'buffer_.changed()' call three line above. So no need
421 // The screen has been recentered around the cursor position so
428 void BufferView::updateScrollbar()
430 Text & t = buffer_.text();
431 TextMetrics & tm = d->text_metrics_[&t];
433 int const parsize = int(t.paragraphs().size() - 1);
434 if (d->anchor_ref_ > parsize) {
435 d->anchor_ref_ = parsize;
439 LYXERR(Debug::GUI, " Updating scrollbar: height: "
440 << t.paragraphs().size()
441 << " curr par: " << d->cursor_.bottom().pit()
442 << " default height " << defaultRowHeight());
444 // It would be better to fix the scrollbar to understand
445 // values in [0..1] and divide everything by wh
447 // estimated average paragraph height:
449 d->wh_ = height_ / 4;
451 int h = tm.parMetrics(d->anchor_ref_).height();
453 // Normalize anchor/offset (MV):
454 while (d->offset_ref_ > h && d->anchor_ref_ < parsize) {
457 h = tm.parMetrics(d->anchor_ref_).height();
459 // Look at paragraph heights on-screen
462 for (pit_type pit = d->anchor_ref_; pit <= parsize; ++pit) {
465 int const h2 = tm.parMetrics(pit).height();
471 int const hav = sumh / nh;
472 // More realistic average paragraph height
477 d->scrollbarParameters_.height = (parsize + 1) * d->wh_;
478 d->scrollbarParameters_.position = d->anchor_ref_ * d->wh_ + int(d->offset_ref_ * d->wh_ / float(h));
479 d->scrollbarParameters_.lineScrollHeight = int(d->wh_ * defaultRowHeight() / float(h));
483 ScrollbarParameters const & BufferView::scrollbarParameters() const
485 return d->scrollbarParameters_;
489 void BufferView::scrollDocView(int value)
491 LYXERR(Debug::GUI, "[ value = " << value << "]");
493 Text & t = buffer_.text();
494 TextMetrics & tm = d->text_metrics_[&t];
496 float const bar = value / float(d->wh_ * t.paragraphs().size());
498 d->anchor_ref_ = int(bar * t.paragraphs().size());
499 if (d->anchor_ref_ > int(t.paragraphs().size()) - 1)
500 d->anchor_ref_ = int(t.paragraphs().size()) - 1;
502 tm.redoParagraph(d->anchor_ref_);
503 int const h = tm.parMetrics(d->anchor_ref_).height();
504 d->offset_ref_ = int((bar * t.paragraphs().size() - d->anchor_ref_) * h);
510 void BufferView::setCursorFromScrollbar()
512 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
514 int const height = 2 * defaultRowHeight();
515 int const first = height;
516 int const last = height_ - height;
517 Cursor & cur = d->cursor_;
519 switch (cursorStatus(cur)) {
521 // We reset the cursor because cursorStatus() does not
522 // work when the cursor is within mathed.
523 cur.reset(buffer_.inset());
524 tm.setCursorFromCoordinates(cur, 0, first);
525 cur.clearSelection();
528 // We reset the cursor because cursorStatus() does not
529 // work when the cursor is within mathed.
530 cur.reset(buffer_.inset());
531 tm.setCursorFromCoordinates(cur, 0, last);
532 cur.clearSelection();
535 int const y = getPos(cur, cur.boundary()).y_;
536 int const newy = min(last, max(y, first));
538 cur.reset(buffer_.inset());
539 tm.setCursorFromCoordinates(cur, 0, newy);
545 Change const BufferView::getCurrentChange() const
547 if (!d->cursor_.selection())
548 return Change(Change::UNCHANGED);
550 DocIterator dit = d->cursor_.selectionBegin();
551 return dit.paragraph().lookupChange(dit.pos());
555 // this could be used elsewhere as well?
556 // FIXME: This does not work within mathed!
557 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
559 Point const p = getPos(dit, dit.boundary());
562 if (p.y_ > workHeight())
568 void BufferView::saveBookmark(unsigned int idx)
570 // tenatively save bookmark, id and pos will be used to
571 // acturately locate a bookmark in a 'live' lyx session.
572 // pit and pos will be updated with bottom level pit/pos
574 LyX::ref().session().bookmarks().save(
576 d->cursor_.bottom().pit(),
577 d->cursor_.bottom().pos(),
578 d->cursor_.paragraph().id(),
583 // emit message signal.
584 message(_("Save bookmark"));
588 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
589 int top_id, pos_type top_pos)
591 bool success = false;
594 d->cursor_.clearSelection();
596 // if a valid par_id is given, try it first
597 // This is the case for a 'live' bookmark when unique paragraph ID
598 // is used to track bookmarks.
600 ParIterator par = buffer_.getParFromID(top_id);
601 if (par != buffer_.par_iterator_end()) {
602 doc_it = makeDocIterator(par, min(par->size(), top_pos));
603 // Some slices of the iterator may not be
604 // reachable (e.g. closed collapsable inset)
605 // so the dociterator may need to be
606 // shortened. Otherwise, setCursor may crash
607 // lyx when the cursor can not be set to these
609 size_t const n = doc_it.depth();
610 for (size_t i = 0; i < n; ++i)
611 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
619 // if top_id == 0, or searching through top_id failed
620 // This is the case for a 'restored' bookmark when only bottom
621 // (document level) pit was saved. Because of this, bookmark
622 // restoration is inaccurate. If a bookmark was within an inset,
623 // it will be restored to the left of the outmost inset that contains
625 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
626 doc_it = doc_iterator_begin(buffer_.inset());
627 doc_it.pit() = bottom_pit;
628 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
633 // Note: only bottom (document) level pit is set.
635 // set the current font.
636 d->cursor_.setCurrentFont();
637 // To center the screen on this new position we need the
638 // paragraph position which is computed at draw() time.
639 // So we need a redraw!
642 // We need another redraw because of the screen recentering.
650 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
652 if (lyxrc.rtl_support) {
653 if (d->cursor_.real_current_font.isRightToLeft()) {
654 if (d->intl_.keymap == Intl::PRIMARY)
655 d->intl_.keyMapSec();
657 if (d->intl_.keymap == Intl::SECONDARY)
658 d->intl_.keyMapPrim();
662 d->intl_.getTransManager().translateAndInsert(c, t, cur);
666 int BufferView::workWidth() const
672 void BufferView::updateOffsetRef()
674 // No need to update d->offset_ref_ in this case.
675 if (!d->need_centering_)
678 // We are not properly started yet, delay until resizing is
683 CursorSlice & bot = d->cursor_.bottom();
684 TextMetrics & tm = d->text_metrics_[bot.text()];
685 ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
686 int y = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
687 d->offset_ref_ = y + pm.ascent() - height_ / 2;
689 d->need_centering_ = false;
693 void BufferView::center()
695 d->anchor_ref_ = d->cursor_.bottom().pit();
696 d->need_centering_ = true;
700 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
704 Cursor & cur = d->cursor_;
706 switch (cmd.action) {
709 flag.enabled(buffer_.undo().hasUndoStack());
712 flag.enabled(buffer_.undo().hasRedoStack());
714 case LFUN_FILE_INSERT:
715 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
716 case LFUN_FILE_INSERT_PLAINTEXT:
717 case LFUN_BOOKMARK_SAVE:
718 // FIXME: Actually, these LFUNS should be moved to Text
719 flag.enabled(cur.inTexted());
721 case LFUN_FONT_STATE:
722 case LFUN_LABEL_INSERT:
723 case LFUN_INFO_INSERT:
724 case LFUN_PARAGRAPH_GOTO:
726 case LFUN_REFERENCE_NEXT:
728 case LFUN_WORD_REPLACE:
731 case LFUN_MARK_TOGGLE:
732 case LFUN_SCREEN_RECENTER:
733 case LFUN_BIBTEX_DATABASE_ADD:
734 case LFUN_BIBTEX_DATABASE_DEL:
735 case LFUN_WORDS_COUNT:
736 case LFUN_NEXT_INSET_TOGGLE:
740 case LFUN_LABEL_GOTO: {
741 flag.enabled(!cmd.argument().empty()
742 || getInsetByCode<InsetRef>(cur, REF_CODE));
746 case LFUN_CHANGES_TRACK:
748 flag.setOnOff(buffer_.params().trackChanges);
751 case LFUN_CHANGES_OUTPUT:
753 flag.setOnOff(buffer_.params().outputChanges);
756 case LFUN_CHANGES_MERGE:
757 case LFUN_CHANGE_NEXT:
758 case LFUN_ALL_CHANGES_ACCEPT:
759 case LFUN_ALL_CHANGES_REJECT:
760 // TODO: context-sensitive enabling of LFUNs
761 // In principle, these command should only be enabled if there
762 // is a change in the document. However, without proper
763 // optimizations, this will inevitably result in poor performance.
767 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
768 flag.setOnOff(buffer_.params().compressed);
772 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
773 flag.setOnOff(buffer_.params().embedded);
778 case LFUN_SCREEN_DOWN:
782 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
783 // everywhere else before this can enabled:
784 case LFUN_SCREEN_UP_SELECT:
785 case LFUN_SCREEN_DOWN_SELECT:
789 case LFUN_LAYOUT_TABULAR:
790 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
794 case LFUN_LAYOUT_PARAGRAPH:
795 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
798 case LFUN_INSET_SETTINGS: {
799 InsetCode code = cur.inset().lyxCode();
803 enable = cmd.argument() == "tabular";
806 enable = cmd.argument() == "ert";
809 enable = cmd.argument() == "float";
812 enable = cmd.argument() == "wrap";
815 enable = cmd.argument() == "note";
818 enable = cmd.argument() == "branch";
821 enable = cmd.argument() == "box";
824 enable = cmd.argument() == "listings";
829 flag.enabled(enable);
833 case LFUN_DIALOG_SHOW_NEW_INSET:
834 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
835 cur.inset().lyxCode() != LISTINGS_CODE);
836 if (cur.inset().lyxCode() == CAPTION_CODE) {
838 if (cur.inset().getStatus(cur, cmd, flag))
851 Update::flags BufferView::dispatch(FuncRequest const & cmd)
853 //lyxerr << [ cmd = " << cmd << "]" << endl;
855 // Make sure that the cached BufferView is correct.
856 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
857 << " arg[" << to_utf8(cmd.argument()) << ']'
858 << " x[" << cmd.x << ']'
859 << " y[" << cmd.y << ']'
860 << " button[" << cmd.button() << ']');
862 Cursor & cur = d->cursor_;
863 // Default Update flags.
864 Update::flags updateFlags = Update::Force | Update::FitCursor;
866 switch (cmd.action) {
869 cur.message(_("Undo"));
870 cur.clearSelection();
871 if (!cur.textUndo()) {
872 cur.message(_("No further undo information"));
873 updateFlags = Update::None;
878 cur.message(_("Redo"));
879 cur.clearSelection();
880 if (!cur.textRedo()) {
881 cur.message(_("No further redo information"));
882 updateFlags = Update::None;
886 case LFUN_FONT_STATE:
887 cur.message(cur.currentState());
890 case LFUN_BOOKMARK_SAVE:
891 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
894 case LFUN_LABEL_GOTO: {
895 docstring label = cmd.argument();
898 getInsetByCode<InsetRef>(d->cursor_,
901 label = inset->getParam("reference");
902 // persistent=false: use temp_bookmark
912 case LFUN_PARAGRAPH_GOTO: {
913 int const id = convert<int>(to_utf8(cmd.argument()));
915 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
916 b = theBufferList().next(b)) {
918 ParIterator par = b->getParFromID(id);
919 if (par == b->par_iterator_end()) {
920 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
922 LYXERR(Debug::INFO, "Paragraph " << par->id()
923 << " found in buffer `"
924 << b->absFileName() << "'.");
928 setCursor(makeDocIterator(par, 0));
930 // Switch to other buffer view and resend cmd
931 theLyXFunc().dispatch(FuncRequest(
932 LFUN_BUFFER_SWITCH, b->absFileName()));
933 theLyXFunc().dispatch(cmd);
934 updateFlags = Update::None;
944 gotoInset(this, NOTE_CODE, false);
947 case LFUN_REFERENCE_NEXT: {
948 vector<InsetCode> tmp;
949 tmp.push_back(LABEL_CODE);
950 tmp.push_back(REF_CODE);
951 gotoInset(this, tmp, true);
955 case LFUN_CHANGES_TRACK:
956 buffer_.params().trackChanges = !buffer_.params().trackChanges;
959 case LFUN_CHANGES_OUTPUT:
960 buffer_.params().outputChanges = !buffer_.params().outputChanges;
961 if (buffer_.params().outputChanges) {
962 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
963 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
964 LaTeXFeatures::isAvailable("xcolor");
966 if (!dvipost && !xcolorsoul) {
967 Alert::warning(_("Changes not shown in LaTeX output"),
968 _("Changes will not be highlighted in LaTeX output, "
969 "because neither dvipost nor xcolor/soul are installed.\n"
970 "Please install these packages or redefine "
971 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
972 } else if (!xcolorsoul) {
973 Alert::warning(_("Changes not shown in LaTeX output"),
974 _("Changes will not be highlighted in LaTeX output "
975 "when using pdflatex, because xcolor and soul are not installed.\n"
976 "Please install both packages or redefine "
977 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
982 case LFUN_CHANGE_NEXT:
983 findNextChange(this);
986 case LFUN_CHANGES_MERGE:
987 if (findNextChange(this))
988 showDialog("changes");
991 case LFUN_ALL_CHANGES_ACCEPT:
992 // select complete document
993 d->cursor_.reset(buffer_.inset());
994 d->cursor_.selHandle(true);
995 buffer_.text().cursorBottom(d->cursor_);
996 // accept everything in a single step to support atomic undo
997 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1000 case LFUN_ALL_CHANGES_REJECT:
1001 // select complete document
1002 d->cursor_.reset(buffer_.inset());
1003 d->cursor_.selHandle(true);
1004 buffer_.text().cursorBottom(d->cursor_);
1005 // reject everything in a single step to support atomic undo
1006 // Note: reject does not work recursively; the user may have to repeat the operation
1007 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1010 case LFUN_WORD_FIND:
1014 case LFUN_WORD_REPLACE: {
1015 bool has_deleted = false;
1016 if (cur.selection()) {
1017 DocIterator beg = cur.selectionBegin();
1018 DocIterator end = cur.selectionEnd();
1019 if (beg.pit() == end.pit()) {
1020 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1021 if (cur.paragraph().isDeleted(p))
1026 replace(this, cmd, has_deleted);
1031 cur.clearSelection();
1033 cur.message(from_utf8(N_("Mark off")));
1037 cur.clearSelection();
1040 cur.message(from_utf8(N_("Mark on")));
1043 case LFUN_MARK_TOGGLE:
1044 cur.clearSelection();
1047 cur.message(from_utf8(N_("Mark removed")));
1050 cur.message(from_utf8(N_("Mark set")));
1055 case LFUN_SCREEN_RECENTER:
1059 case LFUN_BIBTEX_DATABASE_ADD: {
1060 Cursor tmpcur = d->cursor_;
1061 findInset(tmpcur, BIBTEX_CODE, false);
1062 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1065 if (inset->addDatabase(to_utf8(cmd.argument())))
1066 buffer_.updateBibfilesCache();
1071 case LFUN_BIBTEX_DATABASE_DEL: {
1072 Cursor tmpcur = d->cursor_;
1073 findInset(tmpcur, BIBTEX_CODE, false);
1074 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1077 if (inset->delDatabase(to_utf8(cmd.argument())))
1078 buffer_.updateBibfilesCache();
1083 case LFUN_WORDS_COUNT: {
1084 DocIterator from, to;
1085 if (cur.selection()) {
1086 from = cur.selectionBegin();
1087 to = cur.selectionEnd();
1089 from = doc_iterator_begin(buffer_.inset());
1090 to = doc_iterator_end(buffer_.inset());
1092 int const count = countWords(from, to);
1095 if (cur.selection())
1096 message = bformat(_("%1$d words in selection."),
1099 message = bformat(_("%1$d words in document."),
1103 if (cur.selection())
1104 message = _("One word in selection.");
1106 message = _("One word in document.");
1109 Alert::information(_("Count words"), message);
1113 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1114 // turn compression on/off
1115 buffer_.params().compressed = !buffer_.params().compressed;
1118 case LFUN_BUFFER_TOGGLE_EMBEDDING:
1119 // turn embedding on/off
1120 buffer_.embeddedFiles().enable(!buffer_.params().embedded);
1123 case LFUN_NEXT_INSET_TOGGLE: {
1124 // this is the real function we want to invoke
1125 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1126 // if there is an inset at cursor, see whether it
1128 Inset * inset = cur.nextInset();
1130 if (inset->isActive()) {
1131 Cursor tmpcur = cur;
1132 tmpcur.pushBackward(*inset);
1133 inset->dispatch(tmpcur, tmpcmd);
1134 if (tmpcur.result().dispatched()) {
1137 } else if (inset->editable() == Inset::IS_EDITABLE) {
1138 inset->edit(cur, true);
1141 // if it did not work, try the underlying inset.
1142 if (!cur.result().dispatched())
1143 cur.dispatch(tmpcmd);
1145 if (cur.result().dispatched())
1146 cur.clearSelection();
1151 case LFUN_SCREEN_UP:
1152 case LFUN_SCREEN_DOWN: {
1153 Point p = getPos(cur, cur.boundary());
1154 if (p.y_ < 0 || p.y_ > height_) {
1155 // The cursor is off-screen so recenter before proceeding.
1158 //FIXME: updateMetrics() does not update paragraph position
1159 // This is done at draw() time. So we need a redraw!
1160 // But no screen update is needed.
1161 d->update_strategy_ = NoScreenUpdate;
1163 p = getPos(cur, cur.boundary());
1165 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1166 cur.reset(buffer_.inset());
1167 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1168 //FIXME: what to do with cur.x_target()?
1170 // The metrics are already up to date. see scroll()
1171 updateFlags = Update::None;
1175 case LFUN_SCREEN_UP_SELECT:
1176 case LFUN_SCREEN_DOWN_SELECT: {
1177 cur.selHandle(true);
1178 size_t initial_depth = cur.depth();
1179 Point const p = getPos(cur, cur.boundary());
1180 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1181 // FIXME: We need to verify if the cursor stayed within an inset...
1182 //cur.reset(buffer_.inset());
1183 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1185 while (cur.depth() > initial_depth) {
1188 // FIXME: we need to do a redraw again because of the selection
1189 // But no screen update is needed.
1190 d->update_strategy_ = NoScreenUpdate;
1192 updateFlags = Update::Force | Update::FitCursor;
1197 updateFlags = Update::None;
1204 docstring const BufferView::requestSelection()
1206 Cursor & cur = d->cursor_;
1208 if (!cur.selection()) {
1209 d->xsel_cache_.set = false;
1213 if (!d->xsel_cache_.set ||
1214 cur.top() != d->xsel_cache_.cursor ||
1215 cur.anchor_.top() != d->xsel_cache_.anchor)
1217 d->xsel_cache_.cursor = cur.top();
1218 d->xsel_cache_.anchor = cur.anchor_.top();
1219 d->xsel_cache_.set = cur.selection();
1220 return cur.selectionAsString(false);
1226 void BufferView::clearSelection()
1228 d->cursor_.clearSelection();
1229 // Clear the selection buffer. Otherwise a subsequent
1230 // middle-mouse-button paste would use the selection buffer,
1231 // not the more current external selection.
1232 cap::clearSelection();
1233 d->xsel_cache_.set = false;
1234 // The buffer did not really change, but this causes the
1235 // redraw we need because we cleared the selection above.
1240 void BufferView::resize(int width, int height)
1242 // Update from work area
1250 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1252 TextMetrics & tm = d->text_metrics_[&text];
1253 Inset * inset = tm.checkInsetHit(x, y);
1257 if (!inset->descendable())
1258 // No need to go further down if the inset is not
1262 size_t cell_number = inset->nargs();
1263 // Check all the inner cell.
1264 for (size_t i = 0; i != cell_number; ++i) {
1265 Text const * inner_text = inset->getText(i);
1268 Inset const * inset_deeper =
1269 getCoveringInset(*inner_text, x, y);
1271 return inset_deeper;
1279 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1281 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1283 // This is only called for mouse related events including
1284 // LFUN_FILE_OPEN generated by drag-and-drop.
1285 FuncRequest cmd = cmd0;
1288 cur.push(buffer_.inset());
1289 cur.selection() = d->cursor_.selection();
1291 // Either the inset under the cursor or the
1292 // surrounding Text will handle this event.
1294 // make sure we stay within the screen...
1295 cmd.y = min(max(cmd.y, -1), height_);
1297 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1299 // Get inset under mouse, if there is one.
1300 Inset const * covering_inset =
1301 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1302 if (covering_inset == d->last_inset_)
1303 // Same inset, no need to do anything...
1306 bool need_redraw = false;
1307 // const_cast because of setMouseHover().
1308 Inset * inset = const_cast<Inset *>(covering_inset);
1310 // Remove the hint on the last hovered inset (if any).
1311 need_redraw |= d->last_inset_->setMouseHover(false);
1313 // Highlighted the newly hovered inset (if any).
1314 need_redraw |= inset->setMouseHover(true);
1315 d->last_inset_ = inset;
1319 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1320 << cmd.x << ", " << cmd.y << ")");
1322 d->update_strategy_ = DecorationUpdate;
1324 // This event (moving without mouse click) is not passed further.
1325 // This should be changed if it is further utilized.
1330 // Build temporary cursor.
1331 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1333 // Put anchor at the same position.
1336 // Try to dispatch to an non-editable inset near this position
1337 // via the temp cursor. If the inset wishes to change the real
1338 // cursor it has to do so explicitly by using
1339 // cur.bv().cursor() = cur; (or similar)
1341 inset->dispatch(cur, cmd);
1343 // Now dispatch to the temporary cursor. If the real cursor should
1344 // be modified, the inset's dispatch has to do so explicitly.
1345 if (!cur.result().dispatched())
1348 //Do we have a selection?
1349 theSelection().haveSelection(cursor().selection());
1351 // If the command has been dispatched,
1352 if (cur.result().dispatched()
1353 // an update is asked,
1354 && cur.result().update())
1355 processUpdateFlags(cur.result().update());
1359 void BufferView::scroll(int y)
1368 void BufferView::scrollDown(int offset)
1370 Text * text = &buffer_.text();
1371 TextMetrics & tm = d->text_metrics_[text];
1372 int ymax = height_ + offset;
1374 std::pair<pit_type, ParagraphMetrics const *> last = tm.last();
1375 int bottom_pos = last.second->position() + last.second->descent();
1376 if (last.first + 1 == int(text->paragraphs().size())) {
1377 if (bottom_pos <= height_)
1379 offset = min(offset, bottom_pos - height_);
1382 if (bottom_pos > ymax)
1384 tm.newParMetricsDown();
1386 d->offset_ref_ += offset;
1392 void BufferView::scrollUp(int offset)
1394 Text * text = &buffer_.text();
1395 TextMetrics & tm = d->text_metrics_[text];
1396 int ymin = - offset;
1398 std::pair<pit_type, ParagraphMetrics const *> first = tm.first();
1399 int top_pos = first.second->position() - first.second->ascent();
1400 if (first.first == 0) {
1403 offset = min(offset, - top_pos);
1408 tm.newParMetricsUp();
1410 d->offset_ref_ -= offset;
1416 void BufferView::setCursorFromRow(int row)
1421 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1423 d->cursor_.reset(buffer_.inset());
1425 buffer_.text().setCursor(d->cursor_, 0, 0);
1427 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1431 void BufferView::gotoLabel(docstring const & label)
1433 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1434 vector<docstring> labels;
1435 it->getLabelList(buffer_, labels);
1436 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1438 processUpdateFlags(Update::FitCursor);
1445 TextMetrics const & BufferView::textMetrics(Text const * t) const
1447 return const_cast<BufferView *>(this)->textMetrics(t);
1451 TextMetrics & BufferView::textMetrics(Text const * t)
1453 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1454 if (tmc_it == d->text_metrics_.end()) {
1455 tmc_it = d->text_metrics_.insert(
1456 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1458 return tmc_it->second;
1462 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1465 return textMetrics(t).parMetrics(pit);
1469 int BufferView::workHeight() const
1475 void BufferView::setCursor(DocIterator const & dit)
1477 size_t const n = dit.depth();
1478 for (size_t i = 0; i < n; ++i)
1479 dit[i].inset().edit(d->cursor_, true);
1481 d->cursor_.setCursor(dit);
1482 d->cursor_.selection() = false;
1486 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1488 // Would be wrong to delete anything if we have a selection.
1489 if (cur.selection())
1492 bool need_anchor_change = false;
1493 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1494 need_anchor_change);
1496 if (need_anchor_change)
1502 updateLabels(buffer_);
1510 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1512 BOOST_ASSERT(&cur.bv() == this);
1515 // this event will clear selection so we save selection for
1516 // persistent selection
1517 cap::saveSelection(cursor());
1519 // Has the cursor just left the inset?
1520 bool badcursor = false;
1521 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1523 badcursor = notifyCursorLeaves(d->cursor_, cur);
1525 // FIXME: shift-mouse selection doesn't work well across insets.
1526 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1528 // do the dEPM magic if needed
1529 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1530 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1531 // the leftinset bool would not be necessary (badcursor instead).
1532 bool update = leftinset;
1533 if (!do_selection && !badcursor && d->cursor_.inTexted())
1534 update |= checkDepm(cur, d->cursor_);
1536 // if the cursor was in an empty script inset and the new
1537 // position is in the nucleus of the inset, notifyCursorLeaves
1538 // will kill the script inset itself. So we check all the
1539 // elements of the cursor to make sure that they are correct.
1540 // For an example, see bug 2933:
1541 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1542 // The code below could maybe be moved to a DocIterator method.
1543 //lyxerr << "cur before " << cur <<std::endl;
1544 DocIterator dit(cur.inset());
1545 dit.push_back(cur.bottom());
1547 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1548 dit.push_back(cur[i]);
1551 //lyxerr << "5 cur after" << dit <<std::endl;
1553 d->cursor_.setCursor(dit);
1554 d->cursor_.boundary(cur.boundary());
1556 d->cursor_.setSelection();
1558 d->cursor_.clearSelection();
1560 d->cursor_.finishUndo();
1561 d->cursor_.setCurrentFont();
1566 void BufferView::putSelectionAt(DocIterator const & cur,
1567 int length, bool backwards)
1569 d->cursor_.clearSelection();
1575 d->cursor_.pos() += length;
1576 d->cursor_.setSelection(d->cursor_, -length);
1578 d->cursor_.setSelection(d->cursor_, length);
1583 Cursor & BufferView::cursor()
1589 Cursor const & BufferView::cursor() const
1595 pit_type BufferView::anchor_ref() const
1597 return d->anchor_ref_;
1601 bool BufferView::singleParUpdate()
1603 Text & buftext = buffer_.text();
1604 pit_type const bottom_pit = d->cursor_.bottom().pit();
1605 TextMetrics & tm = textMetrics(&buftext);
1606 int old_height = tm.parMetrics(bottom_pit).height();
1608 // In Single Paragraph mode, rebreak only
1609 // the (main text, not inset!) paragraph containing the cursor.
1610 // (if this paragraph contains insets etc., rebreaking will
1611 // recursively descend)
1612 tm.redoParagraph(bottom_pit);
1613 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1614 if (pm.height() != old_height)
1615 // Paragraph height has changed so we cannot proceed to
1616 // the singlePar optimisation.
1619 d->update_strategy_ = SingleParUpdate;
1621 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1622 << " y2: " << pm.position() + pm.descent()
1623 << " pit: " << bottom_pit
1624 << " singlepar: 1");
1629 void BufferView::updateMetrics()
1631 Text & buftext = buffer_.text();
1632 pit_type const npit = int(buftext.paragraphs().size());
1634 if (d->anchor_ref_ > int(npit - 1)) {
1635 d->anchor_ref_ = int(npit - 1);
1639 // Clear out the position cache in case of full screen redraw,
1640 d->coord_cache_.clear();
1642 // Clear out paragraph metrics to avoid having invalid metrics
1643 // in the cache from paragraphs not relayouted below
1644 // The complete text metrics will be redone.
1645 d->text_metrics_.clear();
1647 TextMetrics & tm = textMetrics(&buftext);
1649 pit_type const pit = d->anchor_ref_;
1653 // Rebreak anchor paragraph.
1654 tm.redoParagraph(pit);
1656 // Take care of anchor offset if case a recentering is needed.
1659 int y0 = tm.parMetrics(pit).ascent() - d->offset_ref_;
1661 // Redo paragraphs above anchor if necessary.
1663 while (y1 > 0 && pit1 > 0) {
1664 y1 -= tm.parMetrics(pit1).ascent();
1666 tm.redoParagraph(pit1);
1667 y1 -= tm.parMetrics(pit1).descent();
1670 // Take care of ascent of first line
1671 y1 -= tm.parMetrics(pit1).ascent();
1673 // Normalize anchor for next time
1674 d->anchor_ref_ = pit1;
1675 d->offset_ref_ = -y1;
1677 // Grey at the beginning is ugly
1678 if (pit1 == 0 && y1 > 0) {
1684 // Redo paragraphs below the anchor if necessary.
1686 while (y2 < height_ && pit2 < int(npit) - 1) {
1687 y2 += tm.parMetrics(pit2).descent();
1689 tm.redoParagraph(pit2);
1690 y2 += tm.parMetrics(pit2).ascent();
1693 // Take care of descent of last line
1694 y2 += tm.parMetrics(pit2).descent();
1696 LYXERR(Debug::PAINTING, "\n y1: " << y1
1698 << " pit1: " << pit1
1699 << " pit2: " << pit2
1700 << " npit: " << npit
1701 << " singlepar: 0");
1703 d->update_strategy_ = FullScreenUpdate;
1705 if (lyxerr.debugging(Debug::WORKAREA)) {
1706 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1707 d->coord_cache_.dump();
1712 void BufferView::insertLyXFile(FileName const & fname)
1714 BOOST_ASSERT(d->cursor_.inTexted());
1716 // Get absolute path of file and add ".lyx"
1717 // to the filename if necessary
1718 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1720 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1721 // emit message signal.
1722 message(bformat(_("Inserting document %1$s..."), disp_fn));
1725 Buffer buf("", false);
1726 if (buf.loadLyXFile(filename)) {
1727 ErrorList & el = buffer_.errorList("Parse");
1728 // Copy the inserted document error list into the current buffer one.
1729 el = buf.errorList("Parse");
1730 buffer_.undo().recordUndo(d->cursor_);
1731 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1732 buf.params().getTextClassPtr(), el);
1733 res = _("Document %1$s inserted.");
1735 res = _("Could not insert document %1$s");
1740 // emit message signal.
1741 message(bformat(res, disp_fn));
1742 buffer_.errors("Parse");
1746 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1752 // Addup contribution of nested insets, from inside to outside,
1753 // keeping the outer paragraph for a special handling below
1754 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1755 CursorSlice const & sl = dit[i];
1759 // get relative position inside sl.inset()
1760 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1762 // Make relative position inside of the edited inset relative to sl.inset()
1766 // In case of an RTL inset, the edited inset will be positioned to the left
1769 bool boundary_i = boundary && i + 1 == dit.depth();
1770 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1775 // remember width for the case that sl.inset() is positioned in an RTL inset
1776 if (i && dit[i - 1].text()) {
1777 // If this Inset is inside a Text Inset, retrieve the Dimension
1778 // from the containing text instead of using Inset::dimension() which
1779 // might not be implemented.
1780 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1781 // elimination of Inset::dim_ cache. This coordOffset() method needs
1782 // to be rewritten in light of the new design.
1783 Dimension const & dim = parMetrics(dit[i - 1].text(),
1784 dit[i - 1].pit()).insetDimension(&sl.inset());
1787 Dimension const dim = sl.inset().dimension(*this);
1791 //lyxerr << "Cursor::getPos, i: "
1792 // << i << " x: " << xx << " y: " << y << endl;
1795 // Add contribution of initial rows of outermost paragraph
1796 CursorSlice const & sl = dit[0];
1797 TextMetrics const & tm = textMetrics(sl.text());
1798 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1799 BOOST_ASSERT(!pm.rows().empty());
1800 y -= pm.rows()[0].ascent();
1802 // FIXME: document this mess
1804 if (sl.pos() > 0 && dit.depth() == 1) {
1806 if (pos && boundary)
1808 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << std::endl;
1809 rend = pm.pos2row(pos);
1811 rend = pm.pos2row(sl.pos());
1813 size_t rend = pm.pos2row(sl.pos());
1815 for (size_t rit = 0; rit != rend; ++rit)
1816 y += pm.rows()[rit].height();
1817 y += pm.rows()[rend].ascent();
1819 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1821 // Make relative position from the nested inset now bufferview absolute.
1822 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1825 // In the RTL case place the nested inset at the left of the cursor in
1826 // the outer paragraph
1827 bool boundary_1 = boundary && 1 == dit.depth();
1828 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1836 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1838 CursorSlice const & bot = dit.bottom();
1839 TextMetrics const & tm = textMetrics(bot.text());
1840 if (!tm.has(bot.pit()))
1841 return Point(-1, -1);
1843 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1844 p.y_ += tm.parMetrics(bot.pit()).position();
1849 void BufferView::draw(frontend::Painter & pain)
1851 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1852 Text & text = buffer_.text();
1853 TextMetrics const & tm = d->text_metrics_[&text];
1854 int const y = - d->offset_ref_ + tm.parMetrics(d->anchor_ref_).ascent();
1855 PainterInfo pi(this, pain);
1857 switch (d->update_strategy_) {
1859 case NoScreenUpdate:
1860 // If no screen painting is actually needed, only some the different
1861 // coordinates of insets and paragraphs needs to be updated.
1862 pi.full_repaint = true;
1863 pi.pain.setDrawingEnabled(false);
1867 case SingleParUpdate:
1868 pi.full_repaint = false;
1869 // In general, only the current row of the outermost paragraph
1870 // will be redrawn. Particular cases where selection spans
1871 // multiple paragraph are correctly detected in TextMetrics.
1875 case DecorationUpdate:
1876 // FIXME: We should also distinguish DecorationUpdate to avoid text
1877 // drawing if possible. This is not possible to do easily right now
1878 // because of the single backing pixmap.
1880 case FullScreenUpdate:
1881 // The whole screen, including insets, will be refreshed.
1882 pi.full_repaint = true;
1884 // Clear background.
1885 pain.fillRectangle(0, 0, width_, height_,
1886 buffer_.inset().backgroundColor());
1889 // and possibly grey out below
1890 std::pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1891 int const y2 = lastpm.second->position() + lastpm.second->descent();
1893 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
1897 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
1901 void BufferView::message(docstring const & msg)
1904 d->gui_->message(msg);
1908 void BufferView::showDialog(std::string const & name)
1911 d->gui_->showDialog(name, string());
1915 void BufferView::showDialog(std::string const & name,
1916 std::string const & data, Inset * inset)
1919 d->gui_->showDialog(name, data, inset);
1923 void BufferView::updateDialog(std::string const & name, std::string const & data)
1926 d->gui_->updateDialog(name, data);
1930 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
1936 // FIXME: Move this out of BufferView again
1937 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
1939 if (!fname.isReadableFile()) {
1940 docstring const error = from_ascii(strerror(errno));
1941 docstring const file = makeDisplayPath(fname.absFilename(), 50);
1942 docstring const text =
1943 bformat(_("Could not read the specified document\n"
1944 "%1$s\ndue to the error: %2$s"), file, error);
1945 Alert::error(_("Could not read file"), text);
1949 if (!fname.isReadableFile()) {
1950 docstring const file = makeDisplayPath(fname.absFilename(), 50);
1951 docstring const text =
1952 bformat(_("%1$s\n is not readable."), file);
1953 Alert::error(_("Could not open file"), text);
1957 // FIXME UNICODE: We don't know the encoding of the file
1958 docstring file_content = fname.fileContents("UTF-8");
1959 if (file_content.empty()) {
1960 Alert::error(_("Reading not UTF-8 encoded file"),
1961 _("The file is not UTF-8 encoded.\n"
1962 "It will be read as local 8Bit-encoded.\n"
1963 "If this does not give the correct result\n"
1964 "then please change the encoding of the file\n"
1965 "to UTF-8 with a program other than LyX.\n"));
1966 file_content = fname.fileContents("local8bit");
1969 return normalize_c(file_content);
1973 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
1975 docstring const tmpstr = contentsOfPlaintextFile(f);
1980 Cursor & cur = cursor();
1981 cap::replaceSelection(cur);
1982 buffer_.undo().recordUndo(cur);
1984 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
1986 cur.innerText()->insertStringAsLines(cur, tmpstr);