]> git.lyx.org Git - lyx.git/blob - src/insets/InsetText.cpp
Stupid bug fix.
[lyx.git] / src / insets / InsetText.cpp
1 /**
2  * \file InsetText.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetText.h"
14
15 #include "insets/InsetOptArg.h"
16
17 #include "buffer_funcs.h"
18 #include "Buffer.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "CompletionList.h"
22 #include "CoordCache.h"
23 #include "Cursor.h"
24 #include "CutAndPaste.h"
25 #include "DispatchResult.h"
26 #include "ErrorList.h"
27 #include "FuncRequest.h"
28 #include "InsetList.h"
29 #include "Intl.h"
30 #include "Lexer.h"
31 #include "lyxfind.h"
32 #include "LyXRC.h"
33 #include "MetricsInfo.h"
34 #include "output_docbook.h"
35 #include "output_latex.h"
36 #include "OutputParams.h"
37 #include "output_plaintext.h"
38 #include "paragraph_funcs.h"
39 #include "Paragraph.h"
40 #include "ParagraphParameters.h"
41 #include "ParIterator.h"
42 #include "Row.h"
43 #include "sgml.h"
44 #include "TexRow.h"
45 #include "TextClass.h"
46 #include "Text.h"
47 #include "TextMetrics.h"
48 #include "TocBackend.h"
49
50 #include "frontends/alert.h"
51 #include "frontends/Painter.h"
52
53 #include "support/debug.h"
54 #include "support/gettext.h"
55 #include "support/lstrings.h"
56
57 #include <boost/bind.hpp>
58 #include "support/lassert.h"
59
60 using namespace std;
61 using namespace lyx::support;
62
63 using boost::bind;
64 using boost::ref;
65
66 namespace lyx {
67
68 using graphics::PreviewLoader;
69
70
71 /////////////////////////////////////////////////////////////////////
72
73 InsetText::InsetText(Buffer const & buf)
74         : drawFrame_(false), frame_color_(Color_insetframe)
75 {
76         initParagraphs(buf);
77 }
78
79
80 InsetText::InsetText(InsetText const & in)
81         : Inset(in), text_()
82 {
83         text_.autoBreakRows_ = in.text_.autoBreakRows_;
84         drawFrame_ = in.drawFrame_;
85         frame_color_ = in.frame_color_;
86         text_.paragraphs() = in.text_.paragraphs();
87         setParagraphOwner();
88 }
89
90
91 InsetText::InsetText()
92 {}
93
94
95 void InsetText::setBuffer(Buffer & buf)
96 {
97         ParagraphList::iterator end = paragraphs().end();
98         for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
99                 it->setBuffer(buf);
100         Inset::setBuffer(buf);
101 }
102
103
104 void InsetText::initParagraphs(Buffer const & buf)
105 {
106         LASSERT(paragraphs().empty(), /**/);
107         buffer_ = const_cast<Buffer *>(&buf);
108         paragraphs().push_back(Paragraph());
109         Paragraph & ourpar = paragraphs().back();
110         ourpar.setPlainOrDefaultLayout(buf.params().documentClass());
111         ourpar.setInsetOwner(this);
112 }
113
114 void InsetText::setParagraphOwner()
115 {
116         for_each(paragraphs().begin(), paragraphs().end(),
117                  bind(&Paragraph::setInsetOwner, _1, this));
118 }
119
120
121 void InsetText::clear()
122 {
123         ParagraphList & pars = paragraphs();
124         LASSERT(!pars.empty(), /**/);
125
126         // This is a gross hack...
127         Layout const & old_layout = pars.begin()->layout();
128
129         pars.clear();
130         pars.push_back(Paragraph());
131         pars.begin()->setInsetOwner(this);
132         pars.begin()->setLayout(old_layout);
133 }
134
135
136 Dimension const InsetText::dimension(BufferView const & bv) const
137 {
138         TextMetrics const & tm = bv.textMetrics(&text_);
139         Dimension dim = tm.dimension();
140         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
141         dim.des += TEXT_TO_INSET_OFFSET;
142         dim.asc += TEXT_TO_INSET_OFFSET;
143         return dim;
144 }
145
146
147 void InsetText::write(ostream & os) const
148 {
149         os << "Text\n";
150         text_.write(buffer(), os);
151 }
152
153
154 void InsetText::read(Lexer & lex)
155 {
156         clear();
157
158         // delete the initial paragraph
159         Paragraph oldpar = *paragraphs().begin();
160         paragraphs().clear();
161         ErrorList errorList;
162         lex.setContext("InsetText::read");
163         bool res = text_.read(buffer(), lex, errorList, this);
164
165         if (!res)
166                 lex.printError("Missing \\end_inset at this point. ");
167
168         // sanity check
169         // ensure we have at least one paragraph.
170         if (paragraphs().empty())
171                 paragraphs().push_back(oldpar);
172 }
173
174
175 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
176 {
177         TextMetrics & tm = mi.base.bv->textMetrics(&text_);
178
179         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
180
181         // Hand font through to contained lyxtext:
182         tm.font_.fontInfo() = mi.base.font;
183         mi.base.textwidth -= 2 * TEXT_TO_INSET_OFFSET;
184         if (hasFixedWidth())
185                 tm.metrics(mi, dim, mi.base.textwidth);
186         else
187                 tm.metrics(mi, dim);
188         mi.base.textwidth += 2 * TEXT_TO_INSET_OFFSET;
189         dim.asc += TEXT_TO_INSET_OFFSET;
190         dim.des += TEXT_TO_INSET_OFFSET;
191         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
192 }
193
194
195 void InsetText::draw(PainterInfo & pi, int x, int y) const
196 {
197         TextMetrics & tm = pi.base.bv->textMetrics(&text_);
198
199         if (drawFrame_ || pi.full_repaint) {
200                 int const w = tm.width() + TEXT_TO_INSET_OFFSET;
201                 int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
202                 int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
203                 int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
204                 if (pi.full_repaint)
205                         pi.pain.fillRectangle(xframe, yframe, w, h, backgroundColor());
206                 if (drawFrame_)
207                         pi.pain.rectangle(xframe, yframe, w, h, frameColor());
208         }
209         tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
210 }
211
212
213 docstring InsetText::editMessage() const
214 {
215         return _("Opened Text Inset");
216 }
217
218
219 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
220 {
221         pit_type const pit = front ? 0 : paragraphs().size() - 1;
222         pos_type pos = front ? 0 : paragraphs().back().size();
223
224         // if visual information is not to be ignored, move to extreme right/left
225         if (entry_from != ENTRY_DIRECTION_IGNORE) {
226                 Cursor temp_cur = cur;
227                 temp_cur.pit() = pit;
228                 temp_cur.pos() = pos;
229                 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
230                 pos = temp_cur.pos();
231         }
232
233         text_.setCursor(cur.top(), pit, pos);
234         cur.clearSelection();
235         cur.finishUndo();
236 }
237
238
239 Inset * InsetText::editXY(Cursor & cur, int x, int y)
240 {
241         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
242 }
243
244
245 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
246 {
247         LYXERR(Debug::ACTION, "InsetText::doDispatch()"
248                 << " [ cmd.action = " << cmd.action << ']');
249         text_.dispatch(cur, cmd);
250 }
251
252
253 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
254         FuncStatus & status) const
255 {
256         return text_.getStatus(cur, cmd, status);
257 }
258
259
260 void InsetText::setChange(Change const & change)
261 {
262         ParagraphList::iterator pit = paragraphs().begin();
263         ParagraphList::iterator end = paragraphs().end();
264         for (; pit != end; ++pit) {
265                 pit->setChange(change);
266         }
267 }
268
269
270 void InsetText::acceptChanges(BufferParams const & bparams)
271 {
272         text_.acceptChanges(bparams);
273 }
274
275
276 void InsetText::rejectChanges(BufferParams const & bparams)
277 {
278         text_.rejectChanges(bparams);
279 }
280
281
282 int InsetText::latex(odocstream & os, OutputParams const & runparams) const
283 {
284         TexRow texrow;
285         latexParagraphs(buffer(), text_, os, texrow, runparams);
286         return texrow.rows();
287 }
288
289
290 int InsetText::plaintext(odocstream & os, OutputParams const & runparams) const
291 {
292         ParagraphList::const_iterator beg = paragraphs().begin();
293         ParagraphList::const_iterator end = paragraphs().end();
294         ParagraphList::const_iterator it = beg;
295         bool ref_printed = false;
296         int len = 0;
297         for (; it != end; ++it) {
298                 if (it != beg) {
299                         os << '\n';
300                         if (runparams.linelen > 0)
301                                 os << '\n';
302                 }
303                 odocstringstream oss;
304                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed);
305                 docstring const str = oss.str();
306                 os << str;
307                 // FIXME: len is not computed fully correctly; in principle,
308                 // we have to count the characters after the last '\n'
309                 len = str.size();
310         }
311
312         return len;
313 }
314
315
316 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
317 {
318         docbookParagraphs(paragraphs(), buffer(), os, runparams);
319         return 0;
320 }
321
322
323 void InsetText::validate(LaTeXFeatures & features) const
324 {
325         for_each(paragraphs().begin(), paragraphs().end(),
326                  bind(&Paragraph::validate, _1, ref(features)));
327 }
328
329
330 void InsetText::cursorPos(BufferView const & bv,
331                 CursorSlice const & sl, bool boundary, int & x, int & y) const
332 {
333         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
334         y = bv.textMetrics(&text_).cursorY(sl, boundary);
335 }
336
337
338 bool InsetText::showInsetDialog(BufferView *) const
339 {
340         return false;
341 }
342
343
344 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
345 {
346         clear();
347         Paragraph & first = paragraphs().front();
348         for (unsigned int i = 0; i < data.length(); ++i)
349                 first.insertChar(i, data[i], font, trackChanges);
350 }
351
352
353 void InsetText::setAutoBreakRows(bool flag)
354 {
355         if (flag == text_.autoBreakRows_)
356                 return;
357
358         text_.autoBreakRows_ = flag;
359         if (flag)
360                 return;
361
362         // remove previously existing newlines
363         ParagraphList::iterator it = paragraphs().begin();
364         ParagraphList::iterator end = paragraphs().end();
365         for (; it != end; ++it)
366                 for (int i = 0; i < it->size(); ++i)
367                         if (it->isNewline(i))
368                                 // do not track the change, because the user
369                                 // is not allowed to revert/reject it
370                                 it->eraseChar(i, false);
371 }
372
373
374 void InsetText::setDrawFrame(bool flag)
375 {
376         drawFrame_ = flag;
377 }
378
379
380 ColorCode InsetText::frameColor() const
381 {
382         return frame_color_;
383 }
384
385
386 void InsetText::setFrameColor(ColorCode col)
387 {
388         frame_color_ = col;
389 }
390
391
392 void InsetText::appendParagraphs(ParagraphList & plist)
393 {
394         // There is little we can do here to keep track of changes.
395         // As of 2006/10/20, appendParagraphs is used exclusively by
396         // LyXTabular::setMultiColumn. In this context, the paragraph break
397         // is lost irreversibly and the appended text doesn't really change
398
399         ParagraphList & pl = paragraphs();
400
401         ParagraphList::iterator pit = plist.begin();
402         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
403         ++pit;
404         mergeParagraph(buffer().params(), pl,
405                        distance(pl.begin(), ins) - 1);
406
407         for_each(pit, plist.end(),
408                  bind(&ParagraphList::push_back, ref(pl), _1));
409 }
410
411
412 void InsetText::addPreview(PreviewLoader & loader) const
413 {
414         ParagraphList::const_iterator pit = paragraphs().begin();
415         ParagraphList::const_iterator pend = paragraphs().end();
416
417         for (; pit != pend; ++pit) {
418                 InsetList::const_iterator it  = pit->insetList().begin();
419                 InsetList::const_iterator end = pit->insetList().end();
420                 for (; it != end; ++it)
421                         it->inset->addPreview(loader);
422         }
423 }
424
425
426 ParagraphList const & InsetText::paragraphs() const
427 {
428         return text_.paragraphs();
429 }
430
431
432 ParagraphList & InsetText::paragraphs()
433 {
434         return text_.paragraphs();
435 }
436
437
438 void InsetText::updateLabels(ParIterator const & it)
439 {
440         ParIterator it2 = it;
441         it2.forwardPos();
442         LASSERT(&it2.inset() == this && it2.pit() == 0, /**/);
443         if (producesOutput())
444                 lyx::updateLabels(buffer(), it2);
445         else {
446                 DocumentClass const & tclass = buffer().params().documentClass();
447                 Counters const savecnt = tclass.counters();
448                 lyx::updateLabels(buffer(), it2);
449                 tclass.counters() = savecnt;
450         }
451 }
452
453
454 void InsetText::addToToc(DocIterator const & cdit)
455 {
456         DocIterator dit = cdit;
457         dit.push_back(CursorSlice(*this));
458         Toc & toc = buffer().tocBackend().toc("tableofcontents");
459
460         BufferParams const & bufparams = buffer_->params();
461         const int min_toclevel = bufparams.documentClass().min_toclevel();
462
463         // For each paragraph, traverse its insets and let them add
464         // their toc items
465         ParagraphList & pars = paragraphs();
466         pit_type pend = paragraphs().size();
467         for (pit_type pit = 0; pit != pend; ++pit) {
468                 Paragraph const & par = pars[pit];
469                 dit.pit() = pit;
470                 // the string that goes to the toc (could be the optarg)
471                 docstring tocstring;
472                 InsetList::const_iterator it  = par.insetList().begin();
473                 InsetList::const_iterator end = par.insetList().end();
474                 for (; it != end; ++it) {
475                         Inset & inset = *it->inset;
476                         dit.pos() = it->pos;
477                         //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
478                         inset.addToToc(dit);
479                         switch (inset.lyxCode()) {
480                         case OPTARG_CODE: {
481                                 if (!tocstring.empty())
482                                         break;
483                                 dit.pos() = 0;
484                                 Paragraph const & insetpar =
485                                         *static_cast<InsetOptArg&>(inset).paragraphs().begin();
486                                 if (!par.labelString().empty())
487                                         tocstring = par.labelString() + ' ';
488                                 tocstring += insetpar.asString();
489                                 break;
490                         }
491                         default:
492                                 break;
493                         }
494                 }
495                 /// now the toc entry for the paragraph
496                 int const toclevel = par.layout().toclevel;
497                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
498                         dit.pos() = 0;
499                         // insert this into the table of contents
500                         if (tocstring.empty())
501                                 tocstring = par.asString(AS_STR_LABEL);
502                         toc.push_back(TocItem(dit, toclevel - min_toclevel, tocstring));
503                 }
504         }
505 }
506
507
508 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
509 {
510         if (cur.buffer().isClean())
511                 return Inset::notifyCursorLeaves(old, cur);
512         
513         // find text inset in old cursor
514         Cursor insetCur = old;
515         int scriptSlice = insetCur.find(this);
516         LASSERT(scriptSlice != -1, /**/);
517         insetCur.cutOff(scriptSlice);
518         LASSERT(&insetCur.inset() == this, /**/);
519         
520         // update the old paragraph's words
521         insetCur.paragraph().updateWords(insetCur.top());
522         
523         return Inset::notifyCursorLeaves(old, cur);
524 }
525
526
527 bool InsetText::completionSupported(Cursor const & cur) const
528 {
529         Cursor const & bvCur = cur.bv().cursor();
530         if (&bvCur.inset() != this)
531                 return false;
532         return text_.completionSupported(cur);
533 }
534
535
536 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
537 {
538         return completionSupported(cur);
539 }
540
541
542 bool InsetText::automaticInlineCompletion() const
543 {
544         return lyxrc.completion_inline_text;
545 }
546
547
548 bool InsetText::automaticPopupCompletion() const
549 {
550         return lyxrc.completion_popup_text;
551 }
552
553
554 bool InsetText::showCompletionCursor() const
555 {
556         return lyxrc.completion_cursor_text;
557 }
558
559
560 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
561 {
562         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
563 }
564
565
566 docstring InsetText::completionPrefix(Cursor const & cur) const
567 {
568         if (!completionSupported(cur))
569                 return docstring();
570         return text_.completionPrefix(cur);
571 }
572
573
574 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
575         bool finished)
576 {
577         if (!completionSupported(cur))
578                 return false;
579
580         return text_.insertCompletion(cur, s, finished);
581 }
582
583
584 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y, 
585         Dimension & dim) const
586 {
587         TextMetrics const & tm = cur.bv().textMetrics(&text_);
588         tm.completionPosAndDim(cur, x, y, dim);
589 }
590
591
592 docstring InsetText::contextMenu(BufferView const &, int, int) const
593 {
594         return from_ascii("context-edit");
595 }
596
597
598 } // namespace lyx