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/FileDialog.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/FileFilterList.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"
87 using std::istringstream;
88 using std::istream_iterator;
92 using std::mem_fun_ref;
98 using support::addPath;
99 using support::bformat;
100 using support::FileFilterList;
101 using support::FileName;
102 using support::fileSearch;
103 using support::makeDisplayPath;
104 using support::makeAbsPath;
105 using support::package;
107 namespace Alert = frontend::Alert;
111 /// Return an inset of this class if it exists at the current cursor position
113 T * getInsetByCode(Cursor const & cur, InsetCode code)
115 DocIterator it = cur;
116 Inset * inset = it.nextInset();
117 if (inset && inset->lyxCode() == code)
118 return static_cast<T*>(inset);
123 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
126 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
127 docstring const & contents)
129 DocIterator tmpdit = dit;
132 Inset const * inset = tmpdit.nextInset();
134 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
135 && (contents.empty() ||
136 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
140 tmpdit.forwardInset();
147 /// Looks for next inset with one of the given codes.
148 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
152 DocIterator tmpdit = dit;
153 tmpdit.forwardInset();
158 Inset const * inset = tmpdit.nextInset();
160 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
161 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
165 if (!findNextInset(tmpdit, codes, contents)) {
166 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
167 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
168 if (!findNextInset(tmpdit, codes, contents))
179 /// Looks for next inset with the given code
180 void findInset(DocIterator & dit, InsetCode code, bool same_content)
182 findInset(dit, vector<InsetCode>(1, code), same_content);
186 /// Moves cursor to the next inset with one of the given codes.
187 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
190 Cursor tmpcur = bv->cursor();
191 if (!findInset(tmpcur, codes, same_content)) {
192 bv->cursor().message(_("No more insets"));
196 tmpcur.clearSelection();
197 bv->setCursor(tmpcur);
201 /// Moves cursor to the next inset with given code.
202 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
204 gotoInset(bv, vector<InsetCode>(1, code), same_content);
208 /// A map from a Text to the associated text metrics
209 typedef std::map<Text const *, TextMetrics> TextMetricsCache;
211 enum ScreenUpdateStrategy {
221 /////////////////////////////////////////////////////////////////////
225 /////////////////////////////////////////////////////////////////////
227 struct BufferView::Private
229 Private(BufferView & bv): wh_(0), cursor_(bv),
230 anchor_ref_(0), offset_ref_(0), need_centering_(false),
231 last_inset_(0), gui_(0)
235 ScrollbarParameters scrollbarParameters_;
237 ScreenUpdateStrategy update_strategy_;
239 CoordCache coord_cache_;
241 /// Estimated average par height for scrollbar.
243 /// this is used to handle XSelection events in the right manner.
252 pit_type anchor_ref_;
256 bool need_centering_;
258 /// keyboard mapping object.
261 /// last visited inset.
262 /** kept to send setMouseHover(false).
263 * Not owned, so don't delete.
267 mutable TextMetricsCache text_metrics_;
270 /** Not owned, so don't delete.
272 frontend::GuiBufferViewDelegate * gui_;
276 BufferView::BufferView(Buffer & buf)
277 : width_(0), height_(0), buffer_(buf), d(new Private(*this))
279 d->xsel_cache_.set = false;
280 d->intl_.initKeyMapper(lyxrc.use_kbmap);
282 d->cursor_.push(buffer_.inset());
283 d->cursor_.resetAnchor();
284 d->cursor_.setCurrentFont();
286 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
287 graphics::Previews::get().generateBufferPreviews(buffer_);
291 BufferView::~BufferView()
293 // current buffer is going to be switched-off, save cursor pos
294 // Ideally, the whole cursor stack should be saved, but session
295 // currently can only handle bottom (whole document) level pit and pos.
296 // That is to say, if a cursor is in a nested inset, it will be
297 // restore to the left of the top level inset.
298 LastFilePosSection::FilePos fp;
299 fp.pit = d->cursor_.bottom().pit();
300 fp.pos = d->cursor_.bottom().pos();
301 LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
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_)
359 void BufferView::processUpdateFlags(Update::flags flags)
361 // last_inset_ points to the last visited inset. This pointer may become
362 // invalid because of keyboard editing. Since all such operations
363 // causes screen update(), I reset last_inset_ to avoid such a problem.
365 // This is close to a hot-path.
366 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
367 << "[fitcursor = " << (flags & Update::FitCursor)
368 << ", forceupdate = " << (flags & Update::Force)
369 << ", singlepar = " << (flags & Update::SinglePar)
370 << "] buffer: " << &buffer_);
372 // Update macro store
373 if (!(cursor().inMathed() && cursor().inMacroMode()))
374 buffer_.updateMacros();
376 // Now do the first drawing step if needed. This consists on updating
377 // the CoordCache in updateMetrics().
378 // The second drawing step is done in WorkArea::redraw() if needed.
380 // Case when no explicit update is requested.
382 // no need to redraw anything.
383 d->update_strategy_ = NoScreenUpdate;
387 if (flags == Update::Decoration) {
388 d->update_strategy_ = DecorationUpdate;
393 if (flags == Update::FitCursor
394 || flags == (Update::Decoration | Update::FitCursor)) {
395 bool const fit_cursor = fitCursor();
396 // tell the frontend to update the screen if needed.
402 if (flags & Update::Decoration) {
403 d->update_strategy_ = DecorationUpdate;
407 // no screen update is needed.
408 d->update_strategy_ = NoScreenUpdate;
412 bool const full_metrics = flags & Update::Force;
414 if (full_metrics || !singleParUpdate())
415 // We have to update the full screen metrics.
418 if (!(flags & Update::FitCursor)) {
423 //FIXME: updateMetrics() does not update paragraph position
424 // This is done at draw() time. So we need a redraw!
427 // The screen has already been updated thanks to the
428 // 'buffer_.changed()' call three line above. So no need
432 // The screen has been recentered around the cursor position so
439 void BufferView::updateScrollbar()
441 Text & t = buffer_.text();
442 TextMetrics & tm = d->text_metrics_[&t];
444 int const parsize = int(t.paragraphs().size() - 1);
445 if (d->anchor_ref_ > parsize) {
446 d->anchor_ref_ = parsize;
450 LYXERR(Debug::GUI, " Updating scrollbar: height: "
451 << t.paragraphs().size()
452 << " curr par: " << d->cursor_.bottom().pit()
453 << " default height " << defaultRowHeight());
455 // It would be better to fix the scrollbar to understand
456 // values in [0..1] and divide everything by wh
458 // estimated average paragraph height:
460 d->wh_ = height_ / 4;
462 int h = tm.parMetrics(d->anchor_ref_).height();
464 // Normalize anchor/offset (MV):
465 while (d->offset_ref_ > h && d->anchor_ref_ < parsize) {
468 h = tm.parMetrics(d->anchor_ref_).height();
470 // Look at paragraph heights on-screen
473 for (pit_type pit = d->anchor_ref_; pit <= parsize; ++pit) {
476 int const h2 = tm.parMetrics(pit).height();
482 int const hav = sumh / nh;
483 // More realistic average paragraph height
488 d->scrollbarParameters_.height = (parsize + 1) * d->wh_;
489 d->scrollbarParameters_.position = d->anchor_ref_ * d->wh_ + int(d->offset_ref_ * d->wh_ / float(h));
490 d->scrollbarParameters_.lineScrollHeight = int(d->wh_ * defaultRowHeight() / float(h));
494 ScrollbarParameters const & BufferView::scrollbarParameters() const
496 return d->scrollbarParameters_;
500 void BufferView::scrollDocView(int value)
502 LYXERR(Debug::GUI, "[ value = " << value << "]");
504 Text & t = buffer_.text();
505 TextMetrics & tm = d->text_metrics_[&t];
507 float const bar = value / float(d->wh_ * t.paragraphs().size());
509 d->anchor_ref_ = int(bar * t.paragraphs().size());
510 if (d->anchor_ref_ > int(t.paragraphs().size()) - 1)
511 d->anchor_ref_ = int(t.paragraphs().size()) - 1;
513 tm.redoParagraph(d->anchor_ref_);
514 int const h = tm.parMetrics(d->anchor_ref_).height();
515 d->offset_ref_ = int((bar * t.paragraphs().size() - d->anchor_ref_) * h);
521 void BufferView::setCursorFromScrollbar()
523 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
525 int const height = 2 * defaultRowHeight();
526 int const first = height;
527 int const last = height_ - height;
528 Cursor & cur = d->cursor_;
530 switch (cursorStatus(cur)) {
532 // We reset the cursor because cursorStatus() does not
533 // work when the cursor is within mathed.
534 cur.reset(buffer_.inset());
535 tm.setCursorFromCoordinates(cur, 0, first);
536 cur.clearSelection();
539 // We reset the cursor because cursorStatus() does not
540 // work when the cursor is within mathed.
541 cur.reset(buffer_.inset());
542 tm.setCursorFromCoordinates(cur, 0, last);
543 cur.clearSelection();
546 int const y = getPos(cur, cur.boundary()).y_;
547 int const newy = min(last, max(y, first));
549 cur.reset(buffer_.inset());
550 tm.setCursorFromCoordinates(cur, 0, newy);
556 Change const BufferView::getCurrentChange() const
558 if (!d->cursor_.selection())
559 return Change(Change::UNCHANGED);
561 DocIterator dit = d->cursor_.selectionBegin();
562 return dit.paragraph().lookupChange(dit.pos());
566 // this could be used elsewhere as well?
567 // FIXME: This does not work within mathed!
568 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
570 Point const p = getPos(dit, dit.boundary());
573 if (p.y_ > workHeight())
579 void BufferView::saveBookmark(unsigned int idx)
581 // tenatively save bookmark, id and pos will be used to
582 // acturately locate a bookmark in a 'live' lyx session.
583 // pit and pos will be updated with bottom level pit/pos
585 LyX::ref().session().bookmarks().save(
587 d->cursor_.bottom().pit(),
588 d->cursor_.bottom().pos(),
589 d->cursor_.paragraph().id(),
594 // emit message signal.
595 message(_("Save bookmark"));
599 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
600 int top_id, pos_type top_pos)
602 bool success = false;
605 d->cursor_.clearSelection();
607 // if a valid par_id is given, try it first
608 // This is the case for a 'live' bookmark when unique paragraph ID
609 // is used to track bookmarks.
611 ParIterator par = buffer_.getParFromID(top_id);
612 if (par != buffer_.par_iterator_end()) {
613 doc_it = makeDocIterator(par, min(par->size(), top_pos));
614 // Some slices of the iterator may not be
615 // reachable (e.g. closed collapsable inset)
616 // so the dociterator may need to be
617 // shortened. Otherwise, setCursor may crash
618 // lyx when the cursor can not be set to these
620 size_t const n = doc_it.depth();
621 for (size_t i = 0; i < n; ++i)
622 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
630 // if top_id == 0, or searching through top_id failed
631 // This is the case for a 'restored' bookmark when only bottom
632 // (document level) pit was saved. Because of this, bookmark
633 // restoration is inaccurate. If a bookmark was within an inset,
634 // it will be restored to the left of the outmost inset that contains
636 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
637 doc_it = doc_iterator_begin(buffer_.inset());
638 doc_it.pit() = bottom_pit;
639 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
644 // Note: only bottom (document) level pit is set.
646 // set the current font.
647 d->cursor_.setCurrentFont();
648 // To center the screen on this new position we need the
649 // paragraph position which is computed at draw() time.
650 // So we need a redraw!
653 // We need another redraw because of the screen recentering.
661 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
663 if (lyxrc.rtl_support) {
664 if (d->cursor_.real_current_font.isRightToLeft()) {
665 if (d->intl_.keymap == Intl::PRIMARY)
666 d->intl_.keyMapSec();
668 if (d->intl_.keymap == Intl::SECONDARY)
669 d->intl_.keyMapPrim();
673 d->intl_.getTransManager().translateAndInsert(c, t, cur);
677 int BufferView::workWidth() const
683 void BufferView::updateOffsetRef()
685 // No need to update d->offset_ref_ in this case.
686 if (!d->need_centering_)
689 // We are not properly started yet, delay until resizing is
694 CursorSlice & bot = d->cursor_.bottom();
695 TextMetrics & tm = d->text_metrics_[bot.text()];
696 ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
697 int y = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
698 d->offset_ref_ = y + pm.ascent() - height_ / 2;
700 d->need_centering_ = false;
704 void BufferView::center()
706 d->anchor_ref_ = d->cursor_.bottom().pit();
707 d->need_centering_ = true;
711 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
715 Cursor & cur = d->cursor_;
717 switch (cmd.action) {
720 flag.enabled(buffer_.undo().hasUndoStack());
723 flag.enabled(buffer_.undo().hasRedoStack());
725 case LFUN_FILE_INSERT:
726 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
727 case LFUN_FILE_INSERT_PLAINTEXT:
728 case LFUN_BOOKMARK_SAVE:
729 // FIXME: Actually, these LFUNS should be moved to Text
730 flag.enabled(cur.inTexted());
732 case LFUN_FONT_STATE:
733 case LFUN_LABEL_INSERT:
734 case LFUN_INFO_INSERT:
735 case LFUN_PARAGRAPH_GOTO:
737 case LFUN_REFERENCE_NEXT:
739 case LFUN_WORD_REPLACE:
742 case LFUN_MARK_TOGGLE:
743 case LFUN_SCREEN_RECENTER:
744 case LFUN_BIBTEX_DATABASE_ADD:
745 case LFUN_BIBTEX_DATABASE_DEL:
746 case LFUN_WORDS_COUNT:
747 case LFUN_NEXT_INSET_TOGGLE:
751 case LFUN_LABEL_GOTO: {
752 flag.enabled(!cmd.argument().empty()
753 || getInsetByCode<InsetRef>(cur, REF_CODE));
757 case LFUN_CHANGES_TRACK:
759 flag.setOnOff(buffer_.params().trackChanges);
762 case LFUN_CHANGES_OUTPUT:
764 flag.setOnOff(buffer_.params().outputChanges);
767 case LFUN_CHANGES_MERGE:
768 case LFUN_CHANGE_NEXT:
769 case LFUN_ALL_CHANGES_ACCEPT:
770 case LFUN_ALL_CHANGES_REJECT:
771 // TODO: context-sensitive enabling of LFUNs
772 // In principle, these command should only be enabled if there
773 // is a change in the document. However, without proper
774 // optimizations, this will inevitably result in poor performance.
778 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
779 flag.setOnOff(buffer_.params().compressed);
783 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
784 flag.setOnOff(buffer_.params().embedded);
789 case LFUN_SCREEN_DOWN:
793 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
794 // everywhere else before this can enabled:
795 case LFUN_SCREEN_UP_SELECT:
796 case LFUN_SCREEN_DOWN_SELECT:
800 case LFUN_LAYOUT_TABULAR:
801 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
805 case LFUN_LAYOUT_PARAGRAPH:
806 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
809 case LFUN_INSET_SETTINGS: {
810 InsetCode code = cur.inset().lyxCode();
814 enable = cmd.argument() == "tabular";
817 enable = cmd.argument() == "ert";
820 enable = cmd.argument() == "float";
823 enable = cmd.argument() == "wrap";
826 enable = cmd.argument() == "note";
829 enable = cmd.argument() == "branch";
832 enable = cmd.argument() == "box";
835 enable = cmd.argument() == "listings";
840 flag.enabled(enable);
844 case LFUN_DIALOG_SHOW_NEW_INSET:
845 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
846 cur.inset().lyxCode() != LISTINGS_CODE);
847 if (cur.inset().lyxCode() == CAPTION_CODE) {
849 if (cur.inset().getStatus(cur, cmd, flag))
862 Update::flags BufferView::dispatch(FuncRequest const & cmd)
864 //lyxerr << BOOST_CURRENT_FUNCTION
865 // << [ cmd = " << cmd << "]" << endl;
867 // Make sure that the cached BufferView is correct.
868 LYXERR(Debug::ACTION, BOOST_CURRENT_FUNCTION
869 << " action[" << cmd.action << ']'
870 << " arg[" << to_utf8(cmd.argument()) << ']'
871 << " x[" << cmd.x << ']'
872 << " y[" << cmd.y << ']'
873 << " button[" << cmd.button() << ']');
875 Cursor & cur = d->cursor_;
876 // Default Update flags.
877 Update::flags updateFlags = Update::Force | Update::FitCursor;
879 switch (cmd.action) {
882 cur.message(_("Undo"));
883 cur.clearSelection();
884 if (!cur.textUndo()) {
885 cur.message(_("No further undo information"));
886 updateFlags = Update::None;
891 cur.message(_("Redo"));
892 cur.clearSelection();
893 if (!cur.textRedo()) {
894 cur.message(_("No further redo information"));
895 updateFlags = Update::None;
899 case LFUN_FILE_INSERT:
901 menuInsertLyXFile(to_utf8(cmd.argument()));
904 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
906 insertPlaintextFile(to_utf8(cmd.argument()), true);
909 case LFUN_FILE_INSERT_PLAINTEXT:
911 insertPlaintextFile(to_utf8(cmd.argument()), false);
914 case LFUN_FONT_STATE:
915 cur.message(cur.currentState());
918 case LFUN_BOOKMARK_SAVE:
919 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
922 case LFUN_LABEL_GOTO: {
923 docstring label = cmd.argument();
926 getInsetByCode<InsetRef>(d->cursor_,
929 label = inset->getParam("reference");
930 // persistent=false: use temp_bookmark
940 case LFUN_PARAGRAPH_GOTO: {
941 int const id = convert<int>(to_utf8(cmd.argument()));
943 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
944 b = theBufferList().next(b)) {
946 ParIterator par = b->getParFromID(id);
947 if (par == b->par_iterator_end()) {
948 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
950 LYXERR(Debug::INFO, "Paragraph " << par->id()
951 << " found in buffer `"
952 << b->absFileName() << "'.");
956 setCursor(makeDocIterator(par, 0));
958 // Switch to other buffer view and resend cmd
959 theLyXFunc().dispatch(FuncRequest(
960 LFUN_BUFFER_SWITCH, b->absFileName()));
961 theLyXFunc().dispatch(cmd);
962 updateFlags = Update::None;
972 gotoInset(this, NOTE_CODE, false);
975 case LFUN_REFERENCE_NEXT: {
976 vector<InsetCode> tmp;
977 tmp.push_back(LABEL_CODE);
978 tmp.push_back(REF_CODE);
979 gotoInset(this, tmp, true);
983 case LFUN_CHANGES_TRACK:
984 buffer_.params().trackChanges = !buffer_.params().trackChanges;
987 case LFUN_CHANGES_OUTPUT:
988 buffer_.params().outputChanges = !buffer_.params().outputChanges;
989 if (buffer_.params().outputChanges) {
990 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
991 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
992 LaTeXFeatures::isAvailable("xcolor");
994 if (!dvipost && !xcolorsoul) {
995 Alert::warning(_("Changes not shown in LaTeX output"),
996 _("Changes will not be highlighted in LaTeX output, "
997 "because neither dvipost nor xcolor/soul are installed.\n"
998 "Please install these packages or redefine "
999 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1000 } else if (!xcolorsoul) {
1001 Alert::warning(_("Changes not shown in LaTeX output"),
1002 _("Changes will not be highlighted in LaTeX output "
1003 "when using pdflatex, because xcolor and soul are not installed.\n"
1004 "Please install both packages or redefine "
1005 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1010 case LFUN_CHANGE_NEXT:
1011 findNextChange(this);
1014 case LFUN_CHANGES_MERGE:
1015 if (findNextChange(this))
1016 showDialog("changes");
1019 case LFUN_ALL_CHANGES_ACCEPT:
1020 // select complete document
1021 d->cursor_.reset(buffer_.inset());
1022 d->cursor_.selHandle(true);
1023 buffer_.text().cursorBottom(d->cursor_);
1024 // accept everything in a single step to support atomic undo
1025 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1028 case LFUN_ALL_CHANGES_REJECT:
1029 // select complete document
1030 d->cursor_.reset(buffer_.inset());
1031 d->cursor_.selHandle(true);
1032 buffer_.text().cursorBottom(d->cursor_);
1033 // reject everything in a single step to support atomic undo
1034 // Note: reject does not work recursively; the user may have to repeat the operation
1035 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1038 case LFUN_WORD_FIND:
1042 case LFUN_WORD_REPLACE: {
1043 bool has_deleted = false;
1044 if (cur.selection()) {
1045 DocIterator beg = cur.selectionBegin();
1046 DocIterator end = cur.selectionEnd();
1047 if (beg.pit() == end.pit()) {
1048 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1049 if (cur.paragraph().isDeleted(p))
1054 replace(this, cmd, has_deleted);
1059 cur.clearSelection();
1061 cur.message(from_utf8(N_("Mark off")));
1065 cur.clearSelection();
1068 cur.message(from_utf8(N_("Mark on")));
1071 case LFUN_MARK_TOGGLE:
1072 cur.clearSelection();
1075 cur.message(from_utf8(N_("Mark removed")));
1078 cur.message(from_utf8(N_("Mark set")));
1083 case LFUN_SCREEN_RECENTER:
1087 case LFUN_BIBTEX_DATABASE_ADD: {
1088 Cursor tmpcur = d->cursor_;
1089 findInset(tmpcur, BIBTEX_CODE, false);
1090 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1093 if (inset->addDatabase(to_utf8(cmd.argument())))
1094 buffer_.updateBibfilesCache();
1099 case LFUN_BIBTEX_DATABASE_DEL: {
1100 Cursor tmpcur = d->cursor_;
1101 findInset(tmpcur, BIBTEX_CODE, false);
1102 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1105 if (inset->delDatabase(to_utf8(cmd.argument())))
1106 buffer_.updateBibfilesCache();
1111 case LFUN_WORDS_COUNT: {
1112 DocIterator from, to;
1113 if (cur.selection()) {
1114 from = cur.selectionBegin();
1115 to = cur.selectionEnd();
1117 from = doc_iterator_begin(buffer_.inset());
1118 to = doc_iterator_end(buffer_.inset());
1120 int const count = countWords(from, to);
1123 if (cur.selection())
1124 message = bformat(_("%1$d words in selection."),
1127 message = bformat(_("%1$d words in document."),
1131 if (cur.selection())
1132 message = _("One word in selection.");
1134 message = _("One word in document.");
1137 Alert::information(_("Count words"), message);
1141 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1142 // turn compression on/off
1143 buffer_.params().compressed = !buffer_.params().compressed;
1146 case LFUN_BUFFER_TOGGLE_EMBEDDING:
1147 // turn embedding on/off
1148 buffer_.embeddedFiles().enable(!buffer_.params().embedded);
1151 case LFUN_NEXT_INSET_TOGGLE: {
1152 // this is the real function we want to invoke
1153 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1154 // if there is an inset at cursor, see whether it
1156 Inset * inset = cur.nextInset();
1158 if (inset->isActive()) {
1159 Cursor tmpcur = cur;
1160 tmpcur.pushBackward(*inset);
1161 inset->dispatch(tmpcur, tmpcmd);
1162 if (tmpcur.result().dispatched()) {
1165 } else if (inset->editable() == Inset::IS_EDITABLE) {
1166 inset->edit(cur, true);
1169 // if it did not work, try the underlying inset.
1170 if (!cur.result().dispatched())
1171 cur.dispatch(tmpcmd);
1173 if (cur.result().dispatched())
1174 cur.clearSelection();
1179 case LFUN_SCREEN_UP:
1180 case LFUN_SCREEN_DOWN: {
1181 Point p = getPos(cur, cur.boundary());
1182 if (p.y_ < 0 || p.y_ > height_) {
1183 // The cursor is off-screen so recenter before proceeding.
1186 //FIXME: updateMetrics() does not update paragraph position
1187 // This is done at draw() time. So we need a redraw!
1188 // But no screen update is needed.
1189 d->update_strategy_ = NoScreenUpdate;
1191 p = getPos(cur, cur.boundary());
1193 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1194 cur.reset(buffer_.inset());
1195 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1196 //FIXME: what to do with cur.x_target()?
1198 // The metrics are already up to date. see scroll()
1199 updateFlags = Update::None;
1203 case LFUN_SCREEN_UP_SELECT:
1204 case LFUN_SCREEN_DOWN_SELECT: {
1205 cur.selHandle(true);
1206 size_t initial_depth = cur.depth();
1207 Point const p = getPos(cur, cur.boundary());
1208 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1209 // FIXME: We need to verify if the cursor stayed within an inset...
1210 //cur.reset(buffer_.inset());
1211 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1213 while (cur.depth() > initial_depth) {
1216 // FIXME: we need to do a redraw again because of the selection
1217 // But no screen update is needed.
1218 d->update_strategy_ = NoScreenUpdate;
1220 updateFlags = Update::Force | Update::FitCursor;
1225 updateFlags = Update::None;
1232 docstring const BufferView::requestSelection()
1234 Cursor & cur = d->cursor_;
1236 if (!cur.selection()) {
1237 d->xsel_cache_.set = false;
1241 if (!d->xsel_cache_.set ||
1242 cur.top() != d->xsel_cache_.cursor ||
1243 cur.anchor_.top() != d->xsel_cache_.anchor)
1245 d->xsel_cache_.cursor = cur.top();
1246 d->xsel_cache_.anchor = cur.anchor_.top();
1247 d->xsel_cache_.set = cur.selection();
1248 return cur.selectionAsString(false);
1254 void BufferView::clearSelection()
1256 d->cursor_.clearSelection();
1257 // Clear the selection buffer. Otherwise a subsequent
1258 // middle-mouse-button paste would use the selection buffer,
1259 // not the more current external selection.
1260 cap::clearSelection();
1261 d->xsel_cache_.set = false;
1262 // The buffer did not really change, but this causes the
1263 // redraw we need because we cleared the selection above.
1268 void BufferView::resize(int width, int height)
1270 // Update from work area
1278 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1280 TextMetrics & tm = d->text_metrics_[&text];
1281 Inset * inset = tm.checkInsetHit(x, y);
1285 if (!inset->descendable())
1286 // No need to go further down if the inset is not
1290 size_t cell_number = inset->nargs();
1291 // Check all the inner cell.
1292 for (size_t i = 0; i != cell_number; ++i) {
1293 Text const * inner_text = inset->getText(i);
1296 Inset const * inset_deeper =
1297 getCoveringInset(*inner_text, x, y);
1299 return inset_deeper;
1307 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1309 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1311 // This is only called for mouse related events including
1312 // LFUN_FILE_OPEN generated by drag-and-drop.
1313 FuncRequest cmd = cmd0;
1316 cur.push(buffer_.inset());
1317 cur.selection() = d->cursor_.selection();
1319 // Either the inset under the cursor or the
1320 // surrounding Text will handle this event.
1322 // make sure we stay within the screen...
1323 cmd.y = min(max(cmd.y, -1), height_);
1325 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1327 // Get inset under mouse, if there is one.
1328 Inset const * covering_inset =
1329 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1330 if (covering_inset == d->last_inset_)
1331 // Same inset, no need to do anything...
1334 bool need_redraw = false;
1335 // const_cast because of setMouseHover().
1336 Inset * inset = const_cast<Inset *>(covering_inset);
1338 // Remove the hint on the last hovered inset (if any).
1339 need_redraw |= d->last_inset_->setMouseHover(false);
1341 // Highlighted the newly hovered inset (if any).
1342 need_redraw |= inset->setMouseHover(true);
1343 d->last_inset_ = inset;
1347 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1348 << cmd.x << ", " << cmd.y << ")");
1350 d->update_strategy_ = DecorationUpdate;
1352 // This event (moving without mouse click) is not passed further.
1353 // This should be changed if it is further utilized.
1358 // Build temporary cursor.
1359 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1361 // Put anchor at the same position.
1364 // Try to dispatch to an non-editable inset near this position
1365 // via the temp cursor. If the inset wishes to change the real
1366 // cursor it has to do so explicitly by using
1367 // cur.bv().cursor() = cur; (or similar)
1369 inset->dispatch(cur, cmd);
1371 // Now dispatch to the temporary cursor. If the real cursor should
1372 // be modified, the inset's dispatch has to do so explicitly.
1373 if (!cur.result().dispatched())
1376 //Do we have a selection?
1377 theSelection().haveSelection(cursor().selection());
1379 // If the command has been dispatched,
1380 if (cur.result().dispatched()
1381 // an update is asked,
1382 && cur.result().update())
1383 processUpdateFlags(cur.result().update());
1387 void BufferView::scroll(int y)
1396 void BufferView::scrollDown(int offset)
1398 Text * text = &buffer_.text();
1399 TextMetrics & tm = d->text_metrics_[text];
1400 int ymax = height_ + offset;
1402 std::pair<pit_type, ParagraphMetrics const *> last = tm.last();
1403 int bottom_pos = last.second->position() + last.second->descent();
1404 if (last.first + 1 == int(text->paragraphs().size())) {
1405 if (bottom_pos <= height_)
1407 offset = min(offset, bottom_pos - height_);
1410 if (bottom_pos > ymax)
1412 tm.newParMetricsDown();
1414 d->offset_ref_ += offset;
1420 void BufferView::scrollUp(int offset)
1422 Text * text = &buffer_.text();
1423 TextMetrics & tm = d->text_metrics_[text];
1424 int ymin = - offset;
1426 std::pair<pit_type, ParagraphMetrics const *> first = tm.first();
1427 int top_pos = first.second->position() - first.second->ascent();
1428 if (first.first == 0) {
1431 offset = min(offset, - top_pos);
1436 tm.newParMetricsUp();
1438 d->offset_ref_ -= offset;
1444 void BufferView::setCursorFromRow(int row)
1449 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1451 d->cursor_.reset(buffer_.inset());
1453 buffer_.text().setCursor(d->cursor_, 0, 0);
1455 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1459 void BufferView::gotoLabel(docstring const & label)
1461 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1462 vector<docstring> labels;
1463 it->getLabelList(buffer_, labels);
1464 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1466 processUpdateFlags(Update::FitCursor);
1473 TextMetrics const & BufferView::textMetrics(Text const * t) const
1475 return const_cast<BufferView *>(this)->textMetrics(t);
1479 TextMetrics & BufferView::textMetrics(Text const * t)
1481 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1482 if (tmc_it == d->text_metrics_.end()) {
1483 tmc_it = d->text_metrics_.insert(
1484 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1486 return tmc_it->second;
1490 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1493 return textMetrics(t).parMetrics(pit);
1497 int BufferView::workHeight() const
1503 void BufferView::setCursor(DocIterator const & dit)
1505 size_t const n = dit.depth();
1506 for (size_t i = 0; i < n; ++i)
1507 dit[i].inset().edit(d->cursor_, true);
1509 d->cursor_.setCursor(dit);
1510 d->cursor_.selection() = false;
1514 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1516 // Would be wrong to delete anything if we have a selection.
1517 if (cur.selection())
1520 bool need_anchor_change = false;
1521 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1522 need_anchor_change);
1524 if (need_anchor_change)
1530 updateLabels(buffer_);
1538 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1540 BOOST_ASSERT(&cur.bv() == this);
1543 // this event will clear selection so we save selection for
1544 // persistent selection
1545 cap::saveSelection(cursor());
1547 // Has the cursor just left the inset?
1548 bool badcursor = false;
1549 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1551 badcursor = notifyCursorLeaves(d->cursor_, cur);
1553 // FIXME: shift-mouse selection doesn't work well across insets.
1554 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1556 // do the dEPM magic if needed
1557 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1558 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1559 // the leftinset bool would not be necessary (badcursor instead).
1560 bool update = leftinset;
1561 if (!do_selection && !badcursor && d->cursor_.inTexted())
1562 update |= checkDepm(cur, d->cursor_);
1564 // if the cursor was in an empty script inset and the new
1565 // position is in the nucleus of the inset, notifyCursorLeaves
1566 // will kill the script inset itself. So we check all the
1567 // elements of the cursor to make sure that they are correct.
1568 // For an example, see bug 2933:
1569 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1570 // The code below could maybe be moved to a DocIterator method.
1571 //lyxerr << "cur before " << cur <<std::endl;
1572 DocIterator dit(cur.inset());
1573 dit.push_back(cur.bottom());
1575 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1576 dit.push_back(cur[i]);
1579 //lyxerr << "5 cur after" << dit <<std::endl;
1581 d->cursor_.setCursor(dit);
1582 d->cursor_.boundary(cur.boundary());
1584 d->cursor_.setSelection();
1586 d->cursor_.clearSelection();
1588 d->cursor_.finishUndo();
1589 d->cursor_.setCurrentFont();
1594 void BufferView::putSelectionAt(DocIterator const & cur,
1595 int length, bool backwards)
1597 d->cursor_.clearSelection();
1603 d->cursor_.pos() += length;
1604 d->cursor_.setSelection(d->cursor_, -length);
1606 d->cursor_.setSelection(d->cursor_, length);
1611 Cursor & BufferView::cursor()
1617 Cursor const & BufferView::cursor() const
1623 pit_type BufferView::anchor_ref() const
1625 return d->anchor_ref_;
1629 bool BufferView::singleParUpdate()
1631 Text & buftext = buffer_.text();
1632 pit_type const bottom_pit = d->cursor_.bottom().pit();
1633 TextMetrics & tm = textMetrics(&buftext);
1634 int old_height = tm.parMetrics(bottom_pit).height();
1636 // In Single Paragraph mode, rebreak only
1637 // the (main text, not inset!) paragraph containing the cursor.
1638 // (if this paragraph contains insets etc., rebreaking will
1639 // recursively descend)
1640 tm.redoParagraph(bottom_pit);
1641 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1642 if (pm.height() != old_height)
1643 // Paragraph height has changed so we cannot proceed to
1644 // the singlePar optimisation.
1647 d->update_strategy_ = SingleParUpdate;
1649 LYXERR(Debug::PAINTING, BOOST_CURRENT_FUNCTION
1650 << "\ny1: " << pm.position() - pm.ascent()
1651 << " y2: " << pm.position() + pm.descent()
1652 << " pit: " << bottom_pit
1653 << " singlepar: 1");
1658 void BufferView::updateMetrics()
1660 Text & buftext = buffer_.text();
1661 pit_type const npit = int(buftext.paragraphs().size());
1663 if (d->anchor_ref_ > int(npit - 1)) {
1664 d->anchor_ref_ = int(npit - 1);
1668 // Clear out the position cache in case of full screen redraw,
1669 d->coord_cache_.clear();
1671 // Clear out paragraph metrics to avoid having invalid metrics
1672 // in the cache from paragraphs not relayouted below
1673 // The complete text metrics will be redone.
1674 d->text_metrics_.clear();
1676 TextMetrics & tm = textMetrics(&buftext);
1678 pit_type const pit = d->anchor_ref_;
1682 // Rebreak anchor paragraph.
1683 tm.redoParagraph(pit);
1685 // Take care of anchor offset if case a recentering is needed.
1688 int y0 = tm.parMetrics(pit).ascent() - d->offset_ref_;
1690 // Redo paragraphs above anchor if necessary.
1692 while (y1 > 0 && pit1 > 0) {
1693 y1 -= tm.parMetrics(pit1).ascent();
1695 tm.redoParagraph(pit1);
1696 y1 -= tm.parMetrics(pit1).descent();
1699 // Take care of ascent of first line
1700 y1 -= tm.parMetrics(pit1).ascent();
1702 // Normalize anchor for next time
1703 d->anchor_ref_ = pit1;
1704 d->offset_ref_ = -y1;
1706 // Grey at the beginning is ugly
1707 if (pit1 == 0 && y1 > 0) {
1713 // Redo paragraphs below the anchor if necessary.
1715 while (y2 < height_ && pit2 < int(npit) - 1) {
1716 y2 += tm.parMetrics(pit2).descent();
1718 tm.redoParagraph(pit2);
1719 y2 += tm.parMetrics(pit2).ascent();
1722 // Take care of descent of last line
1723 y2 += tm.parMetrics(pit2).descent();
1725 LYXERR(Debug::PAINTING, BOOST_CURRENT_FUNCTION
1728 << " pit1: " << pit1
1729 << " pit2: " << pit2
1730 << " npit: " << npit
1731 << " singlepar: 0");
1733 d->update_strategy_ = FullScreenUpdate;
1735 if (lyxerr.debugging(Debug::WORKAREA)) {
1736 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1737 d->coord_cache_.dump();
1742 void BufferView::menuInsertLyXFile(string const & filenm)
1744 BOOST_ASSERT(d->cursor_.inTexted());
1745 string filename = filenm;
1747 if (filename.empty()) {
1748 // Launch a file browser
1750 string initpath = lyxrc.document_path;
1751 string const trypath = buffer_.filePath();
1752 // If directory is writeable, use this as default.
1753 if (FileName(trypath).isDirWritable())
1757 FileDialog dlg(_("Select LyX document to insert"), LFUN_FILE_INSERT);
1758 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1759 dlg.setButton2(_("Examples|#E#e"),
1760 from_utf8(addPath(package().system_support().absFilename(),
1763 FileDialog::Result result =
1764 dlg.open(from_utf8(initpath),
1765 FileFilterList(_("LyX Documents (*.lyx)")),
1768 if (result.first == FileDialog::Later)
1772 filename = to_utf8(result.second);
1774 // check selected filename
1775 if (filename.empty()) {
1776 // emit message signal.
1777 message(_("Canceled."));
1782 // Get absolute path of file and add ".lyx"
1783 // to the filename if necessary
1784 filename = fileSearch(string(), filename, "lyx").absFilename();
1786 docstring const disp_fn = makeDisplayPath(filename);
1787 // emit message signal.
1788 message(bformat(_("Inserting document %1$s..."), disp_fn));
1791 Buffer buf("", false);
1792 if (buf.loadLyXFile(FileName(filename))) {
1793 ErrorList & el = buffer_.errorList("Parse");
1794 // Copy the inserted document error list into the current buffer one.
1795 el = buf.errorList("Parse");
1796 buffer_.undo().recordUndo(d->cursor_);
1797 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1798 buf.params().getTextClassPtr(), el);
1799 res = _("Document %1$s inserted.");
1801 res = _("Could not insert document %1$s");
1804 // emit message signal.
1805 message(bformat(res, disp_fn));
1806 buffer_.errors("Parse");
1811 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1817 // Addup contribution of nested insets, from inside to outside,
1818 // keeping the outer paragraph for a special handling below
1819 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1820 CursorSlice const & sl = dit[i];
1824 // get relative position inside sl.inset()
1825 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1827 // Make relative position inside of the edited inset relative to sl.inset()
1831 // In case of an RTL inset, the edited inset will be positioned to the left
1834 bool boundary_i = boundary && i + 1 == dit.depth();
1835 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1840 // remember width for the case that sl.inset() is positioned in an RTL inset
1841 if (i && dit[i - 1].text()) {
1842 // If this Inset is inside a Text Inset, retrieve the Dimension
1843 // from the containing text instead of using Inset::dimension() which
1844 // might not be implemented.
1845 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1846 // elimination of Inset::dim_ cache. This coordOffset() method needs
1847 // to be rewritten in light of the new design.
1848 Dimension const & dim = parMetrics(dit[i - 1].text(),
1849 dit[i - 1].pit()).insetDimension(&sl.inset());
1852 Dimension const dim = sl.inset().dimension(*this);
1856 //lyxerr << "Cursor::getPos, i: "
1857 // << i << " x: " << xx << " y: " << y << endl;
1860 // Add contribution of initial rows of outermost paragraph
1861 CursorSlice const & sl = dit[0];
1862 TextMetrics const & tm = textMetrics(sl.text());
1863 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1864 BOOST_ASSERT(!pm.rows().empty());
1865 y -= pm.rows()[0].ascent();
1867 // FIXME: document this mess
1869 if (sl.pos() > 0 && dit.depth() == 1) {
1871 if (pos && boundary)
1873 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << std::endl;
1874 rend = pm.pos2row(pos);
1876 rend = pm.pos2row(sl.pos());
1878 size_t rend = pm.pos2row(sl.pos());
1880 for (size_t rit = 0; rit != rend; ++rit)
1881 y += pm.rows()[rit].height();
1882 y += pm.rows()[rend].ascent();
1884 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1886 // Make relative position from the nested inset now bufferview absolute.
1887 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1890 // In the RTL case place the nested inset at the left of the cursor in
1891 // the outer paragraph
1892 bool boundary_1 = boundary && 1 == dit.depth();
1893 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1901 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1903 CursorSlice const & bot = dit.bottom();
1904 TextMetrics const & tm = textMetrics(bot.text());
1905 if (!tm.has(bot.pit()))
1906 return Point(-1, -1);
1908 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1909 p.y_ += tm.parMetrics(bot.pit()).position();
1914 void BufferView::draw(frontend::Painter & pain)
1916 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1917 Text & text = buffer_.text();
1918 TextMetrics const & tm = d->text_metrics_[&text];
1919 int const y = - d->offset_ref_ + tm.parMetrics(d->anchor_ref_).ascent();
1920 PainterInfo pi(this, pain);
1922 switch (d->update_strategy_) {
1924 case NoScreenUpdate:
1925 // If no screen painting is actually needed, only some the different
1926 // coordinates of insets and paragraphs needs to be updated.
1927 pi.full_repaint = true;
1928 pi.pain.setDrawingEnabled(false);
1932 case SingleParUpdate:
1933 pi.full_repaint = false;
1934 // In general, only the current row of the outermost paragraph
1935 // will be redrawn. Particular cases where selection spans
1936 // multiple paragraph are correctly detected in TextMetrics.
1940 case DecorationUpdate:
1941 // FIXME: We should also distinguish DecorationUpdate to avoid text
1942 // drawing if possible. This is not possible to do easily right now
1943 // because of the single backing pixmap.
1945 case FullScreenUpdate:
1946 // The whole screen, including insets, will be refreshed.
1947 pi.full_repaint = true;
1949 // Clear background.
1950 pain.fillRectangle(0, 0, width_, height_,
1951 buffer_.inset().backgroundColor());
1954 // and possibly grey out below
1955 std::pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1956 int const y2 = lastpm.second->position() + lastpm.second->descent();
1958 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
1962 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
1966 void BufferView::message(docstring const & msg)
1969 d->gui_->message(msg);
1973 void BufferView::showDialog(std::string const & name)
1976 d->gui_->showDialog(name, string());
1980 void BufferView::showDialog(std::string const & name,
1981 std::string const & data, Inset * inset)
1984 d->gui_->showDialog(name, data, inset);
1988 void BufferView::updateDialog(std::string const & name, std::string const & data)
1991 d->gui_->updateDialog(name, data);
1995 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2001 // FIXME: Move this out of BufferView again
2002 docstring BufferView::contentsOfPlaintextFile(string const & f,
2007 if (fname.empty()) {
2008 FileDialog dlg(_("Select file to insert"),
2010 ? LFUN_FILE_INSERT_PLAINTEXT_PARA
2011 : LFUN_FILE_INSERT_PLAINTEXT) );
2013 FileDialog::Result result =
2014 dlg.open(from_utf8(buffer().filePath()),
2015 FileFilterList(), docstring());
2017 if (result.first == FileDialog::Later)
2020 if (result.second.empty())
2023 fname = makeAbsPath(to_utf8(result.second));
2026 if (!fname.isReadableFile()) {
2027 docstring const error = from_ascii(strerror(errno));
2028 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2029 docstring const text =
2030 bformat(_("Could not read the specified document\n"
2031 "%1$s\ndue to the error: %2$s"), file, error);
2032 Alert::error(_("Could not read file"), text);
2036 ifstream ifs(fname.toFilesystemEncoding().c_str());
2038 docstring const error = from_ascii(strerror(errno));
2039 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2040 docstring const text =
2041 bformat(_("Could not open the specified document\n"
2042 "%1$s\ndue to the error: %2$s"), file, error);
2043 Alert::error(_("Could not open file"), text);
2047 ifs.unsetf(std::ios::skipws);
2048 istream_iterator<char> ii(ifs);
2049 istream_iterator<char> end;
2050 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
2051 // We use this until the compilers get better...
2052 std::vector<char> tmp;
2053 copy(ii, end, back_inserter(tmp));
2054 string const tmpstr(tmp.begin(), tmp.end());
2056 // This is what we want to use and what we will use once the
2057 // compilers get good enough.
2058 //string tmpstr(ii, end); // yet a reason for using std::string
2059 // alternate approach to get the file into a string:
2061 copy(ii, end, back_inserter(tmpstr));
2064 // FIXME UNICODE: We don't know the encoding of the file
2065 docstring file_content = from_utf8(tmpstr);
2066 if (file_content.empty()) {
2067 Alert::error(_("Reading not UTF-8 encoded file"),
2068 _("The file is not UTF-8 encoded.\n"
2069 "It will be read as local 8Bit-encoded.\n"
2070 "If this does not give the correct result\n"
2071 "then please change the encoding of the file\n"
2072 "to UTF-8 with a program other than LyX.\n"));
2073 file_content = from_local8bit(tmpstr);
2076 return normalize_c(file_content);
2080 void BufferView::insertPlaintextFile(string const & f, bool asParagraph)
2082 docstring const tmpstr = contentsOfPlaintextFile(f, asParagraph);
2087 Cursor & cur = cursor();
2088 cap::replaceSelection(cur);
2089 buffer_.undo().recordUndo(cur);
2091 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2093 cur.innerText()->insertStringAsLines(cur, tmpstr);