]> git.lyx.org Git - lyx.git/blob - src/buffer_funcs.cpp
Restor 1.4.x behaviour: Don't touch the preamble QTextEdit if the preamble text is...
[lyx.git] / src / buffer_funcs.cpp
1 /**
2  * \file buffer_funcs.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Alfredo Braunstein
8  *
9  * Full author contact details are available in file CREDITS.
10  *
11  */
12
13 #include <config.h>
14
15 #include "buffer_funcs.h"
16 #include "Buffer.h"
17 #include "BufferList.h"
18 #include "BufferParams.h"
19 #include "DocIterator.h"
20 #include "Counters.h"
21 #include "ErrorList.h"
22 #include "Floating.h"
23 #include "FloatList.h"
24 #include "gettext.h"
25 #include "Language.h"
26 #include "LaTeX.h"
27 #include "TextClass.h"
28 #include "Paragraph.h"
29 #include "paragraph_funcs.h"
30 #include "ParagraphList.h"
31 #include "ParagraphParameters.h"
32 #include "ParIterator.h"
33 #include "LyXVC.h"
34 #include "TexRow.h"
35 #include "TocBackend.h"
36 #include "VCBackend.h"
37
38 #include "frontends/alert.h"
39
40 #include "insets/InsetBibitem.h"
41 #include "insets/InsetCaption.h"
42 #include "insets/InsetInclude.h"
43 #include "insets/InsetTabular.h"
44
45 #include "support/filetools.h"
46 #include "support/fs_extras.h"
47 #include "support/lyxlib.h"
48
49 #include <boost/bind.hpp>
50 #include <boost/filesystem/operations.hpp>
51
52
53 namespace lyx {
54
55 using namespace std;
56
57 using support::bformat;
58 using support::FileName;
59 using support::libFileSearch;
60 using support::makeAbsPath;
61 using support::makeDisplayPath;
62 using support::onlyFilename;
63 using support::onlyPath;
64 using support::unlink;
65
66 using std::min;
67 using std::string;
68
69 namespace Alert = frontend::Alert;
70 namespace fs = boost::filesystem;
71
72 namespace {
73
74 bool readFile(Buffer * const b, FileName const & s)
75 {
76         BOOST_ASSERT(b);
77
78         // File information about normal file
79         if (!fs::exists(s.toFilesystemEncoding())) {
80                 docstring const file = makeDisplayPath(s.absFilename(), 50);
81                 docstring text = bformat(_("The specified document\n%1$s"
82                                                      "\ncould not be read."), file);
83                 Alert::error(_("Could not read document"), text);
84                 return false;
85         }
86
87         // Check if emergency save file exists and is newer.
88         FileName const e(s.absFilename() + ".emergency");
89
90         if (fs::exists(e.toFilesystemEncoding()) &&
91             fs::exists(s.toFilesystemEncoding()) &&
92             fs::last_write_time(e.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
93         {
94                 docstring const file = makeDisplayPath(s.absFilename(), 20);
95                 docstring const text =
96                         bformat(_("An emergency save of the document "
97                                   "%1$s exists.\n\n"
98                                                "Recover emergency save?"), file);
99                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
100                                       _("&Recover"),  _("&Load Original"),
101                                       _("&Cancel")))
102                 {
103                 case 0:
104                         // the file is not saved if we load the emergency file.
105                         b->markDirty();
106                         return b->readFile(e);
107                 case 1:
108                         break;
109                 default:
110                         return false;
111                 }
112         }
113
114         // Now check if autosave file is newer.
115         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
116
117         if (fs::exists(a.toFilesystemEncoding()) &&
118             fs::exists(s.toFilesystemEncoding()) &&
119             fs::last_write_time(a.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
120         {
121                 docstring const file = makeDisplayPath(s.absFilename(), 20);
122                 docstring const text =
123                         bformat(_("The backup of the document "
124                                   "%1$s is newer.\n\nLoad the "
125                                                "backup instead?"), file);
126                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
127                                       _("&Load backup"), _("Load &original"),
128                                       _("&Cancel") ))
129                 {
130                 case 0:
131                         // the file is not saved if we load the autosave file.
132                         b->markDirty();
133                         return b->readFile(a);
134                 case 1:
135                         // Here we delete the autosave
136                         unlink(a);
137                         break;
138                 default:
139                         return false;
140                 }
141         }
142         return b->readFile(s);
143 }
144
145
146 } // namespace anon
147
148
149
150 bool loadLyXFile(Buffer * b, FileName const & s)
151 {
152         BOOST_ASSERT(b);
153
154         if (fs::is_readable(s.toFilesystemEncoding())) {
155                 if (readFile(b, s)) {
156                         b->lyxvc().file_found_hook(s);
157                         if (!fs::is_writable(s.toFilesystemEncoding()))
158                                 b->setReadonly(true);
159                         return true;
160                 }
161         } else {
162                 docstring const file = makeDisplayPath(s.absFilename(), 20);
163                 // Here we probably should run
164                 if (LyXVC::file_not_found_hook(s)) {
165                         docstring const text =
166                                 bformat(_("Do you want to retrieve the document"
167                                                        " %1$s from version control?"), file);
168                         int const ret = Alert::prompt(_("Retrieve from version control?"),
169                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
170
171                         if (ret == 0) {
172                                 // How can we know _how_ to do the checkout?
173                                 // With the current VC support it has to be,
174                                 // a RCS file since CVS do not have special ,v files.
175                                 RCS::retrieve(s);
176                                 return loadLyXFile(b, s);
177                         }
178                 }
179         }
180         return false;
181 }
182
183 // FIXME newFile() should probably be a member method of Application...
184 Buffer * newFile(string const & filename, string const & templatename,
185                  bool const isNamed)
186 {
187         // get a free buffer
188         Buffer * b = theBufferList().newBuffer(filename);
189         BOOST_ASSERT(b);
190
191         FileName tname;
192         // use defaults.lyx as a default template if it exists.
193         if (templatename.empty())
194                 tname = libFileSearch("templates", "defaults.lyx");
195         else
196                 tname = makeAbsPath(templatename);
197
198         if (!tname.empty()) {
199                 if (!b->readFile(tname)) {
200                         docstring const file = makeDisplayPath(tname.absFilename(), 50);
201                         docstring const text  = bformat(
202                                 _("The specified document template\n%1$s\ncould not be read."),
203                                 file);
204                         Alert::error(_("Could not read template"), text);
205                         theBufferList().release(b);
206                         return 0;
207                 }
208         }
209
210         if (!isNamed) {
211                 b->setUnnamed();
212                 b->setFileName(filename);
213         }
214
215         b->setReadonly(false);
216         b->fully_loaded(true);
217
218         return b;
219 }
220
221
222 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
223                                   ErrorList & errorList)
224 {
225         TeXErrors::Errors::const_iterator cit = terr.begin();
226         TeXErrors::Errors::const_iterator end = terr.end();
227
228         for (; cit != end; ++cit) {
229                 int id_start = -1;
230                 int pos_start = -1;
231                 int errorrow = cit->error_in_line;
232                 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
233                                                        pos_start);
234                 int id_end = -1;
235                 int pos_end = -1;
236                 do {
237                         ++errorrow;
238                         found = buf.texrow().getIdFromRow(errorrow, id_end,
239                                                           pos_end);
240                 } while (found && id_start == id_end && pos_start == pos_end);
241
242                 errorList.push_back(ErrorItem(cit->error_desc,
243                         cit->error_text, id_start, pos_start, pos_end));
244         }
245 }
246
247
248 string const bufferFormat(Buffer const & buffer)
249 {
250         if (buffer.isDocBook())
251                 return "docbook";
252         else if (buffer.isLiterate())
253                 return "literate";
254         else
255                 return "latex";
256 }
257
258
259 int countWords(DocIterator const & from, DocIterator const & to)
260 {
261         int count = 0;
262         bool inword = false;
263         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
264                 // Copied and adapted from isLetter() in ControlSpellChecker
265                 if (dit.inTexted()
266                     && dit.pos() != dit.lastpos()
267                     && dit.paragraph().isLetter(dit.pos())
268                     && !dit.paragraph().isDeleted(dit.pos())) {
269                         if (!inword) {
270                                 ++count;
271                                 inword = true;
272                         }
273                 } else if (inword)
274                         inword = false;
275         }
276
277         return count;
278 }
279
280
281 namespace {
282
283 depth_type getDepth(DocIterator const & it)
284 {
285         depth_type depth = 0;
286         for (size_t i = 0 ; i < it.depth() ; ++i)
287                 if (!it[i].inset().inMathed())
288                         depth += it[i].paragraph().getDepth() + 1;
289         // remove 1 since the outer inset does not count
290         return depth - 1;
291 }
292
293 depth_type getItemDepth(ParIterator const & it)
294 {
295         Paragraph const & par = *it;
296         LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
297
298         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
299                 return 0;
300
301         // this will hold the lowest depth encountered up to now.
302         depth_type min_depth = getDepth(it);
303         ParIterator prev_it = it;
304         while (true) {
305                 if (prev_it.pit())
306                         --prev_it.top().pit();
307                 else {
308                         // start of nested inset: go to outer par
309                         prev_it.pop_back();
310                         if (prev_it.empty()) {
311                                 // start of document: nothing to do
312                                 return 0;
313                         }
314                 }
315
316                 // We search for the first paragraph with same label
317                 // that is not more deeply nested.
318                 Paragraph & prev_par = *prev_it;
319                 depth_type const prev_depth = getDepth(prev_it);
320                 if (labeltype == prev_par.layout()->labeltype) {
321                         if (prev_depth < min_depth) {
322                                 return prev_par.itemdepth + 1;
323                         }
324                         else if (prev_depth == min_depth) {
325                                 return prev_par.itemdepth;
326                         }
327                 }
328                 min_depth = std::min(min_depth, prev_depth);
329                 // small optimization: if we are at depth 0, we won't
330                 // find anything else
331                 if (prev_depth == 0) {
332                         return 0;
333                 }
334         }
335 }
336
337
338 bool needEnumCounterReset(ParIterator const & it)
339 {
340         Paragraph const & par = *it;
341         BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
342         depth_type const cur_depth = par.getDepth();
343         ParIterator prev_it = it;
344         while (prev_it.pit()) {
345                 --prev_it.top().pit();
346                 Paragraph const & prev_par = *prev_it;
347                 if (prev_par.getDepth() <= cur_depth)
348                         return  prev_par.layout()->labeltype != LABEL_ENUMERATE;
349         }
350         // start of nested inset: reset
351         return true;
352 }
353
354
355 void setCaptionLabels(Inset & inset, string const & type,
356                 docstring const label, Counters & counters)
357 {
358         Text * text = inset.getText(0);
359         if (!text)
360                 return;
361
362         ParagraphList & pars = text->paragraphs();
363         if (pars.empty())
364                 return;
365
366         docstring const counter = from_ascii(type);
367
368         ParagraphList::iterator p = pars.begin();
369         for (; p != pars.end(); ++p) {
370                 InsetList::iterator it2 = p->insetlist.begin();
371                 InsetList::iterator end2 = p->insetlist.end();
372                 // Any caption within this float should have the same
373                 // label prefix but different numbers.
374                 for (; it2 != end2; ++it2) {
375                         Inset & icap = *it2->inset;
376                         // Look deeper just in case.
377                         setCaptionLabels(icap, type, label, counters);
378                         if (icap.lyxCode() == Inset::CAPTION_CODE) {
379                                 // We found a caption!
380                                 counters.step(counter); 
381                                 int number = counters.value(counter);
382                                 InsetCaption & ic = static_cast<InsetCaption &>(icap);
383                                 ic.setType(type);
384                                 ic.setCount(number);
385                                 ic.setCustomLabel(label);
386                         }
387                 }
388         }
389 }
390
391
392 void setCaptions(Paragraph & par, TextClass const & textclass)
393 {
394         if (par.insetlist.empty())
395                 return;
396
397         Counters & counters = textclass.counters();
398
399         InsetList::iterator it = par.insetlist.begin();
400         InsetList::iterator end = par.insetlist.end();
401         for (; it != end; ++it) {
402                 Inset & inset = *it->inset;
403                 if (inset.lyxCode() == Inset::FLOAT_CODE 
404                         || inset.lyxCode() == Inset::WRAP_CODE) {
405                         docstring const name = inset.name();
406                         if (name.empty())
407                                 continue;
408
409                         Floating const & fl = textclass.floats().getType(to_ascii(name));
410                         // FIXME UNICODE
411                         string const & type = fl.type();
412                         docstring const label = from_utf8(fl.name());
413                         setCaptionLabels(inset, type, label, counters);
414                 }
415                 else if (inset.lyxCode() == Inset::TABULAR_CODE
416                         &&  static_cast<InsetTabular &>(inset).tabular.isLongTabular()) {
417                         // FIXME: are "table" and "Table" the correct type and label?
418                         setCaptionLabels(inset, "table", from_ascii("Table"), counters);
419                 }
420         }
421 }
422
423 // set the label of a paragraph. This includes the counters.
424 void setLabel(Buffer const & buf, ParIterator & it, TextClass const & textclass)
425 {
426         Paragraph & par = *it;
427         Layout_ptr const & layout = par.layout();
428         Counters & counters = textclass.counters();
429
430         if (it.pit() == 0) {
431                 par.params().appendix(par.params().startOfAppendix());
432         } else {
433                 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
434                 if (!par.params().appendix() &&
435                     par.params().startOfAppendix()) {
436                         par.params().appendix(true);
437                         textclass.counters().reset();
438                 }
439         }
440
441         // Compute the item depth of the paragraph
442         par.itemdepth = getItemDepth(it);
443
444         if (layout->margintype == MARGIN_MANUAL) {
445                 if (par.params().labelWidthString().empty())
446                         par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
447         } else {
448                 par.params().labelWidthString(docstring());
449         }
450
451         // Optimisation: setLabel() can be called for each for each
452         // paragraph of the document. So we make the string static to
453         // avoid the repeated instanciation.
454         static docstring itemlabel;
455
456         // is it a layout that has an automatic label?
457         if (layout->labeltype == LABEL_COUNTER) {
458                 if (layout->toclevel <= buf.params().secnumdepth
459                     && (layout->latextype != LATEX_ENVIRONMENT
460                         || isFirstInSequence(it.pit(), it.plist()))) {
461                         counters.step(layout->counter);
462                         par.params().labelString(
463                                 par.expandLabel(layout, buf.params()));
464                 } else
465                         par.params().labelString(docstring());
466
467         } else if (layout->labeltype == LABEL_ITEMIZE) {
468                 // At some point of time we should do something more
469                 // clever here, like:
470                 //   par.params().labelString(
471                 //    buf.params().user_defined_bullet(par.itemdepth).getText());
472                 // for now, use a simple hardcoded label
473                 switch (par.itemdepth) {
474                 case 0:
475                         itemlabel = char_type(0x2022);
476                         break;
477                 case 1:
478                         itemlabel = char_type(0x2013);
479                         break;
480                 case 2:
481                         itemlabel = char_type(0x2217);
482                         break;
483                 case 3:
484                         itemlabel = char_type(0x2219); // or 0x00b7
485                         break;
486                 }
487                 par.params().labelString(itemlabel);
488
489         } else if (layout->labeltype == LABEL_ENUMERATE) {
490                 // FIXME
491                 // Yes I know this is a really, really! bad solution
492                 // (Lgb)
493                 docstring enumcounter = from_ascii("enum");
494
495                 switch (par.itemdepth) {
496                 case 2:
497                         enumcounter += 'i';
498                 case 1:
499                         enumcounter += 'i';
500                 case 0:
501                         enumcounter += 'i';
502                         break;
503                 case 3:
504                         enumcounter += "iv";
505                         break;
506                 default:
507                         // not a valid enumdepth...
508                         break;
509                 }
510
511                 // Maybe we have to reset the enumeration counter.
512                 if (needEnumCounterReset(it))
513                         counters.reset(enumcounter);
514
515                 counters.step(enumcounter);
516
517                 string format;
518
519                 switch (par.itemdepth) {
520                 case 0:
521                         format = N_("\\arabic{enumi}.");
522                         break;
523                 case 1:
524                         format = N_("(\\alph{enumii})");
525                         break;
526                 case 2:
527                         format = N_("\\roman{enumiii}.");
528                         break;
529                 case 3:
530                         format = N_("\\Alph{enumiv}.");
531                         break;
532                 default:
533                         // not a valid enumdepth...
534                         break;
535                 }
536
537                 par.params().labelString(counters.counterLabel(
538                         par.translateIfPossible(from_ascii(format), buf.params())));
539
540         } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
541                 counters.step(from_ascii("bibitem"));
542                 int number = counters.value(from_ascii("bibitem"));
543                 if (par.bibitem())
544                         par.bibitem()->setCounter(number);
545
546                 par.params().labelString(
547                         par.translateIfPossible(layout->labelstring(), buf.params()));
548                 // In biblio shouldn't be following counters but...
549         } else if (layout->labeltype == LABEL_SENSITIVE) {
550                 // Search for the first float or wrap inset in the iterator
551                 size_t i = it.depth();
552                 Inset * in = 0;
553                 while (i > 0) {
554                         --i;
555                         Inset::Code const code = it[i].inset().lyxCode();
556                         if (code == Inset::FLOAT_CODE ||
557                             code == Inset::WRAP_CODE) {
558                                 in = &it[i].inset();
559                                 break;
560                         }
561                 }
562                 // FIXME Can Inset::name() return an empty name for wide or
563                 // float insets? If not we can put the definition of type
564                 // inside the if (in) clause and use that instead of
565                 // if (!type.empty()).
566                 docstring type;
567                 if (in)
568                         type = in->name();
569
570                 if (!type.empty()) {
571                         Floating const & fl = textclass.floats().getType(to_ascii(type));
572                         // FIXME UNICODE
573                         counters.step(from_ascii(fl.type()));
574
575                         // Doesn't work... yet.
576                         par.params().labelString(par.translateIfPossible(
577                                 bformat(from_ascii("%1$s #:"), from_utf8(fl.name())),
578                                 buf.params()));
579                 } else {
580                         // par->SetLayout(0);
581                         par.params().labelString(par.translateIfPossible(
582                                 layout->labelstring(), buf.params()));
583                 }
584
585         } else if (layout->labeltype == LABEL_NO_LABEL)
586                 par.params().labelString(docstring());
587         else
588                 par.params().labelString(
589                         par.translateIfPossible(layout->labelstring(), buf.params()));
590 }
591
592 } // anon namespace
593
594
595 bool updateCurrentLabel(Buffer const & buf,
596         ParIterator & it)
597 {
598     if (it == par_iterator_end(buf.inset()))
599         return false;
600
601 //      if (it.lastpit == 0 && Text::isMainText(buf))
602 //              return false;
603
604         switch (it->layout()->labeltype) {
605
606         case LABEL_NO_LABEL:
607         case LABEL_MANUAL:
608         case LABEL_BIBLIO:
609         case LABEL_TOP_ENVIRONMENT:
610         case LABEL_CENTERED_TOP_ENVIRONMENT:
611         case LABEL_STATIC:
612         case LABEL_ITEMIZE:
613                 setLabel(buf, it, buf.params().getTextClass());
614                 return true;
615
616         case LABEL_SENSITIVE:
617         case LABEL_COUNTER:
618         // do more things with enumerate later
619         case LABEL_ENUMERATE:
620                 return false;
621         }
622
623         // This is dead code which get rid of a warning:
624         return true;
625 }
626
627
628 void updateLabels(Buffer const & buf,
629         ParIterator & from, ParIterator & to, bool childonly)
630 {
631         for (ParIterator it = from; it != to; ++it) {
632                 if (it.pit() > it.lastpit())
633                         return;
634                 if (!updateCurrentLabel (buf, it)) {
635                         updateLabels(buf, childonly);
636                         return;
637                 }
638         }
639 }
640
641
642 void updateLabels(Buffer const & buf, ParIterator & iter, bool childonly)
643 {
644         if (updateCurrentLabel(buf, iter))
645                 return;
646
647         updateLabels(buf, childonly);
648 }
649
650
651 void updateLabels(Buffer const & buf, bool childonly)
652 {
653         // Use the master text class also for child documents
654         TextClass const & textclass = buf.params().getTextClass();
655
656         if (!childonly) {
657                 // If this is a child document start with the master
658                 Buffer const * const master = buf.getMasterBuffer();
659                 if (master != &buf) {
660                         updateLabels(*master);
661                         return;
662                 }
663
664                 // start over the counters
665                 textclass.counters().reset();
666         }
667
668         ParIterator const end = par_iterator_end(buf.inset());
669
670         for (ParIterator it = par_iterator_begin(buf.inset()); it != end; ++it) {
671                 // reduce depth if necessary
672                 if (it.pit()) {
673                         Paragraph const & prevpar = it.plist()[it.pit() - 1];
674                         it->params().depth(min(it->params().depth(),
675                                                prevpar.getMaxDepthAfter()));
676                 } else
677                         it->params().depth(0);
678
679                 // set the counter for this paragraph
680                 setLabel(buf, it, textclass);
681
682                 // It is better to set the captions after setLabel because
683                 // the caption number might need the section number in the
684                 // future.
685                 setCaptions(*it, textclass);
686
687                 // Now included docs
688                 InsetList::const_iterator iit = it->insetlist.begin();
689                 InsetList::const_iterator end = it->insetlist.end();
690                 for (; iit != end; ++iit) {
691                         if (iit->inset->lyxCode() == Inset::INCLUDE_CODE)
692                                 static_cast<InsetInclude const *>(iit->inset)
693                                         ->updateLabels(buf);
694                 }
695         }
696
697         Buffer & cbuf = const_cast<Buffer &>(buf);
698         cbuf.tocBackend().update();
699         cbuf.structureChanged();
700 }
701
702
703 void checkBufferStructure(Buffer & buffer, ParIterator const & par_it)
704 {
705         if (par_it->layout()->labeltype == LABEL_COUNTER
706                 && par_it->layout()->toclevel != Layout::NOT_IN_TOC) {
707                 buffer.tocBackend().updateItem(par_it);
708                 buffer.structureChanged();
709         }
710 }
711
712 } // namespace lyx