]> git.lyx.org Git - lyx.git/blob - src/buffer_funcs.cpp
eb3eb52349d44c08e501b8823937805974723dcf
[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 "InsetList.h"
25 #include "InsetIterator.h"
26 #include "Language.h"
27 #include "LaTeX.h"
28 #include "Layout.h"
29 #include "LayoutPtr.h"
30 #include "LyX.h"
31 #include "TextClass.h"
32 #include "TextClassList.h"
33 #include "Paragraph.h"
34 #include "paragraph_funcs.h"
35 #include "ParagraphList.h"
36 #include "ParagraphParameters.h"
37 #include "ParIterator.h"
38 #include "TexRow.h"
39 #include "Text.h"
40 #include "TocBackend.h"
41
42 #include "frontends/alert.h"
43
44 #include "insets/InsetBibitem.h"
45 #include "insets/InsetInclude.h"
46
47 #include "support/convert.h"
48 #include "support/debug.h"
49 #include "support/filetools.h"
50 #include "support/gettext.h"
51 #include "support/lstrings.h"
52 #include "support/textutils.h"
53
54 using namespace std;
55 using namespace lyx::support;
56
57 namespace lyx {
58
59 namespace Alert = frontend::Alert;
60
61
62 Buffer * checkAndLoadLyXFile(FileName const & filename)
63 {
64         // File already open?
65         Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
66         if (checkBuffer) {
67                 if (checkBuffer->isClean())
68                         return checkBuffer;
69                 docstring const file = makeDisplayPath(filename.absFilename(), 20);
70                 docstring text = bformat(_(
71                                 "The document %1$s is already loaded and has unsaved changes.\n"
72                                 "Do you want to abandon your changes and reload the version on disk?"), file);
73                 if (Alert::prompt(_("Reload saved document?"),
74                                 text, 0, 1,  _("&Reload"), _("&Keep Changes")))
75                         return checkBuffer;
76
77                 // FIXME: should be LFUN_REVERT
78                 theBufferList().release(checkBuffer);
79                 // Load it again.
80                 return checkAndLoadLyXFile(filename);
81         }
82
83         if (filename.exists()) {
84                 if (!filename.isReadableFile()) {
85                         docstring text = bformat(_("The file %1$s exists but is not "
86                                 "readable by the current user."),
87                                 from_utf8(filename.absFilename()));
88                         Alert::error(_("File not readable!"), text);
89                         return 0;
90                 }
91                 Buffer * b = theBufferList().newBuffer(filename.absFilename());
92                 if (!b)
93                         // Buffer creation is not possible.
94                         return 0;
95                 if (!b->loadLyXFile(filename)) {
96                         theBufferList().release(b);
97                         return 0;
98                 }
99                 return b;
100         }
101
102         docstring text = bformat(_("The document %1$s does not yet "
103                 "exist.\n\nDo you want to create a new document?"),
104                 from_utf8(filename.absFilename()));
105         if (!Alert::prompt(_("Create new document?"),
106                         text, 0, 1, _("&Create"), _("Cancel")))
107                 return newFile(filename.absFilename(), string(), true);
108
109         return 0;
110 }
111
112
113 // FIXME newFile() should probably be a member method of Application...
114 Buffer * newFile(string const & filename, string const & templatename,
115                  bool const isNamed)
116 {
117         // get a free buffer
118         Buffer * b = theBufferList().newBuffer(filename);
119         if (!b)
120                 // Buffer creation is not possible.
121                 return 0;
122
123         FileName tname;
124         // use defaults.lyx as a default template if it exists.
125         if (templatename.empty())
126                 tname = libFileSearch("templates", "defaults.lyx");
127         else
128                 tname = makeAbsPath(templatename);
129
130         if (!tname.empty()) {
131                 if (!b->readFile(tname)) {
132                         docstring const file = makeDisplayPath(tname.absFilename(), 50);
133                         docstring const text  = bformat(
134                                 _("The specified document template\n%1$s\ncould not be read."),
135                                 file);
136                         Alert::error(_("Could not read template"), text);
137                         theBufferList().release(b);
138                         return 0;
139                 }
140         }
141
142         if (!isNamed) {
143                 b->setUnnamed();
144                 b->setFileName(filename);
145         }
146
147         b->setReadonly(false);
148         b->setFullyLoaded(true);
149
150         return b;
151 }
152
153
154 Buffer * newUnnamedFile(string const & templatename, FileName const & path)
155 {
156         static int newfile_number;
157
158         string document_path = path.absFilename();
159         string filename = addName(document_path,
160                 "newfile" + convert<string>(++newfile_number) + ".lyx");
161         while (theBufferList().exists(filename)
162                 || FileName(filename).isReadableFile()) {
163                 ++newfile_number;
164                 filename = addName(document_path,
165                         "newfile" +     convert<string>(newfile_number) + ".lyx");
166         }
167         return newFile(filename, templatename, false);
168 }
169
170
171 int countWords(DocIterator const & from, DocIterator const & to)
172 {
173         int count = 0;
174         bool inword = false;
175         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
176                 // Copied and adapted from isLetter() in ControlSpellChecker
177                 if (dit.inTexted()
178                     && dit.pos() != dit.lastpos()
179                     && dit.paragraph().isLetter(dit.pos())
180                     && !dit.paragraph().isDeleted(dit.pos())) {
181                         if (!inword) {
182                                 ++count;
183                                 inword = true;
184                         }
185                 } else if (inword)
186                         inword = false;
187         }
188
189         return count;
190 }
191
192
193 int countChars(DocIterator const & from, DocIterator const & to, bool with_blanks)
194 {
195         int chars = 0;
196         int blanks = 0;
197         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
198
199                 if (!dit.inTexted()) continue;
200                 Paragraph const & par = dit.paragraph();
201                 pos_type const pos = dit.pos();
202
203                 if (pos != dit.lastpos() && !par.isDeleted(pos)) {
204                         if (par.isInset(pos)) {
205                                 Inset const * ins = par.getInset(pos);
206                                 if (ins->isLetter())
207                                         ++chars;
208                                 else if (with_blanks && ins->isSpace())
209                                         ++blanks;
210                         } else {
211                                 char_type const c = par.getChar(pos);
212                                 if (isPrintableNonspace(c))
213                                         ++chars;
214                                 else if (isSpace(c) && with_blanks)
215                                         ++blanks;
216                         }
217                 }
218         }
219
220         return chars + blanks;
221 }
222
223
224 namespace {
225
226 depth_type getDepth(DocIterator const & it)
227 {
228         depth_type depth = 0;
229         for (size_t i = 0 ; i < it.depth() ; ++i)
230                 if (!it[i].inset().inMathed())
231                         depth += it[i].paragraph().getDepth() + 1;
232         // remove 1 since the outer inset does not count
233         return depth - 1;
234 }
235
236 depth_type getItemDepth(ParIterator const & it)
237 {
238         Paragraph const & par = *it;
239         LabelType const labeltype = par.layout()->labeltype;
240
241         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
242                 return 0;
243
244         // this will hold the lowest depth encountered up to now.
245         depth_type min_depth = getDepth(it);
246         ParIterator prev_it = it;
247         while (true) {
248                 if (prev_it.pit())
249                         --prev_it.top().pit();
250                 else {
251                         // start of nested inset: go to outer par
252                         prev_it.pop_back();
253                         if (prev_it.empty()) {
254                                 // start of document: nothing to do
255                                 return 0;
256                         }
257                 }
258
259                 // We search for the first paragraph with same label
260                 // that is not more deeply nested.
261                 Paragraph & prev_par = *prev_it;
262                 depth_type const prev_depth = getDepth(prev_it);
263                 if (labeltype == prev_par.layout()->labeltype) {
264                         if (prev_depth < min_depth)
265                                 return prev_par.itemdepth + 1;
266                         if (prev_depth == min_depth)
267                                 return prev_par.itemdepth;
268                 }
269                 min_depth = min(min_depth, prev_depth);
270                 // small optimization: if we are at depth 0, we won't
271                 // find anything else
272                 if (prev_depth == 0)
273                         return 0;
274         }
275 }
276
277
278 bool needEnumCounterReset(ParIterator const & it)
279 {
280         Paragraph const & par = *it;
281         BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
282         depth_type const cur_depth = par.getDepth();
283         ParIterator prev_it = it;
284         while (prev_it.pit()) {
285                 --prev_it.top().pit();
286                 Paragraph const & prev_par = *prev_it;
287                 if (prev_par.getDepth() <= cur_depth)
288                         return  prev_par.layout()->labeltype != LABEL_ENUMERATE;
289         }
290         // start of nested inset: reset
291         return true;
292 }
293
294
295 // set the label of a paragraph. This includes the counters.
296 void setLabel(Buffer const & buf, ParIterator & it)
297 {
298         TextClass const & textclass = buf.params().getTextClass();
299         Paragraph & par = it.paragraph();
300         LayoutPtr const & layout = par.layout();
301         Counters & counters = textclass.counters();
302
303         if (par.params().startOfAppendix()) {
304                 // FIXME: only the counter corresponding to toplevel
305                 // sectionning should be reset
306                 counters.reset();
307                 counters.appendix(true);
308         }
309         par.params().appendix(counters.appendix());
310
311         // Compute the item depth of the paragraph
312         par.itemdepth = getItemDepth(it);
313
314         if (layout->margintype == MARGIN_MANUAL) {
315                 if (par.params().labelWidthString().empty())
316                         par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
317         } else {
318                 par.params().labelWidthString(docstring());
319         }
320
321         switch(layout->labeltype) {
322         case LABEL_COUNTER:
323                 if (layout->toclevel <= buf.params().secnumdepth
324                     && (layout->latextype != LATEX_ENVIRONMENT
325                         || isFirstInSequence(it.pit(), it.plist()))) {
326                         counters.step(layout->counter);
327                         par.params().labelString(
328                                 par.expandLabel(layout, buf.params()));
329                 } else
330                         par.params().labelString(docstring());
331                 break;
332
333         case LABEL_ITEMIZE: {
334                 // At some point of time we should do something more
335                 // clever here, like:
336                 //   par.params().labelString(
337                 //    buf.params().user_defined_bullet(par.itemdepth).getText());
338                 // for now, use a simple hardcoded label
339                 docstring itemlabel;
340                 switch (par.itemdepth) {
341                 case 0:
342                         itemlabel = char_type(0x2022);
343                         break;
344                 case 1:
345                         itemlabel = char_type(0x2013);
346                         break;
347                 case 2:
348                         itemlabel = char_type(0x2217);
349                         break;
350                 case 3:
351                         itemlabel = char_type(0x2219); // or 0x00b7
352                         break;
353                 }
354                 par.params().labelString(itemlabel);
355                 break;
356         }
357
358         case LABEL_ENUMERATE: {
359                 // FIXME: Yes I know this is a really, really! bad solution
360                 // (Lgb)
361                 docstring enumcounter = from_ascii("enum");
362
363                 switch (par.itemdepth) {
364                 case 2:
365                         enumcounter += 'i';
366                 case 1:
367                         enumcounter += 'i';
368                 case 0:
369                         enumcounter += 'i';
370                         break;
371                 case 3:
372                         enumcounter += "iv";
373                         break;
374                 default:
375                         // not a valid enumdepth...
376                         break;
377                 }
378
379                 // Maybe we have to reset the enumeration counter.
380                 if (needEnumCounterReset(it))
381                         counters.reset(enumcounter);
382
383                 counters.step(enumcounter);
384
385                 string format;
386
387                 switch (par.itemdepth) {
388                 case 0:
389                         format = N_("\\arabic{enumi}.");
390                         break;
391                 case 1:
392                         format = N_("(\\alph{enumii})");
393                         break;
394                 case 2:
395                         format = N_("\\roman{enumiii}.");
396                         break;
397                 case 3:
398                         format = N_("\\Alph{enumiv}.");
399                         break;
400                 default:
401                         // not a valid enumdepth...
402                         break;
403                 }
404
405                 par.params().labelString(counters.counterLabel(
406                         par.translateIfPossible(from_ascii(format), buf.params())));
407
408                 break;
409         }
410
411         case LABEL_SENSITIVE: {
412                 string const & type = counters.current_float();
413                 docstring full_label;
414                 if (type.empty())
415                         full_label = buf.B_("Senseless!!! ");
416                 else {
417                         docstring name = buf.B_(textclass.floats().getType(type).name());
418                         if (counters.hasCounter(from_utf8(type))) {
419                                 counters.step(from_utf8(type));
420                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
421                                                      name, 
422                                                      counters.theCounter(from_utf8(type)));
423                         } else
424                                 full_label = bformat(from_ascii("%1$s #:"), name);      
425                 }
426                 par.params().labelString(full_label);   
427                 break;
428         }
429
430         case LABEL_NO_LABEL:
431                 par.params().labelString(docstring());
432                 break;
433
434         case LABEL_MANUAL:
435         case LABEL_TOP_ENVIRONMENT:
436         case LABEL_CENTERED_TOP_ENVIRONMENT:
437         case LABEL_STATIC:      
438         case LABEL_BIBLIO:
439                 par.params().labelString(
440                         par.translateIfPossible(layout->labelstring(), 
441                                                 buf.params()));
442                 break;
443         }
444 }
445
446 } // anon namespace
447
448 void updateLabels(Buffer const & buf, ParIterator & parit)
449 {
450         BOOST_ASSERT(parit.pit() == 0);
451
452         // set the position of the text in the buffer to be able
453         // to resolve macros in it. This has nothing to do with
454         // labels, but by putting it here we avoid implementing
455         // a whole bunch of traversal routines just for this call.
456         parit.text()->setMacrocontextPosition(parit);
457
458         depth_type maxdepth = 0;
459         pit_type const lastpit = parit.lastpit();
460         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
461                 // reduce depth if necessary
462                 parit->params().depth(min(parit->params().depth(), maxdepth));
463                 maxdepth = parit->getMaxDepthAfter();
464
465                 // set the counter for this paragraph
466                 setLabel(buf, parit);
467
468                 // Now the insets
469                 InsetList::const_iterator iit = parit->insetList().begin();
470                 InsetList::const_iterator end = parit->insetList().end();
471                 for (; iit != end; ++iit) {
472                         parit.pos() = iit->pos;
473                         iit->inset->updateLabels(buf, parit);
474                 }
475         }
476         
477 }
478
479
480 // FIXME: buf should should be const because updateLabels() modifies
481 // the contents of the paragraphs.
482 void updateLabels(Buffer const & buf, bool childonly)
483 {
484         Buffer const * const master = buf.masterBuffer();
485         // Use the master text class also for child documents
486         TextClass const & textclass = master->params().getTextClass();
487
488         if (!childonly) {
489                 // If this is a child document start with the master
490                 if (master != &buf) {
491                         updateLabels(*master);
492                         return;
493                 }
494
495                 // start over the counters
496                 textclass.counters().reset();
497         }
498
499         Buffer & cbuf = const_cast<Buffer &>(buf);
500
501         if (buf.text().empty()) {
502                 // FIXME: we don't call continue with updateLabels()
503                 // here because it crashes on newly created documents.
504                 // But the TocBackend needs to be initialised
505                 // nonetheless so we update the tocBackend manually.
506                 cbuf.tocBackend().update();
507                 return;
508         }
509
510         // do the real work
511         ParIterator parit = par_iterator_begin(buf.inset());
512         updateLabels(buf, parit);
513
514         cbuf.tocBackend().update();
515         if (!childonly)
516                 cbuf.structureChanged();
517 }
518
519
520 } // namespace lyx