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"
37 #include "lyx_cb.h" // added for Dispatch functions
41 #include "lyxlayout.h"
43 #include "lyxtextclass.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "pariterator.h"
54 #include "WordLangTuple.h"
55 #include "metricsinfo.h"
57 #include "insets/insetbibtex.h"
58 #include "insets/insetcommand.h" // ChangeRefs
59 #include "insets/insetref.h"
60 #include "insets/insettext.h"
62 #include "frontends/Alert.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/FontMetrics.h"
66 #include "graphics/Previews.h"
68 #include "support/convert.h"
69 #include "support/filefilterlist.h"
70 #include "support/filetools.h"
71 #include "support/package.h"
72 #include "support/types.h"
74 #include <boost/bind.hpp>
75 #include <boost/current_function.hpp>
81 using lyx::CoordCache;
86 using lyx::support::addPath;
87 using lyx::support::bformat;
88 using lyx::support::FileFilterList;
89 using lyx::support::fileSearch;
90 using lyx::support::isDirWriteable;
91 using lyx::support::makeDisplayPath;
92 using lyx::support::makeAbsPath;
93 using lyx::support::package;
97 using std::istringstream;
102 using std::mem_fun_ref;
106 namespace Alert = lyx::frontend::Alert;
110 unsigned int const saved_positions_num = 20;
113 /// Return an inset of this class if it exists at the current cursor position
115 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
118 DocIterator it = cur;
119 if (it.nextInset() &&
120 it.nextInset()->lyxCode() == code) {
121 inset = static_cast<T*>(it.nextInset());
129 BufferView::BufferView()
130 : buffer_(0), wh_(0),
132 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
135 xsel_cache_.set = false;
137 saved_positions.resize(saved_positions_num);
138 // load saved bookmarks
139 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
140 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
141 bm != bmList.end(); ++bm)
142 if (bm->get<0>() < saved_positions_num)
143 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
144 // and then clear them
147 intl_->initKeyMapper(lyxrc.use_kbmap);
151 BufferView::~BufferView()
156 Buffer * BufferView::buffer() const
162 void BufferView::setBuffer(Buffer * b)
164 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
165 << "[ b = " << b << "]" << endl;
168 // Save the actual cursor position and anchor inside the
169 // buffer so that it can be restored in case we rechange
170 // to this buffer later on.
171 buffer_->saveCursor(cursor_.selectionBegin(),
172 cursor_.selectionEnd());
173 // current buffer is going to be switched-off, save cursor pos
174 LyX::ref().session().saveFilePosition(buffer_->fileName(),
175 boost::tie(cursor_.pit(), cursor_.pos()) );
178 // If we're quitting lyx, don't bother updating stuff
184 // If we are closing current buffer, switch to the first in
187 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
188 << " No Buffer!" << endl;
189 // We are closing the buffer, use the first buffer as current
190 buffer_ = theBufferList().first();
192 // Set current buffer
197 cursor_ = LCursor(*this);
202 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
203 << "Buffer addr: " << buffer_ << endl;
204 cursor_.push(buffer_->inset());
205 cursor_.resetAnchor();
206 buffer_->text().init(this);
207 buffer_->text().setCurrentFont(cursor_);
208 if (buffer_->getCursor().size() > 0 &&
209 buffer_->getAnchor().size() > 0)
211 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
212 cursor_.resetAnchor();
213 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
214 cursor_.setSelection();
220 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
221 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
225 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
227 // Get absolute path of file and add ".lyx"
228 // to the filename if necessary
229 string s = fileSearch(string(), filename, "lyx");
231 bool const found = !s.empty();
236 // File already open?
237 if (theBufferList().exists(s)) {
238 docstring const file = makeDisplayPath(s, 20);
239 docstring text = bformat(_("The document %1$s is already "
240 "loaded.\n\nDo you want to revert "
241 "to the saved version?"), file);
242 int const ret = Alert::prompt(_("Revert to saved document?"),
243 text, 0, 1, _("&Revert"), _("&Switch to document"));
246 setBuffer(theBufferList().getBuffer(s));
249 // FIXME: should be LFUN_REVERT
250 if (!theBufferList().close(theBufferList().getBuffer(s), false))
252 // Fall through to new load. (Asger)
258 b = theBufferList().newBuffer(s);
259 if (!::loadLyXFile(b, s)) {
260 theBufferList().release(b);
264 docstring text = bformat(_("The document %1$s does not yet "
265 "exist.\n\nDo you want to create "
266 "a new document?"), lyx::from_utf8(s));
267 int const ret = Alert::prompt(_("Create new document?"),
268 text, 0, 1, _("&Create"), _("Cancel"));
271 b = newFile(s, string(), true);
279 // Send the "errors" signal in case of parsing errors
282 // scroll to the position when the file was last closed
283 if (lyxrc.use_lastfilepos) {
286 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
287 // I am not sure how to separate the following part to a function
288 // so I will leave this to Lars.
290 // check pit since the document may be externally changed.
291 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
292 ParIterator it = b->par_iterator_begin();
293 ParIterator const end = b->par_iterator_end();
294 for (; it != end; ++it)
295 if (it.pit() == pit) {
296 // restored pos may be bigger than it->size
297 setCursor(makeDocIterator(it, min(pos, it->size())));
298 update(Update::FitCursor);
305 LyX::ref().session().addLastFile(b->fileName());
311 void BufferView::reload()
313 string const fn = buffer_->fileName();
314 if (theBufferList().close(buffer_, false))
319 void BufferView::resize()
324 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
326 buffer_->text().init(this);
332 bool BufferView::fitCursor()
334 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
335 lyx::frontend::FontMetrics const & fm =
336 theFontMetrics(cursor_.getFont());
337 int const asc = fm.maxAscent();
338 int const des = fm.maxDescent();
339 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
340 if (p.y_ - asc >= 0 && p.y_ + des < height_)
348 bool BufferView::multiParSel()
350 if (!cursor_.selection())
352 bool ret = multiparsel_cache_;
353 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
354 // Either this, or previous selection spans paragraphs
355 return ret || multiparsel_cache_;
359 bool BufferView::update(Update::flags flags)
361 // This is close to a hot-path.
362 if (lyxerr.debugging(Debug::DEBUG)) {
364 << BOOST_CURRENT_FUNCTION
365 << "[fitcursor = " << (flags & Update::FitCursor)
366 << ", forceupdate = " << (flags & Update::Force)
367 << ", singlepar = " << (flags & Update::SinglePar)
368 << "] buffer: " << buffer_ << endl;
371 // Check needed to survive LyX startup
375 // Update macro store
376 buffer_->buildMacros();
378 // First drawing step
379 updateMetrics(flags & Update::SinglePar);
381 // The second drawing step is done in WorkArea::redraw() if needed.
382 bool const need_second_step =
383 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
384 && (fitCursor() || multiParSel());
386 return need_second_step;
390 void BufferView::updateScrollbar()
393 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
394 << " no text in updateScrollbar" << endl;
395 scrollbarParameters_.reset();
399 LyXText & t = buffer_->text();
400 int const parsize = int(t.paragraphs().size() - 1);
401 if (anchor_ref_ > parsize) {
402 anchor_ref_ = parsize;
407 << BOOST_CURRENT_FUNCTION
408 << " Updating scrollbar: height: " << t.paragraphs().size()
409 << " curr par: " << cursor_.bottom().pit()
410 << " default height " << defaultRowHeight() << endl;
412 // It would be better to fix the scrollbar to understand
413 // values in [0..1] and divide everything by wh
415 // estimated average paragraph height:
418 int h = t.getPar(anchor_ref_).height();
420 // Normalize anchor/offset (MV):
421 while (offset_ref_ > h && anchor_ref_ < parsize) {
424 h = t.getPar(anchor_ref_).height();
426 // Look at paragraph heights on-screen
429 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
432 int const h2 = t.getPar(pit).height();
436 int const hav = sumh / nh;
437 // More realistic average paragraph height
441 scrollbarParameters_.height = (parsize + 1) * wh_;
442 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
443 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
447 ScrollbarParameters const & BufferView::scrollbarParameters() const
449 return scrollbarParameters_;
453 void BufferView::scrollDocView(int value)
455 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
456 << "[ value = " << value << "]" << endl;
461 LyXText & t = buffer_->text();
463 float const bar = value / float(wh_ * t.paragraphs().size());
465 anchor_ref_ = int(bar * t.paragraphs().size());
466 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
467 anchor_ref_ = int(t.paragraphs().size()) - 1;
468 t.redoParagraph(anchor_ref_);
469 int const h = t.getPar(anchor_ref_).height();
470 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
474 void BufferView::setCursorFromScrollbar()
476 LyXText & t = buffer_->text();
478 int const height = 2 * defaultRowHeight();
479 int const first = height;
480 int const last = height_ - height;
481 LCursor & cur = cursor_;
483 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
486 case bv_funcs::CUR_ABOVE:
487 t.setCursorFromCoordinates(cur, 0, first);
488 cur.clearSelection();
490 case bv_funcs::CUR_BELOW:
491 t.setCursorFromCoordinates(cur, 0, last);
492 cur.clearSelection();
494 case bv_funcs::CUR_INSIDE:
495 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
496 int const newy = min(last, max(y, first));
498 cur.reset(buffer_->inset());
499 t.setCursorFromCoordinates(cur, 0, newy);
505 Change const BufferView::getCurrentChange() const
507 if (!cursor_.selection())
508 return Change(Change::UNCHANGED);
510 DocIterator dit = cursor_.selectionBegin();
511 return dit.paragraph().lookupChange(dit.pos());
515 void BufferView::savePosition(unsigned int i)
517 if (i >= saved_positions_num)
519 BOOST_ASSERT(cursor_.inTexted());
520 saved_positions[i] = Position(buffer_->fileName(),
521 cursor_.paragraph().id(),
524 // emit message signal.
525 message(bformat(_("Saved bookmark %1$d"), i));
529 void BufferView::restorePosition(unsigned int i)
531 if (i >= saved_positions_num)
534 string const fname = saved_positions[i].filename;
536 cursor_.clearSelection();
538 if (fname != buffer_->fileName()) {
540 if (theBufferList().exists(fname))
541 b = theBufferList().getBuffer(fname);
543 b = theBufferList().newBuffer(fname);
544 // Don't ask, just load it
545 ::loadLyXFile(b, fname);
551 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
552 if (par == buffer_->par_iterator_end())
555 setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
558 // emit message signal.
559 message(bformat(_("Moved to bookmark %1$d"), i));
563 bool BufferView::isSavedPosition(unsigned int i)
565 return i < saved_positions_num && !saved_positions[i].filename.empty();
568 void BufferView::saveSavedPositions()
570 // save bookmarks. It is better to use the pit interface
571 // but I do not know how to effectively convert between
573 for (unsigned int i=1; i < saved_positions_num; ++i) {
574 if ( isSavedPosition(i) )
575 LyX::ref().session().saveBookmark( boost::tie(
577 saved_positions[i].filename,
578 saved_positions[i].par_id,
579 saved_positions[i].par_pos) );
583 void BufferView::switchKeyMap()
585 if (!lyxrc.rtl_support)
588 if (getLyXText()->real_current_font.isRightToLeft()) {
589 if (intl_->keymap == Intl::PRIMARY)
592 if (intl_->keymap == Intl::SECONDARY)
598 int BufferView::workWidth() const
604 void BufferView::center()
606 CursorSlice & bot = cursor_.bottom();
607 lyx::pit_type const pit = bot.pit();
608 bot.text()->redoParagraph(pit);
609 Paragraph const & par = bot.text()->paragraphs()[pit];
611 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
612 + par.ascent() - height_ / 2;
616 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
620 switch (cmd.action) {
623 flag.enabled(!buffer_->undostack().empty());
626 flag.enabled(!buffer_->redostack().empty());
628 case LFUN_FILE_INSERT:
629 case LFUN_FILE_INSERT_ASCII_PARA:
630 case LFUN_FILE_INSERT_ASCII:
631 case LFUN_BOOKMARK_SAVE:
632 // FIXME: Actually, these LFUNS should be moved to LyXText
633 flag.enabled(cursor_.inTexted());
635 case LFUN_FONT_STATE:
636 case LFUN_LABEL_INSERT:
637 case LFUN_PARAGRAPH_GOTO:
638 // FIXME handle non-trivially
639 case LFUN_OUTLINE_UP:
640 case LFUN_OUTLINE_DOWN:
641 case LFUN_OUTLINE_IN:
642 case LFUN_OUTLINE_OUT:
644 case LFUN_REFERENCE_NEXT:
646 case LFUN_WORD_REPLACE:
649 case LFUN_MARK_TOGGLE:
650 case LFUN_SCREEN_RECENTER:
651 case LFUN_BIBTEX_DATABASE_ADD:
652 case LFUN_BIBTEX_DATABASE_DEL:
653 case LFUN_WORDS_COUNT:
654 case LFUN_NEXT_INSET_TOGGLE:
658 case LFUN_LABEL_GOTO: {
659 flag.enabled(!cmd.argument().empty()
660 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
664 case LFUN_BOOKMARK_GOTO:
665 flag.enabled(isSavedPosition(convert<unsigned int>(lyx::to_utf8(cmd.argument()))));
668 case LFUN_CHANGES_TRACK:
670 flag.setOnOff(buffer_->params().trackChanges);
673 case LFUN_CHANGES_OUTPUT: {
674 OutputParams runparams;
675 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
676 flag.enabled(buffer_ && features.isAvailable("dvipost"));
677 flag.setOnOff(buffer_->params().outputChanges);
681 case LFUN_CHANGES_MERGE:
682 case LFUN_CHANGE_NEXT:
683 case LFUN_ALL_CHANGES_ACCEPT:
684 case LFUN_ALL_CHANGES_REJECT:
685 flag.enabled(buffer_); // FIXME: Change tracking (MG)
688 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
689 flag.setOnOff(buffer_->params().compressed);
701 bool BufferView::dispatch(FuncRequest const & cmd)
703 //lyxerr << BOOST_CURRENT_FUNCTION
704 // << [ cmd = " << cmd << "]" << endl;
706 // Make sure that the cached BufferView is correct.
707 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
708 << " action[" << cmd.action << ']'
709 << " arg[" << lyx::to_utf8(cmd.argument()) << ']'
710 << " x[" << cmd.x << ']'
711 << " y[" << cmd.y << ']'
712 << " button[" << cmd.button() << ']'
715 LCursor & cur = cursor_;
717 switch (cmd.action) {
721 cur.message(_("Undo"));
722 cur.clearSelection();
723 if (!textUndo(*this))
724 cur.message(_("No further undo information"));
732 cur.message(_("Redo"));
733 cur.clearSelection();
734 if (!textRedo(*this))
735 cur.message(_("No further redo information"));
741 case LFUN_FILE_INSERT:
742 // FIXME: We don't know the encoding of filenames
743 menuInsertLyXFile(lyx::to_utf8(cmd.argument()));
746 case LFUN_FILE_INSERT_ASCII_PARA:
747 // FIXME: We don't know the encoding of filenames
748 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), true);
751 case LFUN_FILE_INSERT_ASCII:
752 // FIXME: We don't know the encoding of filenames
753 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), false);
756 case LFUN_FONT_STATE:
757 cur.message(lyx::from_utf8(cur.currentState()));
760 case LFUN_BOOKMARK_SAVE:
761 savePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
764 case LFUN_BOOKMARK_GOTO:
765 restorePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
768 case LFUN_LABEL_GOTO: {
769 docstring label = cmd.argument();
772 getInsetByCode<InsetRef>(cursor_,
773 InsetBase::REF_CODE);
775 label = lyx::from_utf8(inset->getContents());
785 case LFUN_PARAGRAPH_GOTO: {
786 int const id = convert<int>(lyx::to_utf8(cmd.argument()));
787 ParIterator par = buffer_->getParFromID(id);
788 if (par == buffer_->par_iterator_end()) {
789 lyxerr[Debug::INFO] << "No matching paragraph found! ["
790 << id << ']' << endl;
793 lyxerr[Debug::INFO] << "Paragraph " << par->id()
794 << " found." << endl;
798 setCursor(makeDocIterator(par, 0));
805 case LFUN_OUTLINE_UP:
806 lyx::toc::outline(lyx::toc::Up, cursor_);
807 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
808 updateLabels(*buffer_);
810 case LFUN_OUTLINE_DOWN:
811 lyx::toc::outline(lyx::toc::Down, cursor_);
812 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
813 updateLabels(*buffer_);
815 case LFUN_OUTLINE_IN:
816 lyx::toc::outline(lyx::toc::In, cursor_);
817 updateLabels(*buffer_);
819 case LFUN_OUTLINE_OUT:
820 lyx::toc::outline(lyx::toc::Out, cursor_);
821 updateLabels(*buffer_);
825 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
828 case LFUN_REFERENCE_NEXT: {
829 vector<InsetBase_code> tmp;
830 tmp.push_back(InsetBase::LABEL_CODE);
831 tmp.push_back(InsetBase::REF_CODE);
832 bv_funcs::gotoInset(this, tmp, true);
836 case LFUN_CHANGES_TRACK:
837 buffer_->params().trackChanges = !buffer_->params().trackChanges;
840 case LFUN_CHANGES_OUTPUT: {
841 buffer_->params().outputChanges = !buffer_->params().outputChanges;
845 case LFUN_CHANGE_NEXT:
846 lyx::find::findNextChange(this);
849 case LFUN_CHANGES_MERGE:
850 if (lyx::find::findNextChange(this))
851 showDialog("changes");
854 case LFUN_ALL_CHANGES_ACCEPT: {
855 cursor_.reset(buffer_->inset());
857 #warning FIXME changes
859 while (lyx::find::findNextChange(this))
860 getLyXText()->acceptChange(cursor_);
865 case LFUN_ALL_CHANGES_REJECT: {
866 cursor_.reset(buffer_->inset());
868 #warning FIXME changes
870 while (lyx::find::findNextChange(this))
871 getLyXText()->rejectChange(cursor_);
876 lyx::find::find(this, cmd);
879 case LFUN_WORD_REPLACE:
880 lyx::find::replace(this, cmd);
884 cur.clearSelection();
886 cur.message(lyx::from_utf8(N_("Mark off")));
890 cur.clearSelection();
893 cur.message(lyx::from_utf8(N_("Mark on")));
896 case LFUN_MARK_TOGGLE:
897 cur.clearSelection();
900 cur.message(lyx::from_utf8(N_("Mark removed")));
903 cur.message(lyx::from_utf8(N_("Mark set")));
908 case LFUN_SCREEN_RECENTER:
912 case LFUN_BIBTEX_DATABASE_ADD: {
913 LCursor tmpcur = cursor_;
914 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
915 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
916 InsetBase::BIBTEX_CODE);
918 if (inset->addDatabase(lyx::to_utf8(cmd.argument())))
919 buffer_->updateBibfilesCache();
924 case LFUN_BIBTEX_DATABASE_DEL: {
925 LCursor tmpcur = cursor_;
926 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
927 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
928 InsetBase::BIBTEX_CODE);
930 if (inset->delDatabase(lyx::to_utf8(cmd.argument())))
931 buffer_->updateBibfilesCache();
936 case LFUN_WORDS_COUNT: {
937 DocIterator from, to;
938 if (cur.selection()) {
939 from = cur.selectionBegin();
940 to = cur.selectionEnd();
942 from = doc_iterator_begin(buffer_->inset());
943 to = doc_iterator_end(buffer_->inset());
945 int const count = countWords(from, to);
949 message = bformat(_("%1$d words in selection."),
952 message = bformat(_("%1$d words in document."),
957 message = _("One word in selection.");
959 message = _("One word in document.");
962 Alert::information(_("Count words"), message);
966 case LFUN_BUFFER_TOGGLE_COMPRESSION:
967 // turn compression on/off
968 buffer_->params().compressed = !buffer_->params().compressed;
971 case LFUN_NEXT_INSET_TOGGLE: {
972 // this is the real function we want to invoke
973 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
974 // if there is an inset at cursor, see whether it
976 InsetBase * inset = cur.nextInset();
977 if (inset && inset->isActive()) {
978 LCursor tmpcur = cur;
979 tmpcur.pushLeft(*inset);
980 inset->dispatch(tmpcur, tmpcmd);
981 if (tmpcur.result().dispatched()) {
985 // if it did not work, try the underlying inset.
986 if (!cur.result().dispatched())
987 cur.dispatch(tmpcmd);
989 if (cur.result().dispatched())
990 cur.clearSelection();
1003 docstring const BufferView::requestSelection()
1008 LCursor & cur = cursor_;
1010 if (!cur.selection()) {
1011 xsel_cache_.set = false;
1015 if (!xsel_cache_.set ||
1016 cur.top() != xsel_cache_.cursor ||
1017 cur.anchor_.top() != xsel_cache_.anchor)
1019 xsel_cache_.cursor = cur.top();
1020 xsel_cache_.anchor = cur.anchor_.top();
1021 xsel_cache_.set = cur.selection();
1022 return cur.selectionAsString(false);
1028 void BufferView::clearSelection()
1031 cursor_.clearSelection();
1032 xsel_cache_.set = false;
1037 void BufferView::workAreaResize(int width, int height)
1039 bool const widthChange = width != width_;
1040 bool const heightChange = height != height_;
1042 // Update from work area
1046 if (buffer_ && widthChange) {
1047 // The WorkArea content needs a resize
1051 if (widthChange || heightChange)
1056 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1058 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1060 // This is only called for mouse related events including
1061 // LFUN_FILE_OPEN generated by drag-and-drop.
1062 FuncRequest cmd = cmd0;
1068 cur.push(buffer_->inset());
1069 cur.selection() = cursor_.selection();
1071 // Doesn't go through lyxfunc, so we need to update
1072 // the layout choice etc. ourselves
1074 // E.g. Qt mouse press when no buffer
1078 // Either the inset under the cursor or the
1079 // surrounding LyXText will handle this event.
1081 // Build temporary cursor.
1082 cmd.y = min(max(cmd.y, -1), height_);
1083 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1084 //lyxerr << BOOST_CURRENT_FUNCTION
1085 // << " * hit inset at tip: " << inset << endl;
1086 //lyxerr << BOOST_CURRENT_FUNCTION
1087 // << " * created temp cursor:" << cur << endl;
1089 // Put anchor at the same position.
1092 // Try to dispatch to an non-editable inset near this position
1093 // via the temp cursor. If the inset wishes to change the real
1094 // cursor it has to do so explicitly by using
1095 // cur.bv().cursor() = cur; (or similar)
1097 inset->dispatch(cur, cmd);
1099 // Now dispatch to the temporary cursor. If the real cursor should
1100 // be modified, the inset's dispatch has to do so explicitly.
1101 if (!cur.result().dispatched())
1104 if (cur.result().dispatched()) {
1105 // Redraw if requested or necessary.
1106 if (cur.result().update())
1107 update(Update::FitCursor | Update::Force);
1109 update(Update::FitCursor | Update::MultiParSel);
1116 void BufferView::scroll(int /*lines*/)
1121 // LyXText const * t = &buffer_->text();
1122 // int const line_height = defaultRowHeight();
1124 // // The new absolute coordinate
1125 // int new_top_y = top_y() + lines * line_height;
1127 // // Restrict to a valid value
1128 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1129 // new_top_y = std::max(0, new_top_y);
1131 // scrollDocView(new_top_y);
1133 // // Update the scrollbar.
1134 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1138 void BufferView::setCursorFromRow(int row)
1143 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1146 buffer_->text().setCursor(cursor_, 0, 0);
1148 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1152 void BufferView::gotoLabel(docstring const & label)
1154 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1155 vector<docstring> labels;
1156 it->getLabelList(*buffer_, labels);
1157 if (find(labels.begin(),labels.end(),label) != labels.end()) {
1166 LyXText * BufferView::getLyXText()
1168 LyXText * text = cursor_.innerText();
1174 LyXText const * BufferView::getLyXText() const
1176 LyXText const * text = cursor_.innerText();
1182 int BufferView::workHeight() const
1188 void BufferView::setCursor(DocIterator const & dit)
1190 size_t const n = dit.depth();
1191 for (size_t i = 0; i < n; ++i)
1192 dit[i].inset().edit(cursor_, true);
1194 cursor_.setCursor(dit);
1195 cursor_.selection() = false;
1199 void BufferView::mouseSetCursor(LCursor & cur)
1201 BOOST_ASSERT(&cur.bv() == this);
1203 // Has the cursor just left the inset?
1204 bool badcursor = false;
1205 if (&cursor_.inset() != &cur.inset())
1206 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1208 // do the dEPM magic if needed
1209 // FIXME: move this to InsetText::notifyCursorLeaves?
1210 if (!badcursor && cursor_.inTexted())
1211 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1214 cursor_.clearSelection();
1215 cursor_.setTargetX();
1221 void BufferView::putSelectionAt(DocIterator const & cur,
1222 int length, bool backwards)
1224 cursor_.clearSelection();
1230 cursor_.pos() += length;
1231 cursor_.setSelection(cursor_, -length);
1233 cursor_.setSelection(cursor_, length);
1238 LCursor & BufferView::cursor()
1244 LCursor const & BufferView::cursor() const
1250 lyx::pit_type BufferView::anchor_ref() const
1256 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1258 return metrics_info_;
1262 void BufferView::updateMetrics(bool singlepar)
1264 // FIXME (Abdel 19/10/2006):
1265 // There's something fishy in tabular. The coord_cache_ is not
1266 // correctly reconstructed when a character is trying to be inserted.
1267 // Not clearing out the coord_cache_ fixes the crash but there is a
1268 // bad side effect: buffer-begin and buffer-end do not update the screen.
1270 // Remove old position cache
1271 coord_cache_.clear();
1273 LyXText & buftext = buffer_->text();
1274 lyx::pit_type size = int(buftext.paragraphs().size());
1276 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1277 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1281 lyx::pit_type const pit = anchor_ref_;
1284 size_t const npit = buftext.paragraphs().size();
1286 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1287 // the (main text, not inset!) paragraph containing the cursor.
1288 // (if this paragraph contains insets etc., rebreaking will
1289 // recursively descend)
1290 if (!singlepar || pit == cursor_.bottom().pit())
1291 buftext.redoParagraph(pit);
1292 int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1294 // Redo paragraphs above anchor if necessary; again, in Single Par
1295 // mode, only if we encounter the (main text) one having the cursor.
1297 while (y1 > 0 && pit1 > 0) {
1298 y1 -= buftext.getPar(pit1).ascent();
1300 if (!singlepar || pit1 == cursor_.bottom().pit())
1301 buftext.redoParagraph(pit1);
1302 y1 -= buftext.getPar(pit1).descent();
1306 // Take care of ascent of first line
1307 y1 -= buftext.getPar(pit1).ascent();
1309 // Normalize anchor for next time
1313 // Grey at the beginning is ugly
1314 if (pit1 == 0 && y1 > 0) {
1320 // Redo paragraphs below the anchor if necessary. Single par mode:
1321 // only the one containing the cursor if encountered.
1323 while (y2 < height_ && pit2 < int(npit) - 1) {
1324 y2 += buftext.getPar(pit2).descent();
1326 if (!singlepar || pit2 == cursor_.bottom().pit())
1327 buftext.redoParagraph(pit2);
1328 y2 += buftext.getPar(pit2).ascent();
1331 // Take care of descent of last line
1332 y2 += buftext.getPar(pit2).descent();
1334 // The coordinates of all these paragraphs are correct, cache them
1336 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1337 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1338 Paragraph const & par = buftext.getPar(pit);
1340 parPos[pit] = Point(0, y);
1341 if (singlepar && pit == cursor_.bottom().pit()) {
1342 // In Single Paragraph mode, collect here the
1343 // y1 and y2 of the (one) paragraph the cursor is in
1344 y1 = y - par.ascent();
1345 y2 = y + par.descent();
1351 // collect cursor paragraph iter bounds
1352 pit1 = cursor_.bottom().pit();
1353 pit2 = cursor_.bottom().pit();
1356 lyxerr[Debug::DEBUG]
1357 << BOOST_CURRENT_FUNCTION
1360 << " pit1: " << pit1
1361 << " pit2: " << pit2
1362 << " npit: " << npit
1363 << " singlepar: " << singlepar
1367 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1371 void BufferView::menuInsertLyXFile(string const & filenm)
1373 BOOST_ASSERT(cursor_.inTexted());
1374 string filename = filenm;
1376 if (filename.empty()) {
1377 // Launch a file browser
1379 string initpath = lyxrc.document_path;
1382 string const trypath = buffer_->filePath();
1383 // If directory is writeable, use this as default.
1384 if (isDirWriteable(trypath))
1389 FileDialog fileDlg(_("Select LyX document to insert"),
1391 make_pair(_("Documents|#o#O"), lyx::from_utf8(lyxrc.document_path)),
1392 make_pair(_("Examples|#E#e"), lyx::from_utf8(addPath(package().system_support(), "examples"))));
1394 FileDialog::Result result =
1395 fileDlg.open(lyx::from_utf8(initpath),
1396 FileFilterList(_("LyX Documents (*.lyx)")),
1399 if (result.first == FileDialog::Later)
1403 filename = lyx::to_utf8(result.second);
1405 // check selected filename
1406 if (filename.empty()) {
1407 // emit message signal.
1408 message(_("Canceled."));
1413 // Get absolute path of file and add ".lyx"
1414 // to the filename if necessary
1415 filename = fileSearch(string(), filename, "lyx");
1417 docstring const disp_fn = makeDisplayPath(filename);
1418 // emit message signal.
1419 message(bformat(_("Inserting document %1$s..."), disp_fn));
1422 Buffer buf("", false);
1423 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
1424 ErrorList & el = buffer_->errorList("Parse");
1425 // Copy the inserted document error list into the current buffer one.
1426 el = buf.errorList("Parse");
1427 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
1428 buf.params().textclass, el);
1429 res = _("Document %1$s inserted.");
1431 res = _("Could not insert document %1$s");
1433 // emit message signal.
1434 message(bformat(res, disp_fn));
1435 buffer_->errors("Parse");