]> git.lyx.org Git - lyx.git/blob - src/buffer_funcs.C
hopefully fix tex2lyx linking.
[lyx.git] / src / buffer_funcs.C
1 /**
2  * \file buffer_funcs.C
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 "lyxtextclass.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 "vc-backend.h"
37
38 #include "frontends/Alert.h"
39
40 #include "insets/insetbibitem.h"
41 #include "insets/insetinclude.h"
42
43 #include "support/filetools.h"
44 #include "support/fs_extras.h"
45 #include "support/lyxlib.h"
46
47 #include <boost/bind.hpp>
48 #include <boost/filesystem/operations.hpp>
49
50
51 namespace lyx {
52
53 using namespace std;
54
55 using support::bformat;
56 using support::libFileSearch;
57 using support::makeDisplayPath;
58 using support::onlyFilename;
59 using support::onlyPath;
60 using support::unlink;
61
62 using std::min;
63 using std::string;
64
65 namespace Alert = frontend::Alert;
66 namespace fs = boost::filesystem;
67
68 namespace {
69
70 bool readFile(Buffer * const b, string const & s)
71 {
72         BOOST_ASSERT(b);
73
74         // File information about normal file
75         if (!fs::exists(s)) {
76                 docstring const file = makeDisplayPath(s, 50);
77                 docstring text = bformat(_("The specified document\n%1$s"
78                                                      "\ncould not be read."), file);
79                 Alert::error(_("Could not read document"), text);
80                 return false;
81         }
82
83         // Check if emergency save file exists and is newer.
84         string const e = onlyPath(s) + onlyFilename(s) + ".emergency";
85
86         if (fs::exists(e) && fs::exists(s)
87             && fs::last_write_time(e) > fs::last_write_time(s))
88         {
89                 docstring const file = makeDisplayPath(s, 20);
90                 docstring const text =
91                         bformat(_("An emergency save of the document "
92                                   "%1$s exists.\n\n"
93                                                "Recover emergency save?"), file);
94                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
95                                       _("&Recover"),  _("&Load Original"),
96                                       _("&Cancel")))
97                 {
98                 case 0:
99                         // the file is not saved if we load the emergency file.
100                         b->markDirty();
101                         return b->readFile(e);
102                 case 1:
103                         break;
104                 default:
105                         return false;
106                 }
107         }
108
109         // Now check if autosave file is newer.
110         string const a = onlyPath(s) + '#' + onlyFilename(s) + '#';
111
112         if (fs::exists(a) && fs::exists(s)
113             && fs::last_write_time(a) > fs::last_write_time(s))
114         {
115                 docstring const file = makeDisplayPath(s, 20);
116                 docstring const text =
117                         bformat(_("The backup of the document "
118                                   "%1$s is newer.\n\nLoad the "
119                                                "backup instead?"), file);
120                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
121                                       _("&Load backup"), _("Load &original"),
122                                       _("&Cancel") ))
123                 {
124                 case 0:
125                         // the file is not saved if we load the autosave file.
126                         b->markDirty();
127                         return b->readFile(a);
128                 case 1:
129                         // Here we delete the autosave
130                         unlink(a);
131                         break;
132                 default:
133                         return false;
134                 }
135         }
136         return b->readFile(s);
137 }
138
139
140 } // namespace anon
141
142
143
144 bool loadLyXFile(Buffer * b, string const & s)
145 {
146         BOOST_ASSERT(b);
147
148         if (fs::is_readable(s)) {
149                 if (readFile(b, s)) {
150                         b->lyxvc().file_found_hook(s);
151                         if (!fs::is_writable(s))
152                                 b->setReadonly(true);
153                         return true;
154                 }
155         } else {
156                 docstring const file = makeDisplayPath(s, 20);
157                 // Here we probably should run
158                 if (LyXVC::file_not_found_hook(s)) {
159                         docstring const text =
160                                 bformat(_("Do you want to retrieve the document"
161                                                        " %1$s from version control?"), file);
162                         int const ret = Alert::prompt(_("Retrieve from version control?"),
163                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
164
165                         if (ret == 0) {
166                                 // How can we know _how_ to do the checkout?
167                                 // With the current VC support it has to be,
168                                 // a RCS file since CVS do not have special ,v files.
169                                 RCS::retrieve(s);
170                                 return loadLyXFile(b, s);
171                         }
172                 }
173         }
174         return false;
175 }
176
177 // FIXME newFile() should probably be a member method of Application...
178 Buffer * newFile(string const & filename, string const & templatename,
179                  bool const isNamed)
180 {
181         // get a free buffer
182         Buffer * b = theBufferList().newBuffer(filename);
183         BOOST_ASSERT(b);
184
185         string tname;
186         // use defaults.lyx as a default template if it exists.
187         if (templatename.empty())
188                 tname = libFileSearch("templates", "defaults.lyx");
189         else
190                 tname = templatename;
191
192         if (!tname.empty()) {
193                 if (!b->readFile(tname)) {
194                         docstring const file = makeDisplayPath(tname, 50);
195                         docstring const text  = bformat(
196                                 _("The specified document template\n%1$s\ncould not be read."),
197                                 file);
198                         Alert::error(_("Could not read template"), text);
199                         theBufferList().release(b);
200                         return 0;
201                 }
202         }
203
204         if (!isNamed) {
205                 b->setUnnamed();
206                 b->setFileName(filename);
207         }
208
209         b->setReadonly(false);
210         b->fully_loaded(true);
211         b->updateDocLang(b->params().language);
212
213         return b;
214 }
215
216
217 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
218                                   ErrorList & errorList)
219 {
220         TeXErrors::Errors::const_iterator cit = terr.begin();
221         TeXErrors::Errors::const_iterator end = terr.end();
222
223         for (; cit != end; ++cit) {
224                 int id_start = -1;
225                 int pos_start = -1;
226                 int errorrow = cit->error_in_line;
227                 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
228                                                        pos_start);
229                 int id_end = -1;
230                 int pos_end = -1;
231                 do {
232                         ++errorrow;
233                         found = buf.texrow().getIdFromRow(errorrow, id_end,
234                                                           pos_end);
235                 } while (found && id_start == id_end && pos_start == pos_end);
236
237                 errorList.push_back(ErrorItem(cit->error_desc,
238                         cit->error_text, id_start, pos_start, pos_end));
239         }
240 }
241
242
243 string const bufferFormat(Buffer const & buffer)
244 {
245         if (buffer.isDocBook())
246                 return "docbook";
247         else if (buffer.isLiterate())
248                 return "literate";
249         else
250                 return "latex";
251 }
252
253
254 int countWords(DocIterator const & from, DocIterator const & to)
255 {
256         int count = 0;
257         bool inword = false;
258         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
259                 // Copied and adapted from isLetter() in ControlSpellChecker
260                 if (dit.inTexted()
261                     && dit.pos() != dit.lastpos()
262                     && dit.paragraph().isLetter(dit.pos())
263                     && !dit.paragraph().isDeleted(dit.pos())) {
264                         if (!inword) {
265                                 ++count;
266                                 inword = true;
267                         }
268                 } else if (inword)
269                         inword = false;
270         }
271
272         return count;
273 }
274
275
276 namespace {
277
278 depth_type getDepth(DocIterator const & it)
279 {
280         depth_type depth = 0;
281         for (size_t i = 0 ; i < it.depth() ; ++i)
282                 if (!it[i].inset().inMathed())
283                         depth += it[i].paragraph().getDepth() + 1;
284         // remove 1 since the outer inset does not count
285         return depth - 1;
286 }
287
288 depth_type getItemDepth(ParIterator const & it)
289 {
290         Paragraph const & par = *it;
291         LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
292
293         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
294                 return 0;
295
296         // this will hold the lowest depth encountered up to now.
297         depth_type min_depth = getDepth(it);
298         ParIterator prev_it = it;
299         while (true) {
300                 if (prev_it.pit())
301                         --prev_it.top().pit();
302                 else {
303                         // start of nested inset: go to outer par
304                         prev_it.pop_back();
305                         if (prev_it.empty()) {
306                                 // start of document: nothing to do
307                                 return 0;
308                         }
309                 }
310
311                 // We search for the first paragraph with same label
312                 // that is not more deeply nested.
313                 Paragraph & prev_par = *prev_it;
314                 depth_type const prev_depth = getDepth(prev_it);
315                 if (labeltype == prev_par.layout()->labeltype) {
316                         if (prev_depth < min_depth) {
317                                 return prev_par.itemdepth + 1;
318                         }
319                         else if (prev_depth == min_depth) {
320                                 return prev_par.itemdepth;
321                         }
322                 }
323                 min_depth = std::min(min_depth, prev_depth);
324                 // small optimization: if we are at depth 0, we won't
325                 // find anything else
326                 if (prev_depth == 0) {
327                         return 0;
328                 }
329         }
330 }
331
332
333 bool needEnumCounterReset(ParIterator const & it)
334 {
335         Paragraph const & par = *it;
336         BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
337         depth_type const cur_depth = par.getDepth();
338         ParIterator prev_it = it;
339         while (prev_it.pit()) {
340                 --prev_it.top().pit();
341                 Paragraph const & prev_par = *prev_it;
342                 if (prev_par.getDepth() <= cur_depth)
343                         return  prev_par.layout()->labeltype != LABEL_ENUMERATE;
344         }
345         // start of nested inset: reset
346         return true;
347 }
348
349
350 // set the label of a paragraph. This includes the counters.
351 void setLabel(Buffer const & buf, ParIterator & it, LyXTextClass const & textclass)
352 {
353         Paragraph & par = *it;
354         LyXLayout_ptr const & layout = par.layout();
355         Counters & counters = textclass.counters();
356
357         if (it.pit() == 0) {
358                 par.params().appendix(par.params().startOfAppendix());
359         } else {
360                 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
361                 if (!par.params().appendix() &&
362                     par.params().startOfAppendix()) {
363                         par.params().appendix(true);
364                         textclass.counters().reset();
365                 }
366         }
367
368         // Compute the item depth of the paragraph
369         par.itemdepth = getItemDepth(it);
370
371         // erase what was there before
372         par.params().labelString(docstring());
373
374         if (layout->margintype == MARGIN_MANUAL) {
375                 if (par.params().labelWidthString().empty())
376                         par.setLabelWidthString(buf.translateLabel(layout->labelstring()));
377         } else {
378                 par.setLabelWidthString(docstring());
379         }
380
381         // is it a layout that has an automatic label?
382         if (layout->labeltype == LABEL_COUNTER) {
383                 if (layout->toclevel <= buf.params().secnumdepth
384                     && (layout->latextype != LATEX_ENVIRONMENT
385                         || isFirstInSequence(it.pit(), it.plist()))) {
386                         counters.step(layout->counter);
387                         docstring label = expandLabel(buf, layout,
388                                                       par.params().appendix());
389                         par.params().labelString(label);
390                 }
391         } else if (layout->labeltype == LABEL_ITEMIZE) {
392                 // At some point of time we should do something more
393                 // clever here, like:
394                 //   par.params().labelString(
395                 //    buf.params().user_defined_bullet(par.itemdepth).getText());
396                 // for now, use a simple hardcoded label
397                 docstring itemlabel;
398                 switch (par.itemdepth) {
399                 case 0:
400                         itemlabel = char_type(0x2022);
401                         break;
402                 case 1:
403                         itemlabel = char_type(0x2013);
404                         break;
405                 case 2:
406                         itemlabel = char_type(0x2217);
407                         break;
408                 case 3:
409                         itemlabel += char_type(0x2219); // or 0x00b7
410                         break;
411                 }
412
413                 par.params().labelString(itemlabel);
414         } else if (layout->labeltype == LABEL_ENUMERATE) {
415                 // FIXME
416                 // Yes I know this is a really, really! bad solution
417                 // (Lgb)
418                 docstring enumcounter = from_ascii("enum");
419
420                 switch (par.itemdepth) {
421                 case 2:
422                         enumcounter += 'i';
423                 case 1:
424                         enumcounter += 'i';
425                 case 0:
426                         enumcounter += 'i';
427                         break;
428                 case 3:
429                         enumcounter += "iv";
430                         break;
431                 default:
432                         // not a valid enumdepth...
433                         break;
434                 }
435
436                 // Maybe we have to reset the enumeration counter.
437                 if (needEnumCounterReset(it))
438                         counters.reset(enumcounter);
439
440                 counters.step(enumcounter);
441
442                 string format;
443
444                 switch (par.itemdepth) {
445                 case 0:
446                         format = N_("\\arabic{enumi}.");
447                         break;
448                 case 1:
449                         format = N_("(\\alph{enumii})");
450                         break;
451                 case 2:
452                         format = N_("\\roman{enumiii}.");
453                         break;
454                 case 3:
455                         format = N_("\\Alph{enumiv}.");
456                         break;
457                 default:
458                         // not a valid enumdepth...
459                         break;
460                 }
461
462                 par.params().labelString(counters.counterLabel(buf.B_(format)));
463         } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
464                 counters.step(from_ascii("bibitem"));
465                 int number = counters.value(from_ascii("bibitem"));
466                 if (par.bibitem())
467                         par.bibitem()->setCounter(number);
468                 par.params().labelString(buf.translateLabel(layout->labelstring()));
469                 // In biblio should't be following counters but...
470         } else if (layout->labeltype == LABEL_SENSITIVE) {
471                 // Search for the first float or wrap inset in the iterator
472                 docstring type;
473                 size_t i = it.depth();
474                 while (i > 0) {
475                         --i;
476                         InsetBase * const in = &it[i].inset();
477                         if (in->lyxCode() == InsetBase::FLOAT_CODE
478                             || in->lyxCode() == InsetBase::WRAP_CODE) {
479                                 type = in->getInsetName();
480                                 break;
481                         }
482                 }
483
484                 docstring s;
485                 if (!type.empty()) {
486                         Floating const & fl = textclass.floats().getType(to_ascii(type));
487                         // FIXME UNICODE
488                         counters.step(from_ascii(fl.type()));
489
490                         // Doesn't work... yet.
491                         s = bformat(_("%1$s #:"), buf.B_(fl.name()));
492                 } else {
493                         // par->SetLayout(0);
494                         s = buf.translateLabel(layout->labelstring());
495                 }
496
497                 par.params().labelString(s);
498         } else if (layout->labeltype == LABEL_NO_LABEL)
499                 par.params().labelString(docstring());
500         else
501                 par.params().labelString(buf.translateLabel(layout->labelstring()));
502 }
503
504 } // anon namespace
505
506
507 bool updateCurrentLabel(Buffer const & buf,
508         ParIterator & it)
509 {
510     if (it == par_iterator_end(buf.inset()))
511         return false;
512
513 //      if (it.lastpit == 0 && LyXText::isMainText(buf))
514 //              return false;
515
516         switch (it->layout()->labeltype) {
517
518         case LABEL_NO_LABEL:
519         case LABEL_MANUAL:
520         case LABEL_BIBLIO:
521         case LABEL_TOP_ENVIRONMENT:
522         case LABEL_CENTERED_TOP_ENVIRONMENT:
523         case LABEL_STATIC:
524         case LABEL_ITEMIZE:
525                 setLabel(buf, it, buf.params().getLyXTextClass());
526                 return true;
527
528         case LABEL_SENSITIVE:
529         case LABEL_COUNTER:
530         // do more things with enumerate later
531         case LABEL_ENUMERATE:
532                 return false;
533         }
534
535         // This is dead code which get rid of a warning:
536         return true;
537 }
538
539
540 void updateLabels(Buffer const & buf,
541         ParIterator & from, ParIterator & to, bool childonly)
542 {
543         for (ParIterator it = from; it != to; ++it) {
544                 if (it.pit() > it.lastpit())
545                         return;
546                 if (!updateCurrentLabel (buf, it)) {
547                         updateLabels(buf, childonly);
548                         return;
549                 }
550         }
551 }
552
553
554 void updateLabels(Buffer const & buf, ParIterator & iter, bool childonly)
555 {
556         if (updateCurrentLabel(buf, iter))
557                 return;
558
559         updateLabels(buf, childonly);
560 }
561
562
563 void updateLabels(Buffer const & buf, bool childonly)
564 {
565         // Use the master text class also for child documents
566         LyXTextClass const & textclass = buf.params().getLyXTextClass();
567
568         if (!childonly) {
569                 // If this is a child document start with the master
570                 Buffer const * const master = buf.getMasterBuffer();
571                 if (master != &buf) {
572                         updateLabels(*master);
573                         return;
574                 }
575
576                 // start over the counters
577                 textclass.counters().reset();
578         }
579
580         ParIterator const end = par_iterator_end(buf.inset());
581
582         for (ParIterator it = par_iterator_begin(buf.inset()); it != end; ++it) {
583                 // reduce depth if necessary
584                 if (it.pit()) {
585                         Paragraph const & prevpar = it.plist()[it.pit() - 1];
586                         it->params().depth(min(it->params().depth(),
587                                                prevpar.getMaxDepthAfter()));
588                 } else
589                         it->params().depth(0);
590
591                 // set the counter for this paragraph
592                 setLabel(buf, it, textclass);
593
594                 // Now included docs
595                 InsetList::const_iterator iit = it->insetlist.begin();
596                 InsetList::const_iterator end = it->insetlist.end();
597                 for (; iit != end; ++iit) {
598                         if (iit->inset->lyxCode() == InsetBase::INCLUDE_CODE)
599                                 static_cast<InsetInclude const *>(iit->inset)
600                                         ->updateLabels(buf);
601                 }
602         }
603
604         const_cast<Buffer &>(buf).tocBackend().update();
605 }
606
607
608 docstring expandLabel(Buffer const & buf,
609                       LyXLayout_ptr const & layout, bool appendix)
610 {
611         LyXTextClass const & tclass = buf.params().getLyXTextClass();
612
613         docstring fmt = buf.translateLabel(appendix ?
614                         layout->labelstring_appendix() :
615                         layout->labelstring());
616
617         // handle 'inherited level parts' in 'fmt',
618         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
619         size_t const i = fmt.find('@', 0);
620         if (i != docstring::npos) {
621                 size_t const j = fmt.find('@', i + 1);
622                 if (j != docstring::npos) {
623                         docstring parent(fmt, i + 1, j - i - 1);
624                         // FIXME UNICODE
625                         docstring label = expandLabel(buf, tclass[to_utf8(parent)], appendix);
626                         fmt = docstring(fmt, 0, i) + label + docstring(fmt, j + 1, docstring::npos);
627                 }
628         }
629
630         return tclass.counters().counterLabel(fmt);
631 }
632
633
634 } // namespace lyx