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"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
35 #include "InsetIterator.h"
37 #include "LaTeXFeatures.h"
43 #include "MetricsInfo.h"
44 #include "Paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
50 #include "TextClass.h"
51 #include "TextMetrics.h"
55 #include "WordLangTuple.h"
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
63 #include "frontends/alert.h"
64 #include "frontends/Delegates.h"
65 #include "frontends/FileDialog.h"
66 #include "frontends/FontMetrics.h"
67 #include "frontends/Painter.h"
68 #include "frontends/Selection.h"
70 #include "graphics/Previews.h"
72 #include "support/convert.h"
73 #include "support/FileFilterList.h"
74 #include "support/filetools.h"
75 #include "support/Package.h"
76 #include "support/types.h"
77 #include "support/fs_extras.h"
79 #include <boost/bind.hpp>
80 #include <boost/current_function.hpp>
81 #include <boost/next_prior.hpp>
82 #include <boost/filesystem/operations.hpp>
92 using std::istringstream;
93 using std::istream_iterator;
97 using std::mem_fun_ref;
101 namespace fs = boost::filesystem;
105 using support::addPath;
106 using support::bformat;
107 using support::FileFilterList;
108 using support::FileName;
109 using support::fileSearch;
110 using support::isDirWriteable;
111 using support::isFileReadable;
112 using support::makeDisplayPath;
113 using support::makeAbsPath;
114 using support::package;
116 namespace Alert = frontend::Alert;
120 /// Return an inset of this class if it exists at the current cursor position
122 T * getInsetByCode(Cursor const & cur, Inset::Code code)
124 DocIterator it = cur;
125 Inset * inset = it.nextInset();
126 if (inset && inset->lyxCode() == code)
127 return static_cast<T*>(inset);
132 bool findInset(DocIterator & dit, vector<Inset_code> const & codes,
135 bool findNextInset(DocIterator & dit, vector<Inset_code> const & codes,
136 string const & contents)
138 DocIterator tmpdit = dit;
141 Inset const * inset = tmpdit.nextInset();
143 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
144 && (contents.empty() ||
145 static_cast<InsetCommand const *>(inset)->getContents() == contents)) {
149 tmpdit.forwardInset();
156 /// Looks for next inset with one of the the given code
157 bool findInset(DocIterator & dit, vector<Inset_code> const & codes,
161 DocIterator tmpdit = dit;
162 tmpdit.forwardInset();
167 Inset const * inset = tmpdit.nextInset();
169 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
170 contents = static_cast<InsetCommand const *>(inset)->getContents();
174 if (!findNextInset(tmpdit, codes, contents)) {
175 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
176 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
177 if (!findNextInset(tmpdit, codes, contents))
188 /// Looks for next inset with the given code
189 void findInset(DocIterator & dit, Inset_code code, bool same_content)
191 findInset(dit, vector<Inset_code>(1, code), same_content);
195 /// Moves cursor to the next inset with one of the given codes.
196 void gotoInset(BufferView * bv, vector<Inset_code> const & codes,
199 Cursor tmpcur = bv->cursor();
200 if (!findInset(tmpcur, codes, same_content)) {
201 bv->cursor().message(_("No more insets"));
205 tmpcur.clearSelection();
206 bv->setCursor(tmpcur);
210 /// Moves cursor to the next inset with given code.
211 void gotoInset(BufferView * bv, Inset_code code, bool same_content)
213 gotoInset(bv, vector<Inset_code>(1, code), same_content);
218 /// the type of outline operation
220 OutlineUp, // Move this header with text down
221 OutlineDown, // Move this header with text up
222 OutlineIn, // Make this header deeper
223 OutlineOut // Make this header shallower
227 void outline(OutlineOp mode, Cursor & cur)
229 Buffer & buf = cur.buffer();
230 pit_type & pit = cur.pit();
231 ParagraphList & pars = buf.text().paragraphs();
232 ParagraphList::iterator bgn = pars.begin();
233 // The first paragraph of the area to be copied:
234 ParagraphList::iterator start = boost::next(bgn, pit);
235 // The final paragraph of area to be copied:
236 ParagraphList::iterator finish = start;
237 ParagraphList::iterator end = pars.end();
239 TextClass::const_iterator lit =
240 buf.params().getTextClass().begin();
241 TextClass::const_iterator const lend =
242 buf.params().getTextClass().end();
244 int const thistoclevel = start->layout()->toclevel;
248 // Move out (down) from this section header
251 // Seek the one (on same level) below
252 for (; finish != end; ++finish) {
253 toclevel = finish->layout()->toclevel;
254 if (toclevel != Layout::NOT_IN_TOC
255 && toclevel <= thistoclevel) {
259 ParagraphList::iterator dest = start;
260 // Move out (up) from this header
263 // Search previous same-level header above
266 toclevel = dest->layout()->toclevel;
268 && (toclevel == Layout::NOT_IN_TOC
269 || toclevel > thistoclevel));
270 // Not found; do nothing
271 if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
273 pit_type const newpit = std::distance(bgn, dest);
274 pit_type const len = std::distance(start, finish);
275 pit_type const deletepit = pit + len;
276 recordUndo(cur, Undo::ATOMIC, newpit, deletepit - 1);
277 pars.insert(dest, start, finish);
278 start = boost::next(pars.begin(), deletepit);
280 pars.erase(start, finish);
284 // Go down out of current header:
287 // Find next same-level header:
288 for (; finish != end; ++finish) {
289 toclevel = finish->layout()->toclevel;
290 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
293 ParagraphList::iterator dest = finish;
294 // Go one down from *this* header:
299 // Go further down to find header to insert in front of:
300 for (; dest != end; ++dest) {
301 toclevel = dest->layout()->toclevel;
302 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
305 // One such was found:
306 pit_type newpit = std::distance(bgn, dest);
307 pit_type const len = std::distance(start, finish);
308 recordUndo(cur, Undo::ATOMIC, pit, newpit - 1);
309 pars.insert(dest, start, finish);
310 start = boost::next(bgn, pit);
312 pars.erase(start, finish);
317 for (; lit != lend; ++lit) {
318 if ((*lit)->toclevel == thistoclevel + 1 &&
319 start->layout()->labeltype == (*lit)->labeltype) {
320 start->layout((*lit));
327 for (; lit != lend; ++lit) {
328 if ((*lit)->toclevel == thistoclevel - 1 &&
329 start->layout()->labeltype == (*lit)->labeltype) {
330 start->layout((*lit));
340 /// A map from a Text to the associated text metrics
341 typedef std::map<Text const *, TextMetrics> TextMetricsCache;
346 /////////////////////////////////////////////////////////////////////
350 /////////////////////////////////////////////////////////////////////
352 struct BufferView::BufferViewPrivate
354 BufferViewPrivate(BufferView & bv): wh_(0), cursor_(bv),
355 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
356 need_centering_(false), last_inset_(0), gui_(0)
360 ScrollbarParameters scrollbarParameters_;
362 ViewMetricsInfo metrics_info_;
364 CoordCache coord_cache_;
366 /// Estimated average par height for scrollbar.
368 /// this is used to handle XSelection events in the right manner.
377 bool multiparsel_cache_;
379 pit_type anchor_ref_;
383 bool need_centering_;
385 /// keyboard mapping object.
388 /// last visited inset.
389 /** kept to send setMouseHover(false).
390 * Not owned, so don't delete.
394 mutable TextMetricsCache text_metrics_;
397 /** Not owned, so don't delete.
399 frontend::GuiBufferViewDelegate * gui_;
403 BufferView::BufferView(Buffer & buf)
404 : width_(0), height_(0), buffer_(buf), d(*new BufferViewPrivate(*this))
406 d.xsel_cache_.set = false;
407 d.intl_.initKeyMapper(lyxrc.use_kbmap);
409 d.cursor_.push(buffer_.inset());
410 d.cursor_.resetAnchor();
411 d.cursor_.setCurrentFont();
413 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
414 graphics::Previews::get().generateBufferPreviews(buffer_);
418 BufferView::~BufferView()
420 // current buffer is going to be switched-off, save cursor pos
421 // Ideally, the whole cursor stack should be saved, but session
422 // currently can only handle bottom (whole document) level pit and pos.
423 // That is to say, if a cursor is in a nested inset, it will be
424 // restore to the left of the top level inset.
425 LyX::ref().session().lastFilePos().save(
426 support::FileName(buffer_.fileName()),
427 boost::tie(d.cursor_.bottom().pit(), d.cursor_.bottom().pos()) );
433 Intl & BufferView::getIntl()
439 Intl const & BufferView::getIntl() const
445 CoordCache & BufferView::coordCache()
447 return d.coord_cache_;
451 CoordCache const & BufferView::coordCache() const
453 return d.coord_cache_;
457 Buffer & BufferView::buffer()
463 Buffer const & BufferView::buffer() const
469 bool BufferView::fitCursor()
471 if (cursorStatus(d.cursor_) == CUR_INSIDE) {
472 frontend::FontMetrics const & fm =
473 theFontMetrics(d.cursor_.getFont());
474 int const asc = fm.maxAscent();
475 int const des = fm.maxDescent();
476 Point const p = getPos(d.cursor_, d.cursor_.boundary());
477 if (p.y_ - asc >= 0 && p.y_ + des < height_)
485 bool BufferView::multiParSel()
487 if (!d.cursor_.selection())
489 bool ret = d.multiparsel_cache_;
490 d.multiparsel_cache_ = d.cursor_.selBegin().pit() != d.cursor_.selEnd().pit();
491 // Either this, or previous selection spans paragraphs
492 return ret || d.multiparsel_cache_;
496 void BufferView::processUpdateFlags(Update::flags flags)
498 // last_inset_ points to the last visited inset. This pointer may become
499 // invalid because of keyboard editing. Since all such operations
500 // causes screen update(), I reset last_inset_ to avoid such a problem.
502 // This is close to a hot-path.
504 << BOOST_CURRENT_FUNCTION
505 << "[fitcursor = " << (flags & Update::FitCursor)
506 << ", forceupdate = " << (flags & Update::Force)
507 << ", singlepar = " << (flags & Update::SinglePar)
508 << "] buffer: " << &buffer_ << endl;
510 // Update macro store
511 if (!(cursor().inMathed() && cursor().inMacroMode()))
512 buffer_.buildMacros();
514 // Now do the first drawing step if needed. This consists on updating
515 // the CoordCache in updateMetrics().
516 // The second drawing step is done in WorkArea::redraw() if needed.
518 // Case when no explicit update is requested.
520 // no need to redraw anything.
521 d.metrics_info_.update_strategy = NoScreenUpdate;
525 if (flags == Update::Decoration) {
526 d.metrics_info_.update_strategy = DecorationUpdate;
531 if (flags == Update::FitCursor
532 || flags == (Update::Decoration | Update::FitCursor)) {
533 bool const fit_cursor = fitCursor();
534 // tell the frontend to update the screen if needed.
536 updateMetrics(false);
540 if (flags & Update::Decoration) {
541 d.metrics_info_.update_strategy = DecorationUpdate;
545 // no screen update is needed.
546 d.metrics_info_.update_strategy = NoScreenUpdate;
550 bool full_metrics = flags & Update::Force;
551 if (flags & Update::MultiParSel)
552 full_metrics |= multiParSel();
554 bool const single_par = !full_metrics;
555 updateMetrics(single_par);
557 if (!(flags & Update::FitCursor)) {
562 //FIXME: updateMetrics() does not update paragraph position
563 // This is done at draw() time. So we need a redraw!
566 // The screen has already been updated thanks to the
567 // 'buffer_.changed()' call three line above. So no need
571 // The screen has been recentered around the cursor position so
573 updateMetrics(false);
578 void BufferView::updateScrollbar()
580 Text & t = buffer_.text();
581 TextMetrics & tm = d.text_metrics_[&t];
583 int const parsize = int(t.paragraphs().size() - 1);
584 if (d.anchor_ref_ > parsize) {
585 d.anchor_ref_ = parsize;
590 << BOOST_CURRENT_FUNCTION
591 << " Updating scrollbar: height: " << t.paragraphs().size()
592 << " curr par: " << d.cursor_.bottom().pit()
593 << " default height " << defaultRowHeight() << endl;
595 // It would be better to fix the scrollbar to understand
596 // values in [0..1] and divide everything by wh
598 // estimated average paragraph height:
602 int h = tm.parMetrics(d.anchor_ref_).height();
604 // Normalize anchor/offset (MV):
605 while (d.offset_ref_ > h && d.anchor_ref_ < parsize) {
608 h = tm.parMetrics(d.anchor_ref_).height();
610 // Look at paragraph heights on-screen
613 for (pit_type pit = d.anchor_ref_; pit <= parsize; ++pit) {
616 int const h2 = tm.parMetrics(pit).height();
622 int const hav = sumh / nh;
623 // More realistic average paragraph height
628 d.scrollbarParameters_.height = (parsize + 1) * d.wh_;
629 d.scrollbarParameters_.position = d.anchor_ref_ * d.wh_ + int(d.offset_ref_ * d.wh_ / float(h));
630 d.scrollbarParameters_.lineScrollHeight = int(d.wh_ * defaultRowHeight() / float(h));
634 ScrollbarParameters const & BufferView::scrollbarParameters() const
636 return d.scrollbarParameters_;
640 void BufferView::scrollDocView(int value)
642 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
643 << "[ value = " << value << "]" << endl;
645 Text & t = buffer_.text();
646 TextMetrics & tm = d.text_metrics_[&t];
648 float const bar = value / float(d.wh_ * t.paragraphs().size());
650 d.anchor_ref_ = int(bar * t.paragraphs().size());
651 if (d.anchor_ref_ > int(t.paragraphs().size()) - 1)
652 d.anchor_ref_ = int(t.paragraphs().size()) - 1;
654 tm.redoParagraph(d.anchor_ref_);
655 int const h = tm.parMetrics(d.anchor_ref_).height();
656 d.offset_ref_ = int((bar * t.paragraphs().size() - d.anchor_ref_) * h);
657 updateMetrics(false);
662 void BufferView::setCursorFromScrollbar()
664 TextMetrics & tm = d.text_metrics_[&buffer_.text()];
666 int const height = 2 * defaultRowHeight();
667 int const first = height;
668 int const last = height_ - height;
669 Cursor & cur = d.cursor_;
671 switch (cursorStatus(cur)) {
673 // We reset the cursor because cursorStatus() does not
674 // work when the cursor is within mathed.
675 cur.reset(buffer_.inset());
676 tm.setCursorFromCoordinates(cur, 0, first);
677 cur.clearSelection();
680 // We reset the cursor because cursorStatus() does not
681 // work when the cursor is within mathed.
682 cur.reset(buffer_.inset());
683 tm.setCursorFromCoordinates(cur, 0, last);
684 cur.clearSelection();
687 int const y = getPos(cur, cur.boundary()).y_;
688 int const newy = min(last, max(y, first));
690 cur.reset(buffer_.inset());
691 tm.setCursorFromCoordinates(cur, 0, newy);
697 Change const BufferView::getCurrentChange() const
699 if (!d.cursor_.selection())
700 return Change(Change::UNCHANGED);
702 DocIterator dit = d.cursor_.selectionBegin();
703 return dit.paragraph().lookupChange(dit.pos());
707 // this could be used elsewhere as well?
708 // FIXME: This does not work within mathed!
709 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
711 Point const p = getPos(dit, dit.boundary());
714 if (p.y_ > workHeight())
720 void BufferView::saveBookmark(unsigned int idx)
722 // tenatively save bookmark, id and pos will be used to
723 // acturately locate a bookmark in a 'live' lyx session.
724 // pit and pos will be updated with bottom level pit/pos
726 LyX::ref().session().bookmarks().save(
727 FileName(buffer_.fileName()),
728 d.cursor_.bottom().pit(),
729 d.cursor_.bottom().pos(),
730 d.cursor_.paragraph().id(),
735 // emit message signal.
736 message(_("Save bookmark"));
740 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
741 int top_id, pos_type top_pos)
743 bool success = false;
746 d.cursor_.clearSelection();
748 // if a valid par_id is given, try it first
749 // This is the case for a 'live' bookmark when unique paragraph ID
750 // is used to track bookmarks.
752 ParIterator par = buffer_.getParFromID(top_id);
753 if (par != buffer_.par_iterator_end()) {
754 doc_it = makeDocIterator(par, min(par->size(), top_pos));
755 // Some slices of the iterator may not be
756 // reachable (e.g. closed collapsable inset)
757 // so the dociterator may need to be
758 // shortened. Otherwise, setCursor may crash
759 // lyx when the cursor can not be set to these
761 size_t const n = doc_it.depth();
762 for (size_t i = 0; i < n; ++i)
763 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
771 // if top_id == 0, or searching through top_id failed
772 // This is the case for a 'restored' bookmark when only bottom
773 // (document level) pit was saved. Because of this, bookmark
774 // restoration is inaccurate. If a bookmark was within an inset,
775 // it will be restored to the left of the outmost inset that contains
777 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
778 doc_it = doc_iterator_begin(buffer_.inset());
779 doc_it.pit() = bottom_pit;
780 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
785 // Note: only bottom (document) level pit is set.
787 // set the current font.
788 d.cursor_.setCurrentFont();
789 // center the screen on this new position.
797 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
799 if (lyxrc.rtl_support) {
800 if (d.cursor_.real_current_font.isRightToLeft()) {
801 if (d.intl_.keymap == Intl::PRIMARY)
804 if (d.intl_.keymap == Intl::SECONDARY)
805 d.intl_.keyMapPrim();
809 d.intl_.getTransManager().translateAndInsert(c, t, cur);
813 int BufferView::workWidth() const
819 void BufferView::updateOffsetRef()
821 // No need to update d.offset_ref_ in this case.
822 if (!d.need_centering_)
825 // We are not properly started yet, delay until resizing is
830 CursorSlice & bot = d.cursor_.bottom();
831 TextMetrics & tm = d.text_metrics_[bot.text()];
832 ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
833 int y = coordOffset(d.cursor_, d.cursor_.boundary()).y_;
834 d.offset_ref_ = y + pm.ascent() - height_ / 2;
836 d.need_centering_ = false;
840 void BufferView::center()
842 d.anchor_ref_ = d.cursor_.bottom().pit();
843 d.need_centering_ = true;
847 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
851 Cursor & cur = d.cursor_;
853 switch (cmd.action) {
856 flag.enabled(!buffer_.undostack().empty());
859 flag.enabled(!buffer_.redostack().empty());
861 case LFUN_FILE_INSERT:
862 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
863 case LFUN_FILE_INSERT_PLAINTEXT:
864 case LFUN_BOOKMARK_SAVE:
865 // FIXME: Actually, these LFUNS should be moved to Text
866 flag.enabled(cur.inTexted());
868 case LFUN_FONT_STATE:
869 case LFUN_LABEL_INSERT:
870 case LFUN_PARAGRAPH_GOTO:
871 // FIXME handle non-trivially
872 case LFUN_OUTLINE_UP:
873 case LFUN_OUTLINE_DOWN:
874 case LFUN_OUTLINE_IN:
875 case LFUN_OUTLINE_OUT:
877 case LFUN_REFERENCE_NEXT:
879 case LFUN_WORD_REPLACE:
882 case LFUN_MARK_TOGGLE:
883 case LFUN_SCREEN_RECENTER:
884 case LFUN_BIBTEX_DATABASE_ADD:
885 case LFUN_BIBTEX_DATABASE_DEL:
886 case LFUN_WORDS_COUNT:
887 case LFUN_NEXT_INSET_TOGGLE:
891 case LFUN_LABEL_GOTO: {
892 flag.enabled(!cmd.argument().empty()
893 || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
897 case LFUN_CHANGES_TRACK:
899 flag.setOnOff(buffer_.params().trackChanges);
902 case LFUN_CHANGES_OUTPUT:
904 flag.setOnOff(buffer_.params().outputChanges);
907 case LFUN_CHANGES_MERGE:
908 case LFUN_CHANGE_NEXT:
909 case LFUN_ALL_CHANGES_ACCEPT:
910 case LFUN_ALL_CHANGES_REJECT:
911 // TODO: context-sensitive enabling of LFUNs
912 // In principle, these command should only be enabled if there
913 // is a change in the document. However, without proper
914 // optimizations, this will inevitably result in poor performance.
918 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
919 flag.setOnOff(buffer_.params().compressed);
924 case LFUN_SCREEN_DOWN:
928 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
929 // everywhere else before this can enabled:
930 case LFUN_SCREEN_UP_SELECT:
931 case LFUN_SCREEN_DOWN_SELECT:
943 Update::flags BufferView::dispatch(FuncRequest const & cmd)
945 //lyxerr << BOOST_CURRENT_FUNCTION
946 // << [ cmd = " << cmd << "]" << endl;
948 // Make sure that the cached BufferView is correct.
949 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
950 << " action[" << cmd.action << ']'
951 << " arg[" << to_utf8(cmd.argument()) << ']'
952 << " x[" << cmd.x << ']'
953 << " y[" << cmd.y << ']'
954 << " button[" << cmd.button() << ']'
957 Cursor & cur = d.cursor_;
958 // Default Update flags.
959 Update::flags updateFlags = Update::Force | Update::FitCursor;
961 switch (cmd.action) {
964 cur.message(_("Undo"));
965 cur.clearSelection();
966 if (!textUndo(*this)) {
967 cur.message(_("No further undo information"));
968 updateFlags = Update::None;
973 cur.message(_("Redo"));
974 cur.clearSelection();
975 if (!textRedo(*this)) {
976 cur.message(_("No further redo information"));
977 updateFlags = Update::None;
981 case LFUN_FILE_INSERT:
983 menuInsertLyXFile(to_utf8(cmd.argument()));
986 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
988 insertPlaintextFile(to_utf8(cmd.argument()), true);
991 case LFUN_FILE_INSERT_PLAINTEXT:
993 insertPlaintextFile(to_utf8(cmd.argument()), false);
996 case LFUN_FONT_STATE:
997 cur.message(cur.currentState());
1000 case LFUN_BOOKMARK_SAVE:
1001 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1004 case LFUN_LABEL_GOTO: {
1005 docstring label = cmd.argument();
1006 if (label.empty()) {
1008 getInsetByCode<InsetRef>(d.cursor_,
1011 label = inset->getParam("reference");
1012 // persistent=false: use temp_bookmark
1022 case LFUN_PARAGRAPH_GOTO: {
1023 int const id = convert<int>(to_utf8(cmd.argument()));
1025 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1026 b = theBufferList().next(b)) {
1028 ParIterator par = b->getParFromID(id);
1029 if (par == b->par_iterator_end()) {
1031 << "No matching paragraph found! ["
1032 << id << "]." << endl;
1035 << "Paragraph " << par->id()
1036 << " found in buffer `"
1037 << b->fileName() << "'." << endl;
1039 if (b == &buffer_) {
1041 setCursor(makeDocIterator(par, 0));
1043 // Switch to other buffer view and resend cmd
1044 theLyXFunc().dispatch(FuncRequest(
1045 LFUN_BUFFER_SWITCH, b->fileName()));
1046 theLyXFunc().dispatch(cmd);
1047 updateFlags = Update::None;
1056 case LFUN_OUTLINE_UP:
1057 outline(OutlineUp, d.cursor_);
1058 d.cursor_.text()->setCursor(d.cursor_, d.cursor_.pit(), 0);
1059 updateLabels(buffer_);
1061 case LFUN_OUTLINE_DOWN:
1062 outline(OutlineDown, d.cursor_);
1063 d.cursor_.text()->setCursor(d.cursor_, d.cursor_.pit(), 0);
1064 updateLabels(buffer_);
1066 case LFUN_OUTLINE_IN:
1067 outline(OutlineIn, d.cursor_);
1068 updateLabels(buffer_);
1070 case LFUN_OUTLINE_OUT:
1071 outline(OutlineOut, d.cursor_);
1072 updateLabels(buffer_);
1075 case LFUN_NOTE_NEXT:
1076 gotoInset(this, Inset::NOTE_CODE, false);
1079 case LFUN_REFERENCE_NEXT: {
1080 vector<Inset_code> tmp;
1081 tmp.push_back(Inset::LABEL_CODE);
1082 tmp.push_back(Inset::REF_CODE);
1083 gotoInset(this, tmp, true);
1087 case LFUN_CHANGES_TRACK:
1088 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1091 case LFUN_CHANGES_OUTPUT:
1092 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1093 if (buffer_.params().outputChanges) {
1094 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1095 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1096 LaTeXFeatures::isAvailable("xcolor");
1098 if (!dvipost && !xcolorsoul) {
1099 Alert::warning(_("Changes not shown in LaTeX output"),
1100 _("Changes will not be highlighted in LaTeX output, "
1101 "because neither dvipost nor xcolor/soul are installed.\n"
1102 "Please install these packages or redefine "
1103 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1104 } else if (!xcolorsoul) {
1105 Alert::warning(_("Changes not shown in LaTeX output"),
1106 _("Changes will not be highlighted in LaTeX output "
1107 "when using pdflatex, because xcolor and soul are not installed.\n"
1108 "Please install both packages or redefine "
1109 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1114 case LFUN_CHANGE_NEXT:
1115 findNextChange(this);
1118 case LFUN_CHANGES_MERGE:
1119 if (findNextChange(this))
1120 showDialog("changes");
1123 case LFUN_ALL_CHANGES_ACCEPT:
1124 // select complete document
1125 d.cursor_.reset(buffer_.inset());
1126 d.cursor_.selHandle(true);
1127 buffer_.text().cursorBottom(d.cursor_);
1128 // accept everything in a single step to support atomic undo
1129 buffer_.text().acceptOrRejectChanges(d.cursor_, Text::ACCEPT);
1132 case LFUN_ALL_CHANGES_REJECT:
1133 // select complete document
1134 d.cursor_.reset(buffer_.inset());
1135 d.cursor_.selHandle(true);
1136 buffer_.text().cursorBottom(d.cursor_);
1137 // reject everything in a single step to support atomic undo
1138 // Note: reject does not work recursively; the user may have to repeat the operation
1139 buffer_.text().acceptOrRejectChanges(d.cursor_, Text::REJECT);
1142 case LFUN_WORD_FIND:
1146 case LFUN_WORD_REPLACE: {
1147 bool has_deleted = false;
1148 if (cur.selection()) {
1149 DocIterator beg = cur.selectionBegin();
1150 DocIterator end = cur.selectionEnd();
1151 if (beg.pit() == end.pit()) {
1152 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1153 if (cur.paragraph().isDeleted(p))
1158 replace(this, cmd, has_deleted);
1163 cur.clearSelection();
1165 cur.message(from_utf8(N_("Mark off")));
1169 cur.clearSelection();
1172 cur.message(from_utf8(N_("Mark on")));
1175 case LFUN_MARK_TOGGLE:
1176 cur.clearSelection();
1179 cur.message(from_utf8(N_("Mark removed")));
1182 cur.message(from_utf8(N_("Mark set")));
1187 case LFUN_SCREEN_RECENTER:
1191 case LFUN_BIBTEX_DATABASE_ADD: {
1192 Cursor tmpcur = d.cursor_;
1193 findInset(tmpcur, Inset::BIBTEX_CODE, false);
1194 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1195 Inset::BIBTEX_CODE);
1197 if (inset->addDatabase(to_utf8(cmd.argument())))
1198 buffer_.updateBibfilesCache();
1203 case LFUN_BIBTEX_DATABASE_DEL: {
1204 Cursor tmpcur = d.cursor_;
1205 findInset(tmpcur, Inset::BIBTEX_CODE, false);
1206 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1207 Inset::BIBTEX_CODE);
1209 if (inset->delDatabase(to_utf8(cmd.argument())))
1210 buffer_.updateBibfilesCache();
1215 case LFUN_WORDS_COUNT: {
1216 DocIterator from, to;
1217 if (cur.selection()) {
1218 from = cur.selectionBegin();
1219 to = cur.selectionEnd();
1221 from = doc_iterator_begin(buffer_.inset());
1222 to = doc_iterator_end(buffer_.inset());
1224 int const count = countWords(from, to);
1227 if (cur.selection())
1228 message = bformat(_("%1$d words in selection."),
1231 message = bformat(_("%1$d words in document."),
1235 if (cur.selection())
1236 message = _("One word in selection.");
1238 message = _("One word in document.");
1241 Alert::information(_("Count words"), message);
1245 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1246 // turn compression on/off
1247 buffer_.params().compressed = !buffer_.params().compressed;
1250 case LFUN_NEXT_INSET_TOGGLE: {
1251 // this is the real function we want to invoke
1252 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1253 // if there is an inset at cursor, see whether it
1255 Inset * inset = cur.nextInset();
1257 if (inset->isActive()) {
1258 Cursor tmpcur = cur;
1259 tmpcur.pushLeft(*inset);
1260 inset->dispatch(tmpcur, tmpcmd);
1261 if (tmpcur.result().dispatched()) {
1264 } else if (inset->editable() == Inset::IS_EDITABLE) {
1265 inset->edit(cur, true);
1268 // if it did not work, try the underlying inset.
1269 if (!cur.result().dispatched())
1270 cur.dispatch(tmpcmd);
1272 if (cur.result().dispatched())
1273 cur.clearSelection();
1278 case LFUN_SCREEN_UP:
1279 case LFUN_SCREEN_DOWN: {
1280 Point p = getPos(cur, cur.boundary());
1281 if (p.y_ < 0 || p.y_ > height_) {
1282 // The cursor is off-screen so recenter before proceeding.
1284 updateMetrics(false);
1285 //FIXME: updateMetrics() does not update paragraph position
1286 // This is done at draw() time. So we need a redraw!
1288 p = getPos(cur, cur.boundary());
1290 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1291 cur.reset(buffer_.inset());
1292 d.text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1293 //FIXME: what to do with cur.x_target()?
1295 // The metrics are already up to date. see scroll()
1296 updateFlags = Update::None;
1300 case LFUN_SCREEN_UP_SELECT:
1301 case LFUN_SCREEN_DOWN_SELECT: {
1302 cur.selHandle(true);
1303 size_t initial_depth = cur.depth();
1304 Point const p = getPos(cur, cur.boundary());
1305 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1306 // FIXME: We need to verify if the cursor stayed within an inset...
1307 //cur.reset(buffer_.inset());
1308 d.text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1310 while (cur.depth() > initial_depth) {
1313 // FIXME: we need to do a redraw again because of the selection
1315 updateFlags = Update::Force | Update::FitCursor;
1320 updateFlags = Update::None;
1327 docstring const BufferView::requestSelection()
1329 Cursor & cur = d.cursor_;
1331 if (!cur.selection()) {
1332 d.xsel_cache_.set = false;
1336 if (!d.xsel_cache_.set ||
1337 cur.top() != d.xsel_cache_.cursor ||
1338 cur.anchor_.top() != d.xsel_cache_.anchor)
1340 d.xsel_cache_.cursor = cur.top();
1341 d.xsel_cache_.anchor = cur.anchor_.top();
1342 d.xsel_cache_.set = cur.selection();
1343 return cur.selectionAsString(false);
1349 void BufferView::clearSelection()
1351 d.cursor_.clearSelection();
1352 // Clear the selection buffer. Otherwise a subsequent
1353 // middle-mouse-button paste would use the selection buffer,
1354 // not the more current external selection.
1355 cap::clearSelection();
1356 d.xsel_cache_.set = false;
1357 // The buffer did not really change, but this causes the
1358 // redraw we need because we cleared the selection above.
1363 void BufferView::resize(int width, int height)
1365 // Update from work area
1369 updateMetrics(false);
1373 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1375 TextMetrics & tm = d.text_metrics_[&text];
1376 Inset * inset = tm.checkInsetHit(x, y);
1380 if (!inset->descendable())
1381 // No need to go further down if the inset is not
1385 size_t cell_number = inset->nargs();
1386 // Check all the inner cell.
1387 for (size_t i = 0; i != cell_number; ++i) {
1388 Text const * inner_text = inset->getText(i);
1391 Inset const * inset_deeper =
1392 getCoveringInset(*inner_text, x, y);
1394 return inset_deeper;
1402 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1404 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1406 // This is only called for mouse related events including
1407 // LFUN_FILE_OPEN generated by drag-and-drop.
1408 FuncRequest cmd = cmd0;
1411 cur.push(buffer_.inset());
1412 cur.selection() = d.cursor_.selection();
1414 // Either the inset under the cursor or the
1415 // surrounding Text will handle this event.
1417 // make sure we stay within the screen...
1418 cmd.y = min(max(cmd.y, -1), height_);
1420 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1422 // Get inset under mouse, if there is one.
1423 Inset const * covering_inset =
1424 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1425 if (covering_inset == d.last_inset_)
1426 // Same inset, no need to do anything...
1429 bool need_redraw = false;
1430 // const_cast because of setMouseHover().
1431 Inset * inset = const_cast<Inset *>(covering_inset);
1433 // Remove the hint on the last hovered inset (if any).
1434 need_redraw |= d.last_inset_->setMouseHover(false);
1436 // Highlighted the newly hovered inset (if any).
1437 need_redraw |= inset->setMouseHover(true);
1438 d.last_inset_ = inset;
1442 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1443 // not expose the button for redraw. We adjust here the metrics dimension
1444 // to enable a full redraw in any case as this is not costly.
1445 TextMetrics & tm = d.text_metrics_[&buffer_.text()];
1446 std::pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1447 std::pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1448 int y1 = firstpm.second->position() - firstpm.second->ascent();
1449 int y2 = lastpm.second->position() + lastpm.second->descent();
1450 d.metrics_info_ = ViewMetricsInfo(firstpm.first, lastpm.first, y1, y2,
1451 FullScreenUpdate, buffer_.text().paragraphs().size());
1452 // Reinitialize anchor to first pit.
1453 d.anchor_ref_ = firstpm.first;
1454 d.offset_ref_ = -y1;
1455 LYXERR(Debug::PAINTING)
1456 << "Mouse hover detected at: (" << cmd.x << ", " << cmd.y << ")"
1457 << "\nTriggering redraw: y1: " << y1 << " y2: " << y2
1458 << " pit1: " << firstpm.first << " pit2: " << lastpm.first << endl;
1460 // This event (moving without mouse click) is not passed further.
1461 // This should be changed if it is further utilized.
1466 // Build temporary cursor.
1467 Inset * inset = d.text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1469 // Put anchor at the same position.
1472 // Try to dispatch to an non-editable inset near this position
1473 // via the temp cursor. If the inset wishes to change the real
1474 // cursor it has to do so explicitly by using
1475 // cur.bv().cursor() = cur; (or similar)
1477 inset->dispatch(cur, cmd);
1479 // Now dispatch to the temporary cursor. If the real cursor should
1480 // be modified, the inset's dispatch has to do so explicitly.
1481 if (!cur.result().dispatched())
1484 //Do we have a selection?
1485 theSelection().haveSelection(cursor().selection());
1487 // If the command has been dispatched,
1488 if (cur.result().dispatched()
1489 // an update is asked,
1490 && cur.result().update())
1491 processUpdateFlags(cur.result().update());
1495 void BufferView::scroll(int y)
1504 void BufferView::scrollDown(int offset)
1506 Text * text = &buffer_.text();
1507 TextMetrics & tm = d.text_metrics_[text];
1508 int ymax = height_ + offset;
1510 std::pair<pit_type, ParagraphMetrics const *> last = tm.last();
1511 int bottom_pos = last.second->position() + last.second->descent();
1512 if (last.first + 1 == int(text->paragraphs().size())) {
1513 if (bottom_pos <= height_)
1515 offset = min(offset, bottom_pos - height_);
1518 if (bottom_pos > ymax)
1520 tm.newParMetricsDown();
1522 d.offset_ref_ += offset;
1523 updateMetrics(false);
1528 void BufferView::scrollUp(int offset)
1530 Text * text = &buffer_.text();
1531 TextMetrics & tm = d.text_metrics_[text];
1532 int ymin = - offset;
1534 std::pair<pit_type, ParagraphMetrics const *> first = tm.first();
1535 int top_pos = first.second->position() - first.second->ascent();
1536 if (first.first == 0) {
1539 offset = min(offset, - top_pos);
1544 tm.newParMetricsUp();
1546 d.offset_ref_ -= offset;
1547 updateMetrics(false);
1552 void BufferView::setCursorFromRow(int row)
1557 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1559 d.cursor_.reset(buffer_.inset());
1561 buffer_.text().setCursor(d.cursor_, 0, 0);
1563 buffer_.text().setCursor(d.cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1567 void BufferView::gotoLabel(docstring const & label)
1569 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1570 vector<docstring> labels;
1571 it->getLabelList(buffer_, labels);
1572 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1574 processUpdateFlags(Update::FitCursor);
1581 TextMetrics const & BufferView::textMetrics(Text const * t) const
1583 return const_cast<BufferView *>(this)->textMetrics(t);
1587 TextMetrics & BufferView::textMetrics(Text const * t)
1589 TextMetricsCache::iterator tmc_it = d.text_metrics_.find(t);
1590 if (tmc_it == d.text_metrics_.end()) {
1591 tmc_it = d.text_metrics_.insert(
1592 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1594 return tmc_it->second;
1598 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1601 return textMetrics(t).parMetrics(pit);
1605 int BufferView::workHeight() const
1611 void BufferView::setCursor(DocIterator const & dit)
1613 size_t const n = dit.depth();
1614 for (size_t i = 0; i < n; ++i)
1615 dit[i].inset().edit(d.cursor_, true);
1617 d.cursor_.setCursor(dit);
1618 d.cursor_.selection() = false;
1622 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1624 // Would be wrong to delete anything if we have a selection.
1625 if (cur.selection())
1628 bool need_anchor_change = false;
1629 bool changed = d.cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1630 need_anchor_change);
1632 if (need_anchor_change)
1638 updateLabels(buffer_);
1640 updateMetrics(false);
1646 bool BufferView::mouseSetCursor(Cursor & cur)
1648 BOOST_ASSERT(&cur.bv() == this);
1650 // this event will clear selection so we save selection for
1651 // persistent selection
1652 cap::saveSelection(cursor());
1654 // Has the cursor just left the inset?
1655 bool badcursor = false;
1656 bool leftinset = (&d.cursor_.inset() != &cur.inset());
1658 badcursor = notifyCursorLeaves(d.cursor_, cur);
1660 // do the dEPM magic if needed
1661 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1662 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1663 // the leftinset bool would not be necessary (badcursor instead).
1664 bool update = leftinset;
1665 if (!badcursor && d.cursor_.inTexted())
1666 update |= checkDepm(cur, d.cursor_);
1668 // if the cursor was in an empty script inset and the new
1669 // position is in the nucleus of the inset, notifyCursorLeaves
1670 // will kill the script inset itself. So we check all the
1671 // elements of the cursor to make sure that they are correct.
1672 // For an example, see bug 2933:
1673 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1674 // The code below could maybe be moved to a DocIterator method.
1675 //lyxerr << "cur before " << cur <<std::endl;
1676 DocIterator dit(cur.inset());
1677 dit.push_back(cur.bottom());
1679 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1680 dit.push_back(cur[i]);
1683 //lyxerr << "5 cur after" << dit <<std::endl;
1685 d.cursor_.setCursor(dit);
1686 d.cursor_.boundary(cur.boundary());
1687 d.cursor_.clearSelection();
1693 void BufferView::putSelectionAt(DocIterator const & cur,
1694 int length, bool backwards)
1696 d.cursor_.clearSelection();
1702 d.cursor_.pos() += length;
1703 d.cursor_.setSelection(d.cursor_, -length);
1705 d.cursor_.setSelection(d.cursor_, length);
1710 Cursor & BufferView::cursor()
1716 Cursor const & BufferView::cursor() const
1722 pit_type BufferView::anchor_ref() const
1724 return d.anchor_ref_;
1728 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1730 return d.metrics_info_;
1734 bool BufferView::singleParUpdate()
1736 Text & buftext = buffer_.text();
1737 pit_type const bottom_pit = d.cursor_.bottom().pit();
1738 TextMetrics & tm = textMetrics(&buftext);
1739 int old_height = tm.parMetrics(bottom_pit).height();
1741 // In Single Paragraph mode, rebreak only
1742 // the (main text, not inset!) paragraph containing the cursor.
1743 // (if this paragraph contains insets etc., rebreaking will
1744 // recursively descend)
1745 tm.redoParagraph(bottom_pit);
1746 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1747 if (pm.height() != old_height)
1748 // Paragraph height has changed so we cannot proceed to
1749 // the singlePar optimisation.
1752 int y1 = pm.position() - pm.ascent();
1753 int y2 = pm.position() + pm.descent();
1754 d.metrics_info_ = ViewMetricsInfo(bottom_pit, bottom_pit, y1, y2,
1755 SingleParUpdate, buftext.paragraphs().size());
1756 LYXERR(Debug::PAINTING)
1757 << BOOST_CURRENT_FUNCTION
1760 << " pit: " << bottom_pit
1767 void BufferView::updateMetrics(bool singlepar)
1769 if (singlepar && singleParUpdate())
1770 // No need to update the full screen metrics.
1773 Text & buftext = buffer_.text();
1774 pit_type const npit = int(buftext.paragraphs().size());
1776 if (d.anchor_ref_ > int(npit - 1)) {
1777 d.anchor_ref_ = int(npit - 1);
1781 // Clear out the position cache in case of full screen redraw,
1782 d.coord_cache_.clear();
1784 // Clear out paragraph metrics to avoid having invalid metrics
1785 // in the cache from paragraphs not relayouted below
1786 // The complete text metrics will be redone.
1787 d.text_metrics_.clear();
1789 TextMetrics & tm = textMetrics(&buftext);
1791 pit_type const pit = d.anchor_ref_;
1795 // Rebreak anchor paragraph.
1796 tm.redoParagraph(pit);
1798 // Take care of anchor offset if case a recentering is needed.
1801 int y0 = tm.parMetrics(pit).ascent() - d.offset_ref_;
1803 // Redo paragraphs above anchor if necessary.
1805 while (y1 > 0 && pit1 > 0) {
1806 y1 -= tm.parMetrics(pit1).ascent();
1808 tm.redoParagraph(pit1);
1809 y1 -= tm.parMetrics(pit1).descent();
1812 // Take care of ascent of first line
1813 y1 -= tm.parMetrics(pit1).ascent();
1815 // Normalize anchor for next time
1816 d.anchor_ref_ = pit1;
1817 d.offset_ref_ = -y1;
1819 // Grey at the beginning is ugly
1820 if (pit1 == 0 && y1 > 0) {
1826 // Redo paragraphs below the anchor if necessary.
1828 while (y2 < height_ && pit2 < int(npit) - 1) {
1829 y2 += tm.parMetrics(pit2).descent();
1831 tm.redoParagraph(pit2);
1832 y2 += tm.parMetrics(pit2).ascent();
1835 // Take care of descent of last line
1836 y2 += tm.parMetrics(pit2).descent();
1838 LYXERR(Debug::PAINTING)
1839 << BOOST_CURRENT_FUNCTION
1842 << " pit1: " << pit1
1843 << " pit2: " << pit2
1844 << " npit: " << npit
1848 d.metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1849 FullScreenUpdate, npit);
1851 if (lyxerr.debugging(Debug::WORKAREA)) {
1852 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1853 d.coord_cache_.dump();
1858 void BufferView::menuInsertLyXFile(string const & filenm)
1860 BOOST_ASSERT(d.cursor_.inTexted());
1861 string filename = filenm;
1863 if (filename.empty()) {
1864 // Launch a file browser
1866 string initpath = lyxrc.document_path;
1867 string const trypath = buffer_.filePath();
1868 // If directory is writeable, use this as default.
1869 if (isDirWriteable(FileName(trypath)))
1873 FileDialog fileDlg(_("Select LyX document to insert"),
1875 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1876 make_pair(_("Examples|#E#e"),
1877 from_utf8(addPath(package().system_support().absFilename(),
1880 FileDialog::Result result =
1881 fileDlg.open(from_utf8(initpath),
1882 FileFilterList(_("LyX Documents (*.lyx)")),
1885 if (result.first == FileDialog::Later)
1889 filename = to_utf8(result.second);
1891 // check selected filename
1892 if (filename.empty()) {
1893 // emit message signal.
1894 message(_("Canceled."));
1899 // Get absolute path of file and add ".lyx"
1900 // to the filename if necessary
1901 filename = fileSearch(string(), filename, "lyx").absFilename();
1903 docstring const disp_fn = makeDisplayPath(filename);
1904 // emit message signal.
1905 message(bformat(_("Inserting document %1$s..."), disp_fn));
1908 Buffer buf("", false);
1909 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1910 ErrorList & el = buffer_.errorList("Parse");
1911 // Copy the inserted document error list into the current buffer one.
1912 el = buf.errorList("Parse");
1913 recordUndo(d.cursor_);
1914 cap::pasteParagraphList(d.cursor_, buf.paragraphs(),
1915 buf.params().getTextClassPtr(), el);
1916 res = _("Document %1$s inserted.");
1918 res = _("Could not insert document %1$s");
1920 // emit message signal.
1921 message(bformat(res, disp_fn));
1922 buffer_.errors("Parse");
1923 updateMetrics(false);
1927 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1933 // Addup contribution of nested insets, from inside to outside,
1934 // keeping the outer paragraph for a special handling below
1935 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1936 CursorSlice const & sl = dit[i];
1940 // get relative position inside sl.inset()
1941 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1943 // Make relative position inside of the edited inset relative to sl.inset()
1947 // In case of an RTL inset, the edited inset will be positioned to the left
1950 bool boundary_i = boundary && i + 1 == dit.depth();
1951 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1956 // remember width for the case that sl.inset() is positioned in an RTL inset
1957 if (i && dit[i - 1].text()) {
1958 // If this Inset is inside a Text Inset, retrieve the Dimension
1959 // from the containing text instead of using Inset::dimension() which
1960 // might not be implemented.
1961 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1962 // elimination of Inset::dim_ cache. This coordOffset() method needs
1963 // to be rewritten in light of the new design.
1964 Dimension const & dim = parMetrics(dit[i - 1].text(),
1965 dit[i - 1].pit()).insetDimension(&sl.inset());
1968 Dimension const dim = sl.inset().dimension(*this);
1972 //lyxerr << "Cursor::getPos, i: "
1973 // << i << " x: " << xx << " y: " << y << endl;
1976 // Add contribution of initial rows of outermost paragraph
1977 CursorSlice const & sl = dit[0];
1978 TextMetrics const & tm = textMetrics(sl.text());
1979 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1980 BOOST_ASSERT(!pm.rows().empty());
1981 y -= pm.rows()[0].ascent();
1983 // FIXME: document this mess
1985 if (sl.pos() > 0 && dit.depth() == 1) {
1987 if (pos && boundary)
1989 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << std::endl;
1990 rend = pm.pos2row(pos);
1992 rend = pm.pos2row(sl.pos());
1994 size_t rend = pm.pos2row(sl.pos());
1996 for (size_t rit = 0; rit != rend; ++rit)
1997 y += pm.rows()[rit].height();
1998 y += pm.rows()[rend].ascent();
2000 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2002 // Make relative position from the nested inset now bufferview absolute.
2003 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2006 // In the RTL case place the nested inset at the left of the cursor in
2007 // the outer paragraph
2008 bool boundary_1 = boundary && 1 == dit.depth();
2009 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2017 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2019 CursorSlice const & bot = dit.bottom();
2020 TextMetrics const & tm = textMetrics(bot.text());
2021 if (!tm.has(bot.pit()))
2022 return Point(-1, -1);
2024 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2025 p.y_ += tm.parMetrics(bot.pit()).position();
2030 void BufferView::draw(frontend::Painter & pain)
2032 PainterInfo pi(this, pain);
2033 // Should the whole screen, including insets, be refreshed?
2034 // FIXME: We should also distinguish DecorationUpdate to avoid text
2035 // drawing if possible. This is not possible to do easily right now
2036 // because of the single backing pixmap.
2037 pi.full_repaint = d.metrics_info_.update_strategy != SingleParUpdate;
2039 if (pi.full_repaint)
2040 // Clear background (if not delegated to rows)
2041 pain.fillRectangle(0, d.metrics_info_.y1, width_,
2042 d.metrics_info_.y2 - d.metrics_info_.y1,
2043 buffer_.inset().backgroundColor());
2045 LYXERR(Debug::PAINTING) << "\t\t*** START DRAWING ***" << endl;
2046 Text & text = buffer_.text();
2047 TextMetrics const & tm = d.text_metrics_[&text];
2048 int y = d.metrics_info_.y1 + tm.parMetrics(d.metrics_info_.p1).ascent();
2049 if (!pi.full_repaint)
2050 tm.drawParagraph(pi, d.metrics_info_.p1, 0, y);
2053 LYXERR(Debug::PAINTING) << "\n\t\t*** END DRAWING ***" << endl;
2055 // and grey out above (should not happen later)
2056 // lyxerr << "par ascent: " << text.getPar(d.metrics_info_.p1).ascent() << endl;
2057 if (d.metrics_info_.y1 > 0
2058 && d.metrics_info_.update_strategy == FullScreenUpdate)
2059 pain.fillRectangle(0, 0, width_, d.metrics_info_.y1, Color::bottomarea);
2061 // and possibly grey out below
2062 // lyxerr << "par descent: " << text.getPar(d.metrics_info_.p1).ascent() << endl;
2063 if (d.metrics_info_.y2 < height_
2064 && d.metrics_info_.update_strategy == FullScreenUpdate)
2065 pain.fillRectangle(0, d.metrics_info_.y2, width_,
2066 height_ - d.metrics_info_.y2, Color::bottomarea);
2070 void BufferView::message(docstring const & msg)
2073 d.gui_->message(msg);
2077 void BufferView::showDialog(std::string const & name)
2080 d.gui_->showDialog(name);
2084 void BufferView::showDialogWithData(std::string const & name,
2085 std::string const & data)
2088 d.gui_->showDialogWithData(name, data);
2092 void BufferView::showInsetDialog(std::string const & name,
2093 std::string const & data, Inset * inset)
2096 d.gui_->showInsetDialog(name, data, inset);
2100 void BufferView::updateDialog(std::string const & name, std::string const & data)
2103 d.gui_->updateDialog(name, data);
2107 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2113 // FIXME: Move this out of BufferView again
2114 docstring BufferView::contentsOfPlaintextFile(string const & f,
2119 if (fname.empty()) {
2120 FileDialog fileDlg(_("Select file to insert"),
2122 ? LFUN_FILE_INSERT_PLAINTEXT_PARA
2123 : LFUN_FILE_INSERT_PLAINTEXT) );
2125 FileDialog::Result result =
2126 fileDlg.open(from_utf8(buffer().filePath()),
2127 FileFilterList(), docstring());
2129 if (result.first == FileDialog::Later)
2132 fname = makeAbsPath(to_utf8(result.second));
2138 if (!fs::is_readable(fname.toFilesystemEncoding())) {
2139 docstring const error = from_ascii(strerror(errno));
2140 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2141 docstring const text =
2142 bformat(_("Could not read the specified document\n"
2143 "%1$s\ndue to the error: %2$s"), file, error);
2144 Alert::error(_("Could not read file"), text);
2148 ifstream ifs(fname.toFilesystemEncoding().c_str());
2150 docstring const error = from_ascii(strerror(errno));
2151 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2152 docstring const text =
2153 bformat(_("Could not open the specified document\n"
2154 "%1$s\ndue to the error: %2$s"), file, error);
2155 Alert::error(_("Could not open file"), text);
2159 ifs.unsetf(std::ios::skipws);
2160 istream_iterator<char> ii(ifs);
2161 istream_iterator<char> end;
2162 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
2163 // We use this until the compilers get better...
2164 std::vector<char> tmp;
2165 copy(ii, end, back_inserter(tmp));
2166 string const tmpstr(tmp.begin(), tmp.end());
2168 // This is what we want to use and what we will use once the
2169 // compilers get good enough.
2170 //string tmpstr(ii, end); // yet a reason for using std::string
2171 // alternate approach to get the file into a string:
2173 copy(ii, end, back_inserter(tmpstr));
2176 // FIXME UNICODE: We don't know the encoding of the file
2177 docstring file_content = from_utf8(tmpstr);
2178 if (file_content.empty()) {
2179 Alert::error(_("Reading not UTF-8 encoded file"),
2180 _("The file is not UTF-8 encoded.\n"
2181 "It will be read as local 8Bit-encoded.\n"
2182 "If this does not give the correct result\n"
2183 "then please change the encoding of the file\n"
2184 "to UTF-8 with a program other than LyX.\n"));
2185 file_content = from_local8bit(tmpstr);
2188 return normalize_c(file_content);
2192 void BufferView::insertPlaintextFile(string const & f, bool asParagraph)
2194 docstring const tmpstr = contentsOfPlaintextFile(f, asParagraph);
2199 Cursor & cur = cursor();
2200 cap::replaceSelection(cur);
2203 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2205 cur.innerText()->insertStringAsLines(cur, tmpstr);