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"
24 #include "CutAndPaste.h"
26 #include "DispatchResult.h"
27 #include "ErrorList.h"
29 #include "FloatList.h"
30 #include "FuncRequest.h"
31 #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"
50 #include "TextClass.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/FileFilterList.h"
71 #include "support/filetools.h"
72 #include "support/Package.h"
73 #include "support/types.h"
74 #include "support/fs_extras.h"
76 #include <boost/bind.hpp>
77 #include <boost/current_function.hpp>
78 #include <boost/next_prior.hpp>
79 #include <boost/filesystem/operations.hpp>
89 using std::istringstream;
90 using std::istream_iterator;
94 using std::mem_fun_ref;
98 namespace fs = boost::filesystem;
102 using support::addPath;
103 using support::bformat;
104 using support::FileFilterList;
105 using support::FileName;
106 using support::fileSearch;
107 using support::isDirWriteable;
108 using support::isFileReadable;
109 using support::makeDisplayPath;
110 using support::makeAbsPath;
111 using support::package;
113 namespace Alert = frontend::Alert;
117 /// Return an inset of this class if it exists at the current cursor position
119 T * getInsetByCode(Cursor const & cur, Inset::Code code)
121 DocIterator it = cur;
122 Inset * inset = it.nextInset();
123 if (inset && inset->lyxCode() == code)
124 return static_cast<T*>(inset);
129 bool findInset(DocIterator & dit, vector<Inset_code> const & codes,
132 bool findNextInset(DocIterator & dit, vector<Inset_code> const & codes,
133 string const & contents)
135 DocIterator tmpdit = dit;
138 Inset const * inset = tmpdit.nextInset();
140 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
141 && (contents.empty() ||
142 static_cast<InsetCommand const *>(inset)->getContents() == contents)) {
146 tmpdit.forwardInset();
153 /// Looks for next inset with one of the the given code
154 bool findInset(DocIterator & dit, vector<Inset_code> const & codes,
158 DocIterator tmpdit = dit;
159 tmpdit.forwardInset();
164 Inset const * inset = tmpdit.nextInset();
166 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
167 contents = static_cast<InsetCommand const *>(inset)->getContents();
171 if (!findNextInset(tmpdit, codes, contents)) {
172 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
173 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
174 if (!findNextInset(tmpdit, codes, contents))
185 /// Looks for next inset with the given code
186 void findInset(DocIterator & dit, Inset_code code, bool same_content)
188 findInset(dit, vector<Inset_code>(1, code), same_content);
192 /// Moves cursor to the next inset with one of the given codes.
193 void gotoInset(BufferView * bv, vector<Inset_code> const & codes,
196 Cursor tmpcur = bv->cursor();
197 if (!findInset(tmpcur, codes, same_content)) {
198 bv->cursor().message(_("No more insets"));
202 tmpcur.clearSelection();
203 bv->setCursor(tmpcur);
207 /// Moves cursor to the next inset with given code.
208 void gotoInset(BufferView * bv, Inset_code code, bool same_content)
210 gotoInset(bv, vector<Inset_code>(1, code), same_content);
215 /// the type of outline operation
217 OutlineUp, // Move this header with text down
218 OutlineDown, // Move this header with text up
219 OutlineIn, // Make this header deeper
220 OutlineOut // Make this header shallower
224 void outline(OutlineOp mode, Cursor & cur)
226 Buffer & buf = cur.buffer();
227 pit_type & pit = cur.pit();
228 ParagraphList & pars = buf.text().paragraphs();
229 ParagraphList::iterator bgn = pars.begin();
230 // The first paragraph of the area to be copied:
231 ParagraphList::iterator start = boost::next(bgn, pit);
232 // The final paragraph of area to be copied:
233 ParagraphList::iterator finish = start;
234 ParagraphList::iterator end = pars.end();
236 TextClass::const_iterator lit =
237 buf.params().getTextClass().begin();
238 TextClass::const_iterator const lend =
239 buf.params().getTextClass().end();
241 int const thistoclevel = start->layout()->toclevel;
245 // Move out (down) from this section header
248 // Seek the one (on same level) below
249 for (; finish != end; ++finish) {
250 toclevel = finish->layout()->toclevel;
251 if (toclevel != Layout::NOT_IN_TOC
252 && toclevel <= thistoclevel) {
256 ParagraphList::iterator dest = start;
257 // Move out (up) from this header
260 // Search previous same-level header above
263 toclevel = dest->layout()->toclevel;
265 && (toclevel == Layout::NOT_IN_TOC
266 || toclevel > thistoclevel));
267 // Not found; do nothing
268 if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
270 pit_type const newpit = std::distance(bgn, dest);
271 pit_type const len = std::distance(start, finish);
272 pit_type const deletepit = pit + len;
273 recordUndo(cur, Undo::ATOMIC, newpit, deletepit - 1);
274 pars.insert(dest, start, finish);
275 start = boost::next(pars.begin(), deletepit);
277 pars.erase(start, finish);
281 // Go down out of current header:
284 // Find next same-level header:
285 for (; finish != end; ++finish) {
286 toclevel = finish->layout()->toclevel;
287 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
290 ParagraphList::iterator dest = finish;
291 // Go one down from *this* header:
296 // Go further down to find header to insert in front of:
297 for (; dest != end; ++dest) {
298 toclevel = dest->layout()->toclevel;
299 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
302 // One such was found:
303 pit_type newpit = std::distance(bgn, dest);
304 pit_type const len = std::distance(start, finish);
305 recordUndo(cur, Undo::ATOMIC, pit, newpit - 1);
306 pars.insert(dest, start, finish);
307 start = boost::next(bgn, pit);
309 pars.erase(start, finish);
314 for (; lit != lend; ++lit) {
315 if ((*lit)->toclevel == thistoclevel + 1 &&
316 start->layout()->labeltype == (*lit)->labeltype) {
317 start->layout((*lit));
324 for (; lit != lend; ++lit) {
325 if ((*lit)->toclevel == thistoclevel - 1 &&
326 start->layout()->labeltype == (*lit)->labeltype) {
327 start->layout((*lit));
340 /////////////////////////////////////////////////////////////////////
344 /////////////////////////////////////////////////////////////////////
347 BufferView::BufferView(Buffer & buf)
348 : width_(0), height_(0), buffer_(buf), wh_(0),
350 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
351 need_centering_(false), intl_(new Intl), last_inset_(0),
354 xsel_cache_.set = false;
355 intl_->initKeyMapper(lyxrc.use_kbmap);
357 cursor_.push(buffer_.inset());
358 cursor_.resetAnchor();
359 cursor_.setCurrentFont();
361 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
362 graphics::Previews::get().generateBufferPreviews(buffer_);
366 BufferView::~BufferView()
368 // current buffer is going to be switched-off, save cursor pos
369 // Ideally, the whole cursor stack should be saved, but session
370 // currently can only handle bottom (whole document) level pit and pos.
371 // That is to say, if a cursor is in a nested inset, it will be
372 // restore to the left of the top level inset.
373 LyX::ref().session().lastFilePos().save(
374 support::FileName(buffer_.fileName()),
375 boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
379 Buffer & BufferView::buffer()
385 Buffer const & BufferView::buffer() const
391 bool BufferView::fitCursor()
393 if (cursorStatus(cursor_) == CUR_INSIDE) {
394 frontend::FontMetrics const & fm =
395 theFontMetrics(cursor_.getFont());
396 int const asc = fm.maxAscent();
397 int const des = fm.maxDescent();
398 Point const p = getPos(cursor_, cursor_.boundary());
399 if (p.y_ - asc >= 0 && p.y_ + des < height_)
407 bool BufferView::multiParSel()
409 if (!cursor_.selection())
411 bool ret = multiparsel_cache_;
412 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
413 // Either this, or previous selection spans paragraphs
414 return ret || multiparsel_cache_;
418 void BufferView::processUpdateFlags(Update::flags flags)
420 // last_inset_ points to the last visited inset. This pointer may become
421 // invalid because of keyboard editing. Since all such operations
422 // causes screen update(), I reset last_inset_ to avoid such a problem.
424 // This is close to a hot-path.
426 << BOOST_CURRENT_FUNCTION
427 << "[fitcursor = " << (flags & Update::FitCursor)
428 << ", forceupdate = " << (flags & Update::Force)
429 << ", singlepar = " << (flags & Update::SinglePar)
430 << "] buffer: " << &buffer_ << endl;
432 // Update macro store
433 if (!(cursor().inMathed() && cursor().inMacroMode()))
434 buffer_.buildMacros();
436 // Now do the first drawing step if needed. This consists on updating
437 // the CoordCache in updateMetrics().
438 // The second drawing step is done in WorkArea::redraw() if needed.
440 // Case when no explicit update is requested.
442 // no need to redraw anything.
443 metrics_info_.update_strategy = NoScreenUpdate;
447 if (flags == Update::Decoration) {
448 metrics_info_.update_strategy = DecorationUpdate;
453 if (flags == Update::FitCursor
454 || flags == (Update::Decoration | Update::FitCursor)) {
455 bool const fit_cursor = fitCursor();
456 // tell the frontend to update the screen if needed.
458 updateMetrics(false);
462 if (flags & Update::Decoration) {
463 metrics_info_.update_strategy = DecorationUpdate;
467 // no screen update is needed.
468 metrics_info_.update_strategy = NoScreenUpdate;
472 bool full_metrics = flags & Update::Force;
473 if (flags & Update::MultiParSel)
474 full_metrics |= multiParSel();
476 bool const single_par = !full_metrics;
477 updateMetrics(single_par);
479 if (!(flags & Update::FitCursor)) {
484 //FIXME: updateMetrics() does not update paragraph position
485 // This is done at draw() time. So we need a redraw!
488 // The screen has already been updated thanks to the
489 // 'buffer_.changed()' call three line above. So no need
493 // The screen has been recentered around the cursor position so
495 updateMetrics(false);
500 void BufferView::updateScrollbar()
502 Text & t = buffer_.text();
503 TextMetrics & tm = text_metrics_[&t];
505 int const parsize = int(t.paragraphs().size() - 1);
506 if (anchor_ref_ > parsize) {
507 anchor_ref_ = parsize;
512 << BOOST_CURRENT_FUNCTION
513 << " Updating scrollbar: height: " << t.paragraphs().size()
514 << " curr par: " << cursor_.bottom().pit()
515 << " default height " << defaultRowHeight() << endl;
517 // It would be better to fix the scrollbar to understand
518 // values in [0..1] and divide everything by wh
520 // estimated average paragraph height:
524 int h = tm.parMetrics(anchor_ref_).height();
526 // Normalize anchor/offset (MV):
527 while (offset_ref_ > h && anchor_ref_ < parsize) {
530 h = tm.parMetrics(anchor_ref_).height();
532 // Look at paragraph heights on-screen
535 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
538 int const h2 = tm.parMetrics(pit).height();
544 int const hav = sumh / nh;
545 // More realistic average paragraph height
550 scrollbarParameters_.height = (parsize + 1) * wh_;
551 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
552 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
556 ScrollbarParameters const & BufferView::scrollbarParameters() const
558 return scrollbarParameters_;
562 void BufferView::scrollDocView(int value)
564 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
565 << "[ value = " << value << "]" << endl;
567 Text & t = buffer_.text();
568 TextMetrics & tm = text_metrics_[&t];
570 float const bar = value / float(wh_ * t.paragraphs().size());
572 anchor_ref_ = int(bar * t.paragraphs().size());
573 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
574 anchor_ref_ = int(t.paragraphs().size()) - 1;
576 tm.redoParagraph(anchor_ref_);
577 int const h = tm.parMetrics(anchor_ref_).height();
578 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
579 updateMetrics(false);
584 void BufferView::setCursorFromScrollbar()
586 TextMetrics & tm = text_metrics_[&buffer_.text()];
588 int const height = 2 * defaultRowHeight();
589 int const first = height;
590 int const last = height_ - height;
591 Cursor & cur = cursor_;
593 switch (cursorStatus(cur)) {
595 // We reset the cursor because cursorStatus() does not
596 // work when the cursor is within mathed.
597 cur.reset(buffer_.inset());
598 tm.setCursorFromCoordinates(cur, 0, first);
599 cur.clearSelection();
602 // We reset the cursor because cursorStatus() does not
603 // work when the cursor is within mathed.
604 cur.reset(buffer_.inset());
605 tm.setCursorFromCoordinates(cur, 0, last);
606 cur.clearSelection();
609 int const y = getPos(cur, cur.boundary()).y_;
610 int const newy = min(last, max(y, first));
612 cur.reset(buffer_.inset());
613 tm.setCursorFromCoordinates(cur, 0, newy);
619 Change const BufferView::getCurrentChange() const
621 if (!cursor_.selection())
622 return Change(Change::UNCHANGED);
624 DocIterator dit = cursor_.selectionBegin();
625 return dit.paragraph().lookupChange(dit.pos());
629 // this could be used elsewhere as well?
630 // FIXME: This does not work within mathed!
631 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
633 Point const p = getPos(dit, dit.boundary());
636 if (p.y_ > workHeight())
642 void BufferView::saveBookmark(unsigned int idx)
644 // tenatively save bookmark, id and pos will be used to
645 // acturately locate a bookmark in a 'live' lyx session.
646 // pit and pos will be updated with bottom level pit/pos
648 LyX::ref().session().bookmarks().save(
649 FileName(buffer_.fileName()),
650 cursor_.bottom().pit(),
651 cursor_.bottom().pos(),
652 cursor_.paragraph().id(),
657 // emit message signal.
658 message(_("Save bookmark"));
662 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
663 int top_id, pos_type top_pos)
665 bool success = false;
668 cursor_.clearSelection();
670 // if a valid par_id is given, try it first
671 // This is the case for a 'live' bookmark when unique paragraph ID
672 // is used to track bookmarks.
674 ParIterator par = buffer_.getParFromID(top_id);
675 if (par != buffer_.par_iterator_end()) {
676 doc_it = makeDocIterator(par, min(par->size(), top_pos));
677 // Some slices of the iterator may not be
678 // reachable (e.g. closed collapsable inset)
679 // so the dociterator may need to be
680 // shortened. Otherwise, setCursor may crash
681 // lyx when the cursor can not be set to these
683 size_t const n = doc_it.depth();
684 for (size_t i = 0; i < n; ++i)
685 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
693 // if top_id == 0, or searching through top_id failed
694 // This is the case for a 'restored' bookmark when only bottom
695 // (document level) pit was saved. Because of this, bookmark
696 // restoration is inaccurate. If a bookmark was within an inset,
697 // it will be restored to the left of the outmost inset that contains
699 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
700 doc_it = doc_iterator_begin(buffer_.inset());
701 doc_it.pit() = bottom_pit;
702 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
707 // Note: only bottom (document) level pit is set.
709 // set the current font.
710 cursor_.setCurrentFont();
711 // center the screen on this new position.
719 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
721 if (lyxrc.rtl_support) {
722 if (cursor_.real_current_font.isRightToLeft()) {
723 if (intl_->keymap == Intl::PRIMARY)
726 if (intl_->keymap == Intl::SECONDARY)
731 intl_->getTransManager().translateAndInsert(c, t, cur);
735 int BufferView::workWidth() const
741 void BufferView::updateOffsetRef()
743 // No need to update offset_ref_ in this case.
744 if (!need_centering_)
747 // We are not properly started yet, delay until resizing is
752 CursorSlice & bot = cursor_.bottom();
753 TextMetrics & tm = text_metrics_[bot.text()];
754 ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
755 int y = coordOffset(cursor_, cursor_.boundary()).y_;
756 offset_ref_ = y + pm.ascent() - height_ / 2;
758 need_centering_ = false;
762 void BufferView::center()
764 anchor_ref_ = cursor_.bottom().pit();
765 need_centering_ = true;
769 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
773 Cursor & cur = cursor_;
775 switch (cmd.action) {
778 flag.enabled(!buffer_.undostack().empty());
781 flag.enabled(!buffer_.redostack().empty());
783 case LFUN_FILE_INSERT:
784 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
785 case LFUN_FILE_INSERT_PLAINTEXT:
786 case LFUN_BOOKMARK_SAVE:
787 // FIXME: Actually, these LFUNS should be moved to Text
788 flag.enabled(cur.inTexted());
790 case LFUN_FONT_STATE:
791 case LFUN_LABEL_INSERT:
792 case LFUN_PARAGRAPH_GOTO:
793 // FIXME handle non-trivially
794 case LFUN_OUTLINE_UP:
795 case LFUN_OUTLINE_DOWN:
796 case LFUN_OUTLINE_IN:
797 case LFUN_OUTLINE_OUT:
799 case LFUN_REFERENCE_NEXT:
801 case LFUN_WORD_REPLACE:
804 case LFUN_MARK_TOGGLE:
805 case LFUN_SCREEN_RECENTER:
806 case LFUN_BIBTEX_DATABASE_ADD:
807 case LFUN_BIBTEX_DATABASE_DEL:
808 case LFUN_WORDS_COUNT:
809 case LFUN_NEXT_INSET_TOGGLE:
813 case LFUN_LABEL_GOTO: {
814 flag.enabled(!cmd.argument().empty()
815 || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
819 case LFUN_CHANGES_TRACK:
821 flag.setOnOff(buffer_.params().trackChanges);
824 case LFUN_CHANGES_OUTPUT:
826 flag.setOnOff(buffer_.params().outputChanges);
829 case LFUN_CHANGES_MERGE:
830 case LFUN_CHANGE_NEXT:
831 case LFUN_ALL_CHANGES_ACCEPT:
832 case LFUN_ALL_CHANGES_REJECT:
833 // TODO: context-sensitive enabling of LFUNs
834 // In principle, these command should only be enabled if there
835 // is a change in the document. However, without proper
836 // optimizations, this will inevitably result in poor performance.
840 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
841 flag.setOnOff(buffer_.params().compressed);
846 case LFUN_SCREEN_DOWN:
850 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
851 // everywhere else before this can enabled:
852 case LFUN_SCREEN_UP_SELECT:
853 case LFUN_SCREEN_DOWN_SELECT:
865 Update::flags BufferView::dispatch(FuncRequest const & cmd)
867 //lyxerr << BOOST_CURRENT_FUNCTION
868 // << [ cmd = " << cmd << "]" << endl;
870 // Make sure that the cached BufferView is correct.
871 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
872 << " action[" << cmd.action << ']'
873 << " arg[" << to_utf8(cmd.argument()) << ']'
874 << " x[" << cmd.x << ']'
875 << " y[" << cmd.y << ']'
876 << " button[" << cmd.button() << ']'
879 Cursor & cur = cursor_;
880 // Default Update flags.
881 Update::flags updateFlags = Update::Force | Update::FitCursor;
883 switch (cmd.action) {
886 cur.message(_("Undo"));
887 cur.clearSelection();
888 if (!textUndo(*this)) {
889 cur.message(_("No further undo information"));
890 updateFlags = Update::None;
895 cur.message(_("Redo"));
896 cur.clearSelection();
897 if (!textRedo(*this)) {
898 cur.message(_("No further redo information"));
899 updateFlags = Update::None;
903 case LFUN_FILE_INSERT:
905 menuInsertLyXFile(to_utf8(cmd.argument()));
908 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
910 insertPlaintextFile(to_utf8(cmd.argument()), true);
913 case LFUN_FILE_INSERT_PLAINTEXT:
915 insertPlaintextFile(to_utf8(cmd.argument()), false);
918 case LFUN_FONT_STATE:
919 cur.message(cur.currentState());
922 case LFUN_BOOKMARK_SAVE:
923 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
926 case LFUN_LABEL_GOTO: {
927 docstring label = cmd.argument();
930 getInsetByCode<InsetRef>(cursor_,
933 label = inset->getParam("reference");
934 // persistent=false: use temp_bookmark
944 case LFUN_PARAGRAPH_GOTO: {
945 int const id = convert<int>(to_utf8(cmd.argument()));
947 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
948 b = theBufferList().next(b)) {
950 ParIterator par = b->getParFromID(id);
951 if (par == b->par_iterator_end()) {
953 << "No matching paragraph found! ["
954 << id << "]." << endl;
957 << "Paragraph " << par->id()
958 << " found in buffer `"
959 << b->fileName() << "'." << endl;
963 setCursor(makeDocIterator(par, 0));
965 // Switch to other buffer view and resend cmd
966 theLyXFunc().dispatch(FuncRequest(
967 LFUN_BUFFER_SWITCH, b->fileName()));
968 theLyXFunc().dispatch(cmd);
969 updateFlags = Update::None;
978 case LFUN_OUTLINE_UP:
979 outline(OutlineUp, cursor_);
980 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
981 updateLabels(buffer_);
983 case LFUN_OUTLINE_DOWN:
984 outline(OutlineDown, cursor_);
985 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
986 updateLabels(buffer_);
988 case LFUN_OUTLINE_IN:
989 outline(OutlineIn, cursor_);
990 updateLabels(buffer_);
992 case LFUN_OUTLINE_OUT:
993 outline(OutlineOut, cursor_);
994 updateLabels(buffer_);
998 gotoInset(this, Inset::NOTE_CODE, false);
1001 case LFUN_REFERENCE_NEXT: {
1002 vector<Inset_code> tmp;
1003 tmp.push_back(Inset::LABEL_CODE);
1004 tmp.push_back(Inset::REF_CODE);
1005 gotoInset(this, tmp, true);
1009 case LFUN_CHANGES_TRACK:
1010 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1013 case LFUN_CHANGES_OUTPUT:
1014 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1015 if (buffer_.params().outputChanges) {
1016 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1017 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1018 LaTeXFeatures::isAvailable("xcolor");
1020 if (!dvipost && !xcolorsoul) {
1021 Alert::warning(_("Changes not shown in LaTeX output"),
1022 _("Changes will not be highlighted in LaTeX output, "
1023 "because neither dvipost nor xcolor/soul are installed.\n"
1024 "Please install these packages or redefine "
1025 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1026 } else if (!xcolorsoul) {
1027 Alert::warning(_("Changes not shown in LaTeX output"),
1028 _("Changes will not be highlighted in LaTeX output "
1029 "when using pdflatex, because xcolor and soul are not installed.\n"
1030 "Please install both packages or redefine "
1031 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1036 case LFUN_CHANGE_NEXT:
1037 findNextChange(this);
1040 case LFUN_CHANGES_MERGE:
1041 if (findNextChange(this))
1042 showDialog("changes");
1045 case LFUN_ALL_CHANGES_ACCEPT:
1046 // select complete document
1047 cursor_.reset(buffer_.inset());
1048 cursor_.selHandle(true);
1049 buffer_.text().cursorBottom(cursor_);
1050 // accept everything in a single step to support atomic undo
1051 buffer_.text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
1054 case LFUN_ALL_CHANGES_REJECT:
1055 // select complete document
1056 cursor_.reset(buffer_.inset());
1057 cursor_.selHandle(true);
1058 buffer_.text().cursorBottom(cursor_);
1059 // reject everything in a single step to support atomic undo
1060 // Note: reject does not work recursively; the user may have to repeat the operation
1061 buffer_.text().acceptOrRejectChanges(cursor_, Text::REJECT);
1064 case LFUN_WORD_FIND:
1068 case LFUN_WORD_REPLACE: {
1069 bool has_deleted = false;
1070 if (cur.selection()) {
1071 DocIterator beg = cur.selectionBegin();
1072 DocIterator end = cur.selectionEnd();
1073 if (beg.pit() == end.pit()) {
1074 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1075 if (cur.paragraph().isDeleted(p))
1080 replace(this, cmd, has_deleted);
1085 cur.clearSelection();
1087 cur.message(from_utf8(N_("Mark off")));
1091 cur.clearSelection();
1094 cur.message(from_utf8(N_("Mark on")));
1097 case LFUN_MARK_TOGGLE:
1098 cur.clearSelection();
1101 cur.message(from_utf8(N_("Mark removed")));
1104 cur.message(from_utf8(N_("Mark set")));
1109 case LFUN_SCREEN_RECENTER:
1113 case LFUN_BIBTEX_DATABASE_ADD: {
1114 Cursor tmpcur = cursor_;
1115 findInset(tmpcur, Inset::BIBTEX_CODE, false);
1116 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1117 Inset::BIBTEX_CODE);
1119 if (inset->addDatabase(to_utf8(cmd.argument())))
1120 buffer_.updateBibfilesCache();
1125 case LFUN_BIBTEX_DATABASE_DEL: {
1126 Cursor tmpcur = cursor_;
1127 findInset(tmpcur, Inset::BIBTEX_CODE, false);
1128 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1129 Inset::BIBTEX_CODE);
1131 if (inset->delDatabase(to_utf8(cmd.argument())))
1132 buffer_.updateBibfilesCache();
1137 case LFUN_WORDS_COUNT: {
1138 DocIterator from, to;
1139 if (cur.selection()) {
1140 from = cur.selectionBegin();
1141 to = cur.selectionEnd();
1143 from = doc_iterator_begin(buffer_.inset());
1144 to = doc_iterator_end(buffer_.inset());
1146 int const count = countWords(from, to);
1149 if (cur.selection())
1150 message = bformat(_("%1$d words in selection."),
1153 message = bformat(_("%1$d words in document."),
1157 if (cur.selection())
1158 message = _("One word in selection.");
1160 message = _("One word in document.");
1163 Alert::information(_("Count words"), message);
1167 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1168 // turn compression on/off
1169 buffer_.params().compressed = !buffer_.params().compressed;
1172 case LFUN_NEXT_INSET_TOGGLE: {
1173 // this is the real function we want to invoke
1174 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1175 // if there is an inset at cursor, see whether it
1177 Inset * inset = cur.nextInset();
1179 if (inset->isActive()) {
1180 Cursor tmpcur = cur;
1181 tmpcur.pushLeft(*inset);
1182 inset->dispatch(tmpcur, tmpcmd);
1183 if (tmpcur.result().dispatched()) {
1186 } else if (inset->editable() == Inset::IS_EDITABLE) {
1187 inset->edit(cur, true);
1190 // if it did not work, try the underlying inset.
1191 if (!cur.result().dispatched())
1192 cur.dispatch(tmpcmd);
1194 if (cur.result().dispatched())
1195 cur.clearSelection();
1200 case LFUN_SCREEN_UP:
1201 case LFUN_SCREEN_DOWN: {
1202 Point p = getPos(cur, cur.boundary());
1203 if (p.y_ < 0 || p.y_ > height_) {
1204 // The cursor is off-screen so recenter before proceeding.
1206 updateMetrics(false);
1207 //FIXME: updateMetrics() does not update paragraph position
1208 // This is done at draw() time. So we need a redraw!
1210 p = getPos(cur, cur.boundary());
1212 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1213 cur.reset(buffer_.inset());
1214 text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1215 //FIXME: what to do with cur.x_target()?
1217 // The metrics are already up to date. see scroll()
1218 updateFlags = Update::None;
1222 case LFUN_SCREEN_UP_SELECT:
1223 case LFUN_SCREEN_DOWN_SELECT: {
1224 cur.selHandle(true);
1225 size_t initial_depth = cur.depth();
1226 Point const p = getPos(cur, cur.boundary());
1227 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1228 // FIXME: We need to verify if the cursor stayed within an inset...
1229 //cur.reset(buffer_.inset());
1230 text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1232 while (cur.depth() > initial_depth) {
1235 // FIXME: we need to do a redraw again because of the selection
1237 updateFlags = Update::Force | Update::FitCursor;
1242 updateFlags = Update::None;
1249 docstring const BufferView::requestSelection()
1251 Cursor & cur = cursor_;
1253 if (!cur.selection()) {
1254 xsel_cache_.set = false;
1258 if (!xsel_cache_.set ||
1259 cur.top() != xsel_cache_.cursor ||
1260 cur.anchor_.top() != xsel_cache_.anchor)
1262 xsel_cache_.cursor = cur.top();
1263 xsel_cache_.anchor = cur.anchor_.top();
1264 xsel_cache_.set = cur.selection();
1265 return cur.selectionAsString(false);
1271 void BufferView::clearSelection()
1273 cursor_.clearSelection();
1274 // Clear the selection buffer. Otherwise a subsequent
1275 // middle-mouse-button paste would use the selection buffer,
1276 // not the more current external selection.
1277 cap::clearSelection();
1278 xsel_cache_.set = false;
1279 // The buffer did not really change, but this causes the
1280 // redraw we need because we cleared the selection above.
1285 void BufferView::resize(int width, int height)
1287 // Update from work area
1291 updateMetrics(false);
1295 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1297 TextMetrics & tm = text_metrics_[&text];
1298 Inset * inset = tm.checkInsetHit(x, y);
1302 if (!inset->descendable())
1303 // No need to go further down if the inset is not
1307 size_t cell_number = inset->nargs();
1308 // Check all the inner cell.
1309 for (size_t i = 0; i != cell_number; ++i) {
1310 Text const * inner_text = inset->getText(i);
1313 Inset const * inset_deeper =
1314 getCoveringInset(*inner_text, x, y);
1316 return inset_deeper;
1324 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1326 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1328 // This is only called for mouse related events including
1329 // LFUN_FILE_OPEN generated by drag-and-drop.
1330 FuncRequest cmd = cmd0;
1333 cur.push(buffer_.inset());
1334 cur.selection() = cursor_.selection();
1336 // Either the inset under the cursor or the
1337 // surrounding Text will handle this event.
1339 // make sure we stay within the screen...
1340 cmd.y = min(max(cmd.y, -1), height_);
1342 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1344 // Get inset under mouse, if there is one.
1345 Inset const * covering_inset =
1346 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1347 if (covering_inset == last_inset_)
1348 // Same inset, no need to do anything...
1351 bool need_redraw = false;
1352 // const_cast because of setMouseHover().
1353 Inset * inset = const_cast<Inset *>(covering_inset);
1355 // Remove the hint on the last hovered inset (if any).
1356 need_redraw |= last_inset_->setMouseHover(false);
1358 // Highlighted the newly hovered inset (if any).
1359 need_redraw |= inset->setMouseHover(true);
1360 last_inset_ = inset;
1364 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1365 // not expose the button for redraw. We adjust here the metrics dimension
1366 // to enable a full redraw in any case as this is not costly.
1367 TextMetrics & tm = text_metrics_[&buffer_.text()];
1368 std::pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1369 std::pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1370 int y1 = firstpm.second->position() - firstpm.second->ascent();
1371 int y2 = lastpm.second->position() + lastpm.second->descent();
1372 metrics_info_ = ViewMetricsInfo(firstpm.first, lastpm.first, y1, y2,
1373 FullScreenUpdate, buffer_.text().paragraphs().size());
1374 // Reinitialize anchor to first pit.
1375 anchor_ref_ = firstpm.first;
1377 LYXERR(Debug::PAINTING)
1378 << "Mouse hover detected at: (" << cmd.x << ", " << cmd.y << ")"
1379 << "\nTriggering redraw: y1: " << y1 << " y2: " << y2
1380 << " pit1: " << firstpm.first << " pit2: " << lastpm.first << endl;
1382 // This event (moving without mouse click) is not passed further.
1383 // This should be changed if it is further utilized.
1388 // Build temporary cursor.
1389 Inset * inset = text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1391 // Put anchor at the same position.
1394 // Try to dispatch to an non-editable inset near this position
1395 // via the temp cursor. If the inset wishes to change the real
1396 // cursor it has to do so explicitly by using
1397 // cur.bv().cursor() = cur; (or similar)
1399 inset->dispatch(cur, cmd);
1401 // Now dispatch to the temporary cursor. If the real cursor should
1402 // be modified, the inset's dispatch has to do so explicitly.
1403 if (!cur.result().dispatched())
1406 //Do we have a selection?
1407 theSelection().haveSelection(cursor().selection());
1409 // If the command has been dispatched,
1410 if (cur.result().dispatched()
1411 // an update is asked,
1412 && cur.result().update())
1413 processUpdateFlags(cur.result().update());
1417 void BufferView::scroll(int y)
1426 void BufferView::scrollDown(int offset)
1428 Text * text = &buffer_.text();
1429 TextMetrics & tm = text_metrics_[text];
1430 int ymax = height_ + offset;
1432 std::pair<pit_type, ParagraphMetrics const *> last = tm.last();
1433 int bottom_pos = last.second->position() + last.second->descent();
1434 if (last.first + 1 == int(text->paragraphs().size())) {
1435 if (bottom_pos <= height_)
1437 offset = min(offset, bottom_pos - height_);
1440 if (bottom_pos > ymax)
1442 tm.newParMetricsDown();
1444 offset_ref_ += offset;
1445 updateMetrics(false);
1450 void BufferView::scrollUp(int offset)
1452 Text * text = &buffer_.text();
1453 TextMetrics & tm = text_metrics_[text];
1454 int ymin = - offset;
1456 std::pair<pit_type, ParagraphMetrics const *> first = tm.first();
1457 int top_pos = first.second->position() - first.second->ascent();
1458 if (first.first == 0) {
1461 offset = min(offset, - top_pos);
1466 tm.newParMetricsUp();
1468 offset_ref_ -= offset;
1469 updateMetrics(false);
1474 void BufferView::setCursorFromRow(int row)
1479 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1481 cursor_.reset(buffer_.inset());
1483 buffer_.text().setCursor(cursor_, 0, 0);
1485 buffer_.text().setCursor(cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1489 void BufferView::gotoLabel(docstring const & label)
1491 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1492 vector<docstring> labels;
1493 it->getLabelList(buffer_, labels);
1494 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1496 processUpdateFlags(Update::FitCursor);
1503 TextMetrics const & BufferView::textMetrics(Text const * t) const
1505 return const_cast<BufferView *>(this)->textMetrics(t);
1509 TextMetrics & BufferView::textMetrics(Text const * t)
1511 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1512 if (tmc_it == text_metrics_.end()) {
1513 tmc_it = text_metrics_.insert(
1514 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1516 return tmc_it->second;
1520 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1523 return textMetrics(t).parMetrics(pit);
1527 int BufferView::workHeight() const
1533 void BufferView::setCursor(DocIterator const & dit)
1535 size_t const n = dit.depth();
1536 for (size_t i = 0; i < n; ++i)
1537 dit[i].inset().edit(cursor_, true);
1539 cursor_.setCursor(dit);
1540 cursor_.selection() = false;
1544 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1546 // Would be wrong to delete anything if we have a selection.
1547 if (cur.selection())
1550 bool need_anchor_change = false;
1551 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1552 need_anchor_change);
1554 if (need_anchor_change)
1560 updateLabels(buffer_);
1562 updateMetrics(false);
1568 bool BufferView::mouseSetCursor(Cursor & cur)
1570 BOOST_ASSERT(&cur.bv() == this);
1572 // this event will clear selection so we save selection for
1573 // persistent selection
1574 cap::saveSelection(cursor());
1576 // Has the cursor just left the inset?
1577 bool badcursor = false;
1578 bool leftinset = (&cursor_.inset() != &cur.inset());
1580 badcursor = notifyCursorLeaves(cursor_, cur);
1582 // do the dEPM magic if needed
1583 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1584 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1585 // the leftinset bool would not be necessary (badcursor instead).
1586 bool update = leftinset;
1587 if (!badcursor && cursor_.inTexted())
1588 update |= checkDepm(cur, cursor_);
1590 // if the cursor was in an empty script inset and the new
1591 // position is in the nucleus of the inset, notifyCursorLeaves
1592 // will kill the script inset itself. So we check all the
1593 // elements of the cursor to make sure that they are correct.
1594 // For an example, see bug 2933:
1595 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1596 // The code below could maybe be moved to a DocIterator method.
1597 //lyxerr << "cur before " << cur <<std::endl;
1598 DocIterator dit(cur.inset());
1599 dit.push_back(cur.bottom());
1601 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1602 dit.push_back(cur[i]);
1605 //lyxerr << "5 cur after" << dit <<std::endl;
1607 cursor_.setCursor(dit);
1608 cursor_.boundary(cur.boundary());
1609 cursor_.clearSelection();
1615 void BufferView::putSelectionAt(DocIterator const & cur,
1616 int length, bool backwards)
1618 cursor_.clearSelection();
1624 cursor_.pos() += length;
1625 cursor_.setSelection(cursor_, -length);
1627 cursor_.setSelection(cursor_, length);
1632 Cursor & BufferView::cursor()
1638 Cursor const & BufferView::cursor() const
1644 pit_type BufferView::anchor_ref() const
1650 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1652 return metrics_info_;
1656 bool BufferView::singleParUpdate()
1658 Text & buftext = buffer_.text();
1659 pit_type const bottom_pit = cursor_.bottom().pit();
1660 TextMetrics & tm = textMetrics(&buftext);
1661 int old_height = tm.parMetrics(bottom_pit).height();
1663 // In Single Paragraph mode, rebreak only
1664 // the (main text, not inset!) paragraph containing the cursor.
1665 // (if this paragraph contains insets etc., rebreaking will
1666 // recursively descend)
1667 tm.redoParagraph(bottom_pit);
1668 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1669 if (pm.height() != old_height)
1670 // Paragraph height has changed so we cannot proceed to
1671 // the singlePar optimisation.
1674 int y1 = pm.position() - pm.ascent();
1675 int y2 = pm.position() + pm.descent();
1676 metrics_info_ = ViewMetricsInfo(bottom_pit, bottom_pit, y1, y2,
1677 SingleParUpdate, buftext.paragraphs().size());
1678 LYXERR(Debug::PAINTING)
1679 << BOOST_CURRENT_FUNCTION
1682 << " pit: " << bottom_pit
1689 void BufferView::updateMetrics(bool singlepar)
1691 if (singlepar && singleParUpdate())
1692 // No need to update the full screen metrics.
1695 Text & buftext = buffer_.text();
1696 pit_type const npit = int(buftext.paragraphs().size());
1698 if (anchor_ref_ > int(npit - 1)) {
1699 anchor_ref_ = int(npit - 1);
1703 // Clear out the position cache in case of full screen redraw,
1704 coord_cache_.clear();
1706 // Clear out paragraph metrics to avoid having invalid metrics
1707 // in the cache from paragraphs not relayouted below
1708 // The complete text metrics will be redone.
1709 text_metrics_.clear();
1711 TextMetrics & tm = textMetrics(&buftext);
1713 pit_type const pit = anchor_ref_;
1717 // Rebreak anchor paragraph.
1718 tm.redoParagraph(pit);
1720 // Take care of anchor offset if case a recentering is needed.
1723 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1725 // Redo paragraphs above anchor if necessary.
1727 while (y1 > 0 && pit1 > 0) {
1728 y1 -= tm.parMetrics(pit1).ascent();
1730 tm.redoParagraph(pit1);
1731 y1 -= tm.parMetrics(pit1).descent();
1734 // Take care of ascent of first line
1735 y1 -= tm.parMetrics(pit1).ascent();
1737 // Normalize anchor for next time
1741 // Grey at the beginning is ugly
1742 if (pit1 == 0 && y1 > 0) {
1748 // Redo paragraphs below the anchor if necessary.
1750 while (y2 < height_ && pit2 < int(npit) - 1) {
1751 y2 += tm.parMetrics(pit2).descent();
1753 tm.redoParagraph(pit2);
1754 y2 += tm.parMetrics(pit2).ascent();
1757 // Take care of descent of last line
1758 y2 += tm.parMetrics(pit2).descent();
1760 LYXERR(Debug::PAINTING)
1761 << BOOST_CURRENT_FUNCTION
1764 << " pit1: " << pit1
1765 << " pit2: " << pit2
1766 << " npit: " << npit
1770 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1771 FullScreenUpdate, npit);
1773 if (lyxerr.debugging(Debug::WORKAREA)) {
1774 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1775 coord_cache_.dump();
1780 void BufferView::menuInsertLyXFile(string const & filenm)
1782 BOOST_ASSERT(cursor_.inTexted());
1783 string filename = filenm;
1785 if (filename.empty()) {
1786 // Launch a file browser
1788 string initpath = lyxrc.document_path;
1789 string const trypath = buffer_.filePath();
1790 // If directory is writeable, use this as default.
1791 if (isDirWriteable(FileName(trypath)))
1795 FileDialog fileDlg(_("Select LyX document to insert"),
1797 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1798 make_pair(_("Examples|#E#e"),
1799 from_utf8(addPath(package().system_support().absFilename(),
1802 FileDialog::Result result =
1803 fileDlg.open(from_utf8(initpath),
1804 FileFilterList(_("LyX Documents (*.lyx)")),
1807 if (result.first == FileDialog::Later)
1811 filename = to_utf8(result.second);
1813 // check selected filename
1814 if (filename.empty()) {
1815 // emit message signal.
1816 message(_("Canceled."));
1821 // Get absolute path of file and add ".lyx"
1822 // to the filename if necessary
1823 filename = fileSearch(string(), filename, "lyx").absFilename();
1825 docstring const disp_fn = makeDisplayPath(filename);
1826 // emit message signal.
1827 message(bformat(_("Inserting document %1$s..."), disp_fn));
1830 Buffer buf("", false);
1831 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1832 ErrorList & el = buffer_.errorList("Parse");
1833 // Copy the inserted document error list into the current buffer one.
1834 el = buf.errorList("Parse");
1835 recordUndo(cursor_);
1836 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1837 buf.params().getTextClassPtr(), el);
1838 res = _("Document %1$s inserted.");
1840 res = _("Could not insert document %1$s");
1842 // emit message signal.
1843 message(bformat(res, disp_fn));
1844 buffer_.errors("Parse");
1845 updateMetrics(false);
1849 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1855 // Addup contribution of nested insets, from inside to outside,
1856 // keeping the outer paragraph for a special handling below
1857 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1858 CursorSlice const & sl = dit[i];
1862 // get relative position inside sl.inset()
1863 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1865 // Make relative position inside of the edited inset relative to sl.inset()
1869 // In case of an RTL inset, the edited inset will be positioned to the left
1872 bool boundary_i = boundary && i + 1 == dit.depth();
1873 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1878 // remember width for the case that sl.inset() is positioned in an RTL inset
1879 if (i && dit[i - 1].text()) {
1880 // If this Inset is inside a Text Inset, retrieve the Dimension
1881 // from the containing text instead of using Inset::dimension() which
1882 // might not be implemented.
1883 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1884 // elimination of Inset::dim_ cache. This coordOffset() method needs
1885 // to be rewritten in light of the new design.
1886 Dimension const & dim = parMetrics(dit[i - 1].text(),
1887 dit[i - 1].pit()).insetDimension(&sl.inset());
1890 Dimension const dim = sl.inset().dimension(*this);
1894 //lyxerr << "Cursor::getPos, i: "
1895 // << i << " x: " << xx << " y: " << y << endl;
1898 // Add contribution of initial rows of outermost paragraph
1899 CursorSlice const & sl = dit[0];
1900 TextMetrics const & tm = textMetrics(sl.text());
1901 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1902 BOOST_ASSERT(!pm.rows().empty());
1903 y -= pm.rows()[0].ascent();
1905 // FIXME: document this mess
1907 if (sl.pos() > 0 && dit.depth() == 1) {
1909 if (pos && boundary)
1911 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << std::endl;
1912 rend = pm.pos2row(pos);
1914 rend = pm.pos2row(sl.pos());
1916 size_t rend = pm.pos2row(sl.pos());
1918 for (size_t rit = 0; rit != rend; ++rit)
1919 y += pm.rows()[rit].height();
1920 y += pm.rows()[rend].ascent();
1922 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1924 // Make relative position from the nested inset now bufferview absolute.
1925 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1928 // In the RTL case place the nested inset at the left of the cursor in
1929 // the outer paragraph
1930 bool boundary_1 = boundary && 1 == dit.depth();
1931 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1939 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1941 CursorSlice const & bot = dit.bottom();
1942 TextMetrics const & tm = textMetrics(bot.text());
1943 if (!tm.has(bot.pit()))
1944 return Point(-1, -1);
1946 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1947 p.y_ += tm.parMetrics(bot.pit()).position();
1952 void BufferView::draw(frontend::Painter & pain)
1954 PainterInfo pi(this, pain);
1955 // Should the whole screen, including insets, be refreshed?
1956 // FIXME: We should also distinguish DecorationUpdate to avoid text
1957 // drawing if possible. This is not possible to do easily right now
1958 // because of the single backing pixmap.
1959 pi.full_repaint = metrics_info_.update_strategy != SingleParUpdate;
1961 if (pi.full_repaint)
1962 // Clear background (if not delegated to rows)
1963 pain.fillRectangle(0, metrics_info_.y1, width_,
1964 metrics_info_.y2 - metrics_info_.y1,
1965 buffer_.inset().backgroundColor());
1967 LYXERR(Debug::PAINTING) << "\t\t*** START DRAWING ***" << endl;
1968 Text & text = buffer_.text();
1969 TextMetrics const & tm = text_metrics_[&text];
1970 int y = metrics_info_.y1 + tm.parMetrics(metrics_info_.p1).ascent();
1971 if (!pi.full_repaint)
1972 tm.drawParagraph(pi, metrics_info_.p1, 0, y);
1975 LYXERR(Debug::PAINTING) << "\n\t\t*** END DRAWING ***" << endl;
1977 // and grey out above (should not happen later)
1978 // lyxerr << "par ascent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1979 if (metrics_info_.y1 > 0
1980 && metrics_info_.update_strategy == FullScreenUpdate)
1981 pain.fillRectangle(0, 0, width_, metrics_info_.y1, Color::bottomarea);
1983 // and possibly grey out below
1984 // lyxerr << "par descent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1985 if (metrics_info_.y2 < height_
1986 && metrics_info_.update_strategy == FullScreenUpdate)
1987 pain.fillRectangle(0, metrics_info_.y2, width_,
1988 height_ - metrics_info_.y2, Color::bottomarea);
1992 void BufferView::message(docstring const & msg)
1999 void BufferView::showDialog(std::string const & name)
2002 gui_->showDialog(name);
2006 void BufferView::showDialogWithData(std::string const & name,
2007 std::string const & data)
2010 gui_->showDialogWithData(name, data);
2014 void BufferView::showInsetDialog(std::string const & name,
2015 std::string const & data, Inset * inset)
2018 gui_->showInsetDialog(name, data, inset);
2022 void BufferView::updateDialog(std::string const & name, std::string const & data)
2025 gui_->updateDialog(name, data);
2029 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2035 // FIXME: Move this out of BufferView again
2036 docstring BufferView::contentsOfPlaintextFile(string const & f,
2041 if (fname.empty()) {
2042 FileDialog fileDlg(_("Select file to insert"),
2044 ? LFUN_FILE_INSERT_PLAINTEXT_PARA
2045 : LFUN_FILE_INSERT_PLAINTEXT) );
2047 FileDialog::Result result =
2048 fileDlg.open(from_utf8(buffer().filePath()),
2049 FileFilterList(), docstring());
2051 if (result.first == FileDialog::Later)
2054 fname = makeAbsPath(to_utf8(result.second));
2060 if (!fs::is_readable(fname.toFilesystemEncoding())) {
2061 docstring const error = from_ascii(strerror(errno));
2062 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2063 docstring const text =
2064 bformat(_("Could not read the specified document\n"
2065 "%1$s\ndue to the error: %2$s"), file, error);
2066 Alert::error(_("Could not read file"), text);
2070 ifstream ifs(fname.toFilesystemEncoding().c_str());
2072 docstring const error = from_ascii(strerror(errno));
2073 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2074 docstring const text =
2075 bformat(_("Could not open the specified document\n"
2076 "%1$s\ndue to the error: %2$s"), file, error);
2077 Alert::error(_("Could not open file"), text);
2081 ifs.unsetf(std::ios::skipws);
2082 istream_iterator<char> ii(ifs);
2083 istream_iterator<char> end;
2084 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
2085 // We use this until the compilers get better...
2086 std::vector<char> tmp;
2087 copy(ii, end, back_inserter(tmp));
2088 string const tmpstr(tmp.begin(), tmp.end());
2090 // This is what we want to use and what we will use once the
2091 // compilers get good enough.
2092 //string tmpstr(ii, end); // yet a reason for using std::string
2093 // alternate approach to get the file into a string:
2095 copy(ii, end, back_inserter(tmpstr));
2098 // FIXME UNICODE: We don't know the encoding of the file
2099 docstring file_content = from_utf8(tmpstr);
2100 if (file_content.empty()) {
2101 Alert::error(_("Reading not UTF-8 encoded file"),
2102 _("The file is not UTF-8 encoded.\n"
2103 "It will be read as local 8Bit-encoded.\n"
2104 "If this does not give the correct result\n"
2105 "then please change the encoding of the file\n"
2106 "to UTF-8 with a program other than LyX.\n"));
2107 file_content = from_local8bit(tmpstr);
2110 return normalize_c(file_content);
2114 void BufferView::insertPlaintextFile(string const & f, bool asParagraph)
2116 docstring const tmpstr = contentsOfPlaintextFile(f, asParagraph);
2121 Cursor & cur = cursor();
2122 cap::replaceSelection(cur);
2125 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2127 cur.innerText()->insertStringAsLines(cur, tmpstr);