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