]> git.lyx.org Git - lyx.git/blob - src/buffer.C
initialize all vars
[lyx.git] / src / buffer.C
1 /**
2  * \file buffer.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  *
8  * Full author contact details are available in file CREDITS
9  */
10
11 #include <config.h>
12
13 #include "buffer.h"
14 #include "bufferlist.h"
15 #include "LyXAction.h"
16 #include "lyxrc.h"
17 #include "lyxlex.h"
18 #include "tex-strings.h"
19 #include "layout.h"
20 #include "bufferview_funcs.h"
21 #include "lyxfont.h"
22 #include "version.h"
23 #include "LaTeX.h"
24 #include "Chktex.h"
25 #include "debug.h"
26 #include "LaTeXFeatures.h"
27 #include "lyxtext.h"
28 #include "gettext.h"
29 #include "language.h"
30 #include "exporter.h"
31 #include "errorlist.h"
32 #include "Lsstream.h"
33 #include "format.h"
34 #include "BufferView.h"
35 #include "ParagraphParameters.h"
36 #include "iterators.h"
37 #include "lyxtextclasslist.h"
38 #include "sgml.h"
39 #include "paragraph_funcs.h"
40 #include "messages.h"
41 #include "author.h"
42
43 #include "frontends/LyXView.h"
44
45 #include "mathed/formulamacro.h"
46 #include "mathed/formula.h"
47
48 #include "insets/inseterror.h"
49 #include "insets/insetbibitem.h"
50 #include "insets/insetbibtex.h"
51 #include "insets/insetinclude.h"
52 #include "insets/insettext.h"
53
54 #include "frontends/Dialogs.h"
55 #include "frontends/Alert.h"
56
57 #include "graphics/Previews.h"
58
59 #include "support/textutils.h"
60 #include "support/filetools.h"
61 #include "support/path.h"
62 #include "support/os.h"
63 #include "support/tostr.h"
64 #include "support/lyxlib.h"
65 #include "support/FileInfo.h"
66 #include "support/lyxmanip.h"
67 #include "support/lyxtime.h"
68
69 #include <boost/bind.hpp>
70 #include <boost/tuple/tuple.hpp>
71
72 #include <fstream>
73 #include <iomanip>
74 #include <map>
75 #include <stack>
76 #include <list>
77 #include <algorithm>
78
79 #include <cstdlib>
80 #include <cmath>
81 #include <unistd.h>
82 #include <sys/types.h>
83 #include <utime.h>
84
85 #ifdef HAVE_LOCALE
86 #include <locale>
87 #endif
88
89 #ifndef CXX_GLOBAL_CSTD
90 using std::pow;
91 #endif
92
93 using std::ostream;
94 using std::ofstream;
95 using std::ifstream;
96 using std::fstream;
97 using std::ios;
98 using std::setw;
99 using std::endl;
100 using std::pair;
101 using std::make_pair;
102 using std::vector;
103 using std::map;
104 using std::stack;
105 using std::list;
106 using std::for_each;
107
108 using lyx::pos_type;
109 using lyx::textclass_type;
110
111 // all these externs should eventually be removed.
112 extern BufferList bufferlist;
113
114 namespace {
115
116 const int LYX_FORMAT = 223;
117
118 } // namespace anon
119
120 Buffer::Buffer(string const & file, bool ronly)
121         : niceFile(true), lyx_clean(true), bak_clean(true),
122           unnamed(false), read_only(ronly),
123           filename_(file), users(0)
124 {
125         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
126         filepath_ = OnlyPath(file);
127         lyxvc.buffer(this);
128         if (read_only || lyxrc.use_tempdir) {
129                 tmppath = CreateBufferTmpDir();
130         } else {
131                 tmppath.erase();
132         }
133
134         // set initial author
135         authors().record(Author(lyxrc.user_name, lyxrc.user_email));
136 }
137
138
139 Buffer::~Buffer()
140 {
141         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
142         // here the buffer should take care that it is
143         // saved properly, before it goes into the void.
144
145         // make sure that views using this buffer
146         // forgets it.
147         if (users)
148                 users->buffer(0);
149
150         if (!tmppath.empty() && destroyDir(tmppath) != 0) {
151                 Alert::warning(_("Could not remove temporary directory"),
152                         bformat(_("Could not remove the temporary directory %1$s"), tmppath));
153         }
154
155         paragraphs.clear();
156
157         // Remove any previewed LaTeX snippets assocoated with this buffer.
158         grfx::Previews::get().removeLoader(this);
159 }
160
161
162 string const Buffer::getLatexName(bool no_path) const
163 {
164         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
165         return no_path ? OnlyFilename(name) : name;
166 }
167
168
169 pair<Buffer::LogType, string> const Buffer::getLogName() const
170 {
171         string const filename = getLatexName(false);
172
173         if (filename.empty())
174                 return make_pair(Buffer::latexlog, string());
175
176         string path = OnlyPath(filename);
177
178         if (lyxrc.use_tempdir || !IsDirWriteable(path))
179                 path = tmppath;
180
181         string const fname = AddName(path,
182                                      OnlyFilename(ChangeExtension(filename,
183                                                                   ".log")));
184         string const bname =
185                 AddName(path, OnlyFilename(
186                         ChangeExtension(filename,
187                                         formats.extension("literate") + ".out")));
188
189         // If no Latex log or Build log is newer, show Build log
190
191         FileInfo const f_fi(fname);
192         FileInfo const b_fi(bname);
193
194         if (b_fi.exist() &&
195             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
196                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
197                 return make_pair(Buffer::buildlog, bname);
198         }
199         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
200         return make_pair(Buffer::latexlog, fname);
201 }
202
203
204 void Buffer::setReadonly(bool flag)
205 {
206         if (read_only != flag) {
207                 read_only = flag;
208                 updateTitles();
209                 users->owner()->getDialogs().updateBufferDependent(false);
210         }
211 }
212
213
214 AuthorList & Buffer::authors()
215 {
216         return params.authorlist;
217 }
218
219
220 /// Update window titles of all users
221 // Should work on a list
222 void Buffer::updateTitles() const
223 {
224         if (users)
225                 users->owner()->updateWindowTitle();
226 }
227
228
229 /// Reset autosave timer of all users
230 // Should work on a list
231 void Buffer::resetAutosaveTimers() const
232 {
233         if (users)
234                 users->owner()->resetAutosaveTimer();
235 }
236
237
238 void Buffer::setFileName(string const & newfile)
239 {
240         filename_ = MakeAbsPath(newfile);
241         filepath_ = OnlyPath(filename_);
242         setReadonly(IsFileWriteable(filename_) == 0);
243         updateTitles();
244 }
245
246
247 // We'll remove this later. (Lgb)
248 namespace {
249
250 void unknownClass(string const & unknown)
251 {
252         Alert::warning(_("Unknown document class"),
253                 bformat(_("Using the default document class, because the "
254                         " class %1$s is unknown."), unknown));
255 }
256
257 } // anon
258
259 int Buffer::readHeader(LyXLex & lex)
260 {
261         int unknown_tokens = 0;
262
263         while (lex.isOK()) {
264                 lex.nextToken();
265                 string const token = lex.getString();
266
267                 if (token.empty())
268                         continue;
269
270                 if (token == "\\end_header")
271                         break;
272
273                 lyxerr[Debug::PARSER] << "Handling header token: `"
274                                       << token << '\'' << endl;
275
276                 string unknown = params.readToken(lex, token);
277                 if (!unknown.empty()) {
278                         if (unknown[0] != '\\') {
279                                 unknownClass(unknown);
280                         } else {
281                                 ++unknown_tokens;
282                         }
283                 }
284         }
285         return unknown_tokens;
286 }
287
288
289 // candidate for move to BufferView
290 // (at least some parts in the beginning of the func)
291 //
292 // Uwe C. Schroeder
293 // changed to be public and have one parameter
294 // if par = 0 normal behavior
295 // else insert behavior
296 // Returns false if "\the_end" is not read (Asger)
297 bool Buffer::readBody(LyXLex & lex, ParagraphList::iterator pit)
298 {
299         int unknown_tokens = 0;
300
301         Paragraph::depth_type depth = 0;
302         bool the_end_read = false;
303
304         if (paragraphs.empty()) {
305                 unknown_tokens += readHeader(lex);
306
307                 if (!params.getLyXTextClass().load()) {
308                         string theclass = params.getLyXTextClass().name();
309                         Alert::error(_("Can't load document class"), bformat(
310                                         "Using the default document class, because the "
311                                         " class %1$s could not be loaded.", theclass));
312                         params.textclass = 0;
313                 }
314         } else {
315                 // We are inserting into an existing document
316                 users->text->breakParagraph(paragraphs);
317
318                 // We don't want to adopt the parameters from the
319                 // document we insert, so read them into a temporary buffer
320                 // and then discard it
321
322                 Buffer tmpbuf("", false);
323                 tmpbuf.readHeader(lex);
324         }
325
326         while (lex.isOK()) {
327                 lex.nextToken();
328                 string const token = lex.getString();
329
330                 if (token.empty())
331                         continue;
332
333                 lyxerr[Debug::PARSER] << "Handling token: `"
334                                       << token << '\'' << endl;
335
336                 if (token == "\\the_end") {
337                         the_end_read = true;
338                         continue;
339                 }
340
341                 unknown_tokens += readParagraph(lex, token, paragraphs, pit, depth);
342         }
343
344
345         if (unknown_tokens > 0) {
346                 string s;
347                 if (unknown_tokens == 1) {
348                         s = bformat(_("Encountered one unknown token when reading "
349                                 "the document %1$s."), fileName());
350                 } else {
351                         s = bformat(_("Encountered %1$s unknown tokens when reading "
352                                 "the document %2$s."), tostr(unknown_tokens), fileName());
353                 }
354                 Alert::warning(_("Document format failure"), s);
355         }
356
357         return the_end_read;
358 }
359
360
361 int Buffer::readParagraph(LyXLex & lex, string const & token,
362                       ParagraphList & pars, ParagraphList::iterator & pit,
363                       Paragraph::depth_type & depth)
364 {
365         static Change current_change;
366         int unknown = 0;
367
368         if (token == "\\layout") {
369                 lex.pushToken(token);
370
371                 Paragraph * par = new Paragraph();
372                 par->params().depth(depth);
373                 if (params.tracking_changes)
374                         par->trackChanges();
375                 LyXFont f(LyXFont::ALL_INHERIT, params.language);
376                 par->setFont(0, f);
377
378                 // FIXME: goddamn InsetTabular makes us pass a Buffer
379                 // not BufferParams
380                 unknown += ::readParagraph(*this, *par, lex);
381
382                 // insert after
383                 if (pit != pars.end())
384                         ++pit;
385                 pit = pars.insert(pit, par);
386         } else if (token == "\\begin_deeper") {
387                 ++depth;
388         } else if (token == "\\end_deeper") {
389                 if (!depth) {
390                         lex.printError("\\end_deeper: " "depth is already null");
391                 } else {
392                         --depth;
393                 }
394         } else {
395                 ++unknown;
396         }
397         return unknown;
398 }
399
400
401 // needed to insert the selection
402 void Buffer::insertStringAsLines(ParagraphList::iterator & par, pos_type & pos,
403                                  LyXFont const & fn,string const & str)
404 {
405         LyXLayout_ptr const & layout = par->layout();
406
407         LyXFont font = fn;
408
409         par->checkInsertChar(font);
410         // insert the string, don't insert doublespace
411         bool space_inserted = true;
412         bool autobreakrows = !par->inInset() ||
413                 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
414         for(string::const_iterator cit = str.begin();
415             cit != str.end(); ++cit) {
416                 if (*cit == '\n') {
417                         if (autobreakrows && (!par->empty() || layout->keepempty)) {
418                                 breakParagraph(params, paragraphs, par, pos,
419                                                layout->isEnvironment());
420                                 ++par;
421                                 pos = 0;
422                                 space_inserted = true;
423                         } else {
424                                 continue;
425                         }
426                         // do not insert consecutive spaces if !free_spacing
427                 } else if ((*cit == ' ' || *cit == '\t') &&
428                            space_inserted && !layout->free_spacing &&
429                                    !par->isFreeSpacing())
430                 {
431                         continue;
432                 } else if (*cit == '\t') {
433                         if (!layout->free_spacing && !par->isFreeSpacing()) {
434                                 // tabs are like spaces here
435                                 par->insertChar(pos, ' ', font);
436                                 ++pos;
437                                 space_inserted = true;
438                         } else {
439                                 const pos_type nb = 8 - pos % 8;
440                                 for (pos_type a = 0; a < nb ; ++a) {
441                                         par->insertChar(pos, ' ', font);
442                                         ++pos;
443                                 }
444                                 space_inserted = true;
445                         }
446                 } else if (!IsPrintable(*cit)) {
447                         // Ignore unprintables
448                         continue;
449                 } else {
450                         // just insert the character
451                         par->insertChar(pos, *cit, font);
452                         ++pos;
453                         space_inserted = (*cit == ' ');
454                 }
455
456         }
457 }
458
459
460 bool Buffer::readFile(LyXLex & lex, string const & filename)
461 {
462         bool ret = readFile(lex, filename, paragraphs.begin());
463
464         // After we have read a file, we must ensure that the buffer
465         // language is set and used in the gui.
466         // If you know of a better place to put this, please tell me. (Lgb)
467         updateDocLang(params.language);
468
469         return ret;
470 }
471
472
473 // FIXME: all the below Alerts should give the filename..
474 bool Buffer::readFile(LyXLex & lex, string const & filename,
475                       ParagraphList::iterator pit)
476 {
477         if (!lex.isOK()) {
478                 Alert::error(_("Document could not be read"),
479                         _("The specified document could not be read."));
480                 return false;
481         }
482
483         lex.next();
484         string const token(lex.getString());
485
486         if (!lex.isOK()) {
487                 Alert::error(_("Document could not be read"),
488                         _("The specified document could not be read."));
489                 return false;
490         }
491
492         // the first token _must_ be...
493         if (token != "\\lyxformat") {
494                 Alert::error(_("Document format failure"),
495                         _("The specified document is not a LyX document."));
496                 return false;
497         }
498
499         lex.eatLine();
500         string tmp_format = lex.getString();
501         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
502         // if present remove ".," from string.
503         string::size_type dot = tmp_format.find_first_of(".,");
504         //lyxerr << "           dot found at " << dot << endl;
505         if (dot != string::npos)
506                         tmp_format.erase(dot, 1);
507         file_format = strToInt(tmp_format);
508         //lyxerr << "format: " << file_format << endl;
509         if (file_format == LYX_FORMAT) {
510                 // current format
511         } else if (file_format > LYX_FORMAT) {
512                 Alert::warning(_("Document format failure"),
513                         _("This document was created with a newer version of "
514                         "LyX. This is likely to cause problems."));
515         } else if (file_format < LYX_FORMAT) {
516                 // old formats
517                 if (file_format < 200) {
518                         Alert::error(_("Document format failure"),
519                                 _("This LyX document is too old to be read "
520                                 "by this version of LyX. Try LyX 0.10."));
521                         return false;
522                 } else if (!filename.empty()) {
523                         string command =
524                                 LibFileSearch("lyx2lyx", "lyx2lyx");
525                         if (command.empty()) {
526                                 Alert::error(_("Conversion script not found"),
527                                         _("The document is from an earlier version "
528                                           "of LyX, but the conversion script lyx2lyx "
529                                           "could not be found."));
530                                 return false;
531                         }
532                         command += " -t"
533                                 +tostr(LYX_FORMAT) + ' '
534                                 + QuoteName(filename);
535                         lyxerr[Debug::INFO] << "Running '"
536                                             << command << '\''
537                                             << endl;
538                         cmd_ret const ret = RunCommand(command);
539                         if (ret.first) {
540                                 Alert::error(_("Conversion script failed"),
541                                         _("The document is from an earlier version "
542                                           "of LyX, but the lyx2lyx script failed "
543                                           "to convert it."));
544                                 return false;
545                         }
546                         istringstream is(STRCONV(ret.second));
547                         LyXLex tmplex(0, 0);
548                         tmplex.setStream(is);
549                         return readFile(tmplex, string(), pit);
550                 } else {
551                         // This code is reached if lyx2lyx failed (for
552                         // some reason) to change the file format of
553                         // the file.
554                         lyx::Assert(false);
555                         return false;
556                 }
557         }
558         bool the_end = readBody(lex, pit);
559         params.setPaperStuff();
560
561         if (!the_end) {
562                 Alert::error(_("Document format failure"),
563                         _("The document ended unexpectedly, which means "
564                           "that it is probably corrupted."));
565         }
566         return true;
567 }
568
569
570 // Should probably be moved to somewhere else: BufferView? LyXView?
571 bool Buffer::save() const
572 {
573         // We don't need autosaves in the immediate future. (Asger)
574         resetAutosaveTimers();
575
576         // make a backup
577         string s;
578         if (lyxrc.make_backup) {
579                 s = fileName() + '~';
580                 if (!lyxrc.backupdir_path.empty())
581                         s = AddName(lyxrc.backupdir_path,
582                                     subst(os::slashify_path(s),'/','!'));
583
584                 // Rename is the wrong way of making a backup,
585                 // this is the correct way.
586                 /* truss cp fil fil2:
587                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
588                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
589                    open("LyXVC.lyx", O_RDONLY)                     = 3
590                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
591                    fstat(4, 0xEFFFF508)                            = 0
592                    fstat(3, 0xEFFFF508)                            = 0
593                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
594                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
595                    read(3, 0xEFFFD4A0, 8192)                       = 0
596                    close(4)                                        = 0
597                    close(3)                                        = 0
598                    chmod("LyXVC3.lyx", 0100644)                    = 0
599                    lseek(0, 0, SEEK_CUR)                           = 46440
600                    _exit(0)
601                 */
602
603                 // Should probably have some more error checking here.
604                 // Doing it this way, also makes the inodes stay the same.
605                 // This is still not a very good solution, in particular we
606                 // might loose the owner of the backup.
607                 FileInfo finfo(fileName());
608                 if (finfo.exist()) {
609                         mode_t fmode = finfo.getMode();
610                         struct utimbuf times = {
611                                 finfo.getAccessTime(),
612                                 finfo.getModificationTime() };
613
614                         ifstream ifs(fileName().c_str());
615                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
616                         if (ifs && ofs) {
617                                 ofs << ifs.rdbuf();
618                                 ifs.close();
619                                 ofs.close();
620                                 ::chmod(s.c_str(), fmode);
621
622                                 if (::utime(s.c_str(), &times)) {
623                                         lyxerr << "utime error." << endl;
624                                 }
625                         } else {
626                                 lyxerr << "LyX was not able to make "
627                                         "backup copy. Beware." << endl;
628                         }
629                 }
630         }
631
632         if (writeFile(fileName())) {
633                 markClean();
634                 removeAutosaveFile(fileName());
635         } else {
636                 // Saving failed, so backup is not backup
637                 if (lyxrc.make_backup) {
638                         lyx::rename(s, fileName());
639                 }
640                 return false;
641         }
642         return true;
643 }
644
645
646 bool Buffer::writeFile(string const & fname) const
647 {
648         if (read_only && (fname == fileName())) {
649                 return false;
650         }
651
652         FileInfo finfo(fname);
653         if (finfo.exist() && !finfo.writable()) {
654                 return false;
655         }
656
657         ofstream ofs(fname.c_str());
658         if (!ofs) {
659                 return false;
660         }
661
662 #ifdef HAVE_LOCALE
663         // Use the standard "C" locale for file output.
664         ofs.imbue(std::locale::classic());
665 #endif
666
667         // The top of the file should not be written by params.
668
669         // write out a comment in the top of the file
670         ofs << '#' << lyx_docversion
671             << " created this file. For more info see http://www.lyx.org/\n"
672             << "\\lyxformat " << LYX_FORMAT << "\n";
673
674         // now write out the buffer paramters.
675         params.writeFile(ofs);
676
677         ofs << "\\end_header\n";
678
679         Paragraph::depth_type depth = 0;
680
681         // this will write out all the paragraphs
682         // using recursive descent.
683         ParagraphList::iterator pit = paragraphs.begin();
684         ParagraphList::iterator pend = paragraphs.end();
685         for (; pit != pend; ++pit)
686                 pit->write(this, ofs, params, depth);
687
688         // Write marker that shows file is complete
689         ofs << "\n\\the_end" << endl;
690
691         ofs.close();
692
693         // how to check if close went ok?
694         // Following is an attempt... (BE 20001011)
695
696         // good() returns false if any error occured, including some
697         //        formatting error.
698         // bad()  returns true if something bad happened in the buffer,
699         //        which should include file system full errors.
700
701         bool status = true;
702         if (!ofs.good()) {
703                 status = false;
704 #if 0
705                 if (ofs.bad()) {
706                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
707                 } else {
708                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
709                                << endl;
710                 }
711 #endif
712         }
713
714         return status;
715 }
716
717
718 namespace {
719
720 pair<int, string> const addDepth(int depth, int ldepth)
721 {
722         int d = depth * 2;
723         if (ldepth > depth)
724                 d += (ldepth - depth) * 2;
725         return make_pair(d, string(d, ' '));
726 }
727
728 }
729
730
731 string const Buffer::asciiParagraph(Paragraph const & par,
732                                     unsigned int linelen,
733                                     bool noparbreak) const
734 {
735         ostringstream buffer;
736         Paragraph::depth_type depth = 0;
737         int ltype = 0;
738         Paragraph::depth_type ltype_depth = 0;
739         bool ref_printed = false;
740 //      if (!par->previous()) {
741 #if 0
742         // begins or ends a deeper area ?
743         if (depth != par->params().depth()) {
744                 if (par->params().depth() > depth) {
745                         while (par->params().depth() > depth) {
746                                 ++depth;
747                         }
748                 } else {
749                         while (par->params().depth() < depth) {
750                                 --depth;
751                         }
752                 }
753         }
754 #else
755         depth = par.params().depth();
756 #endif
757
758         // First write the layout
759         string const & tmp = par.layout()->name();
760         if (compare_no_case(tmp, "itemize") == 0) {
761                 ltype = 1;
762                 ltype_depth = depth + 1;
763         } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
764                 ltype = 2;
765                 ltype_depth = depth + 1;
766         } else if (contains(ascii_lowercase(tmp), "ection")) {
767                 ltype = 3;
768                 ltype_depth = depth + 1;
769         } else if (contains(ascii_lowercase(tmp), "aragraph")) {
770                 ltype = 4;
771                 ltype_depth = depth + 1;
772         } else if (compare_ascii_no_case(tmp, "description") == 0) {
773                 ltype = 5;
774                 ltype_depth = depth + 1;
775         } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
776                 ltype = 6;
777                 ltype_depth = 0;
778         } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
779                 ltype = 7;
780                 ltype_depth = 0;
781         } else {
782                 ltype = 0;
783                 ltype_depth = 0;
784         }
785
786         /* maybe some vertical spaces */
787
788         /* the labelwidthstring used in lists */
789
790         /* some lines? */
791
792         /* some pagebreaks? */
793
794         /* noindent ? */
795
796         /* what about the alignment */
797
798         // linelen <= 0 is special and means we don't have paragraph breaks
799
800         string::size_type currlinelen = 0;
801
802         if (!noparbreak) {
803                 if (linelen > 0)
804                         buffer << "\n\n";
805
806                 buffer << string(depth * 2, ' ');
807                 currlinelen += depth * 2;
808
809                 //--
810                 // we should probably change to the paragraph language in the
811                 // gettext here (if possible) so that strings are outputted in
812                 // the correct language! (20012712 Jug)
813                 //--
814                 switch (ltype) {
815                 case 0: // Standard
816                 case 4: // (Sub)Paragraph
817                 case 5: // Description
818                         break;
819                 case 6: // Abstract
820                         if (linelen > 0) {
821                                 buffer << _("Abstract") << "\n\n";
822                                 currlinelen = 0;
823                         } else {
824                                 string const abst = _("Abstract: ");
825                                 buffer << abst;
826                                 currlinelen += abst.length();
827                         }
828                         break;
829                 case 7: // Bibliography
830                         if (!ref_printed) {
831                                 if (linelen > 0) {
832                                         buffer << _("References") << "\n\n";
833                                         currlinelen = 0;
834                                 } else {
835                                         string const refs = _("References: ");
836                                         buffer << refs;
837                                         currlinelen += refs.length();
838                                 }
839
840                                 ref_printed = true;
841                         }
842                         break;
843                 default:
844                 {
845                         string const parlab = par.params().labelString();
846                         buffer << parlab << ' ';
847                         currlinelen += parlab.length() + 1;
848                 }
849                 break;
850
851                 }
852         }
853
854         if (!currlinelen) {
855                 pair<int, string> p = addDepth(depth, ltype_depth);
856                 buffer << p.second;
857                 currlinelen += p.first;
858         }
859
860         // this is to change the linebreak to do it by word a bit more
861         // intelligent hopefully! (only in the case where we have a
862         // max linelength!) (Jug)
863
864         string word;
865
866         for (pos_type i = 0; i < par.size(); ++i) {
867                 char c = par.getUChar(params, i);
868                 switch (c) {
869                 case Paragraph::META_INSET:
870                 {
871                         Inset const * inset = par.getInset(i);
872                         if (inset) {
873                                 if (linelen > 0) {
874                                         buffer << word;
875                                         currlinelen += word.length();
876                                         word.erase();
877                                 }
878                                 if (inset->ascii(this, buffer, linelen)) {
879                                         // to be sure it breaks paragraph
880                                         currlinelen += linelen;
881                                 }
882                         }
883                 }
884                 break;
885
886                 default:
887                         if (c == ' ') {
888                                 if (linelen > 0 &&
889                                     currlinelen + word.length() > linelen - 10) {
890                                         buffer << "\n";
891                                         pair<int, string> p = addDepth(depth, ltype_depth);
892                                         buffer << p.second;
893                                         currlinelen = p.first;
894                                 }
895
896                                 buffer << word << ' ';
897                                 currlinelen += word.length() + 1;
898                                 word.erase();
899
900                         } else {
901                                 if (c != '\0') {
902                                         word += c;
903                                 } else {
904                                         lyxerr[Debug::INFO] <<
905                                                 "writeAsciiFile: NULL char in structure." << endl;
906                                 }
907                                 if ((linelen > 0) &&
908                                         (currlinelen + word.length()) > linelen)
909                                 {
910                                         buffer << "\n";
911
912                                         pair<int, string> p =
913                                                 addDepth(depth, ltype_depth);
914                                         buffer << p.second;
915                                         currlinelen = p.first;
916                                 }
917                         }
918                         break;
919                 }
920         }
921         buffer << word;
922         return STRCONV(buffer.str());
923 }
924
925
926 void Buffer::writeFileAscii(string const & fname, int linelen)
927 {
928         ofstream ofs(fname.c_str());
929         if (!ofs) {
930                 string const file = MakeDisplayPath(fname, 50);
931                 string text = bformat(_("Could not save the document\n%1$s."), file);
932                 Alert::error(_("Could not save document"), text);
933                 return;
934         }
935         writeFileAscii(ofs, linelen);
936 }
937
938
939 void Buffer::writeFileAscii(ostream & os, int linelen)
940 {
941         ParagraphList::iterator beg = paragraphs.begin();
942         ParagraphList::iterator end = paragraphs.end();
943         ParagraphList::iterator it = beg;
944         for (; it != end; ++it) {
945                 os << asciiParagraph(*it, linelen, it == beg);
946         }
947         os << "\n";
948 }
949
950
951
952 void Buffer::makeLaTeXFile(string const & fname,
953                            string const & original_path,
954                            LatexRunParams const & runparams,
955                            bool nice, bool only_body, bool only_preamble)
956 {
957         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
958
959         ofstream ofs(fname.c_str());
960         if (!ofs) {
961                 string const file = MakeDisplayPath(fname, 50);
962                 string text = bformat(_("Could not open the specified document\n%1$s."),
963                         file);
964                 Alert::error(_("Could not open file"), text);
965                 return;
966         }
967
968         makeLaTeXFile(ofs, original_path,
969                       runparams, nice, only_body, only_preamble);
970
971         ofs.close();
972         if (ofs.fail()) {
973                 lyxerr << "File was not closed properly." << endl;
974         }
975 }
976
977
978 void Buffer::makeLaTeXFile(ostream & os,
979                            string const & original_path,
980                            LatexRunParams const & runparams,
981                            bool nice, bool only_body, bool only_preamble)
982 {
983         niceFile = nice; // this will be used by Insetincludes.
984
985         // validate the buffer.
986         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
987         LaTeXFeatures features(params);
988         validate(features);
989         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
990
991         texrow.reset();
992         // The starting paragraph of the coming rows is the
993         // first paragraph of the document. (Asger)
994         texrow.start(paragraphs.begin()->id(), 0);
995
996         if (!only_body && nice) {
997                 os << "%% " << lyx_docversion << " created this file.  "
998                         "For more info, see http://www.lyx.org/.\n"
999                         "%% Do not edit unless you really know what "
1000                         "you are doing.\n";
1001                 texrow.newline();
1002                 texrow.newline();
1003         }
1004         lyxerr[Debug::INFO] << "lyx header finished" << endl;
1005         // There are a few differences between nice LaTeX and usual files:
1006         // usual is \batchmode and has a
1007         // special input@path to allow the including of figures
1008         // with either \input or \includegraphics (what figinsets do).
1009         // input@path is set when the actual parameter
1010         // original_path is set. This is done for usual tex-file, but not
1011         // for nice-latex-file. (Matthias 250696)
1012         if (!only_body) {
1013                 if (!nice) {
1014                         // code for usual, NOT nice-latex-file
1015                         os << "\\batchmode\n"; // changed
1016                         // from \nonstopmode
1017                         texrow.newline();
1018                 }
1019                 if (!original_path.empty()) {
1020                         string inputpath = os::external_path(original_path);
1021                         subst(inputpath, "~", "\\string~");
1022                         os << "\\makeatletter\n"
1023                             << "\\def\\input@path{{"
1024                             << inputpath << "/}}\n"
1025                             << "\\makeatother\n";
1026                         texrow.newline();
1027                         texrow.newline();
1028                         texrow.newline();
1029                 }
1030
1031                 // Write the preamble
1032                 params.writeLaTeX(os, features, texrow);
1033
1034                 if (only_preamble)
1035                         return;
1036
1037                 // make the body.
1038                 os << "\\begin{document}\n";
1039                 texrow.newline();
1040         } // only_body
1041         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
1042
1043         if (!lyxrc.language_auto_begin) {
1044                 os << subst(lyxrc.language_command_begin, "$$lang",
1045                              params.language->babel())
1046                     << endl;
1047                 texrow.newline();
1048         }
1049
1050         latexParagraphs(this, paragraphs, os, texrow, runparams, false);
1051
1052         // add this just in case after all the paragraphs
1053         os << endl;
1054         texrow.newline();
1055
1056         if (!lyxrc.language_auto_end) {
1057                 os << subst(lyxrc.language_command_end, "$$lang",
1058                              params.language->babel())
1059                     << endl;
1060                 texrow.newline();
1061         }
1062
1063         if (!only_body) {
1064                 os << "\\end{document}\n";
1065                 texrow.newline();
1066
1067                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1068         } else {
1069                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1070                                      << endl;
1071         }
1072
1073         // Just to be sure. (Asger)
1074         texrow.newline();
1075
1076         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1077         lyxerr[Debug::INFO] << "Row count was " << texrow.rows() - 1
1078                             << '.' << endl;
1079
1080         // we want this to be true outside previews (for insetexternal)
1081         niceFile = true;
1082 }
1083
1084
1085 bool Buffer::isLatex() const
1086 {
1087         return params.getLyXTextClass().outputType() == LATEX;
1088 }
1089
1090
1091 bool Buffer::isLinuxDoc() const
1092 {
1093         return params.getLyXTextClass().outputType() == LINUXDOC;
1094 }
1095
1096
1097 bool Buffer::isLiterate() const
1098 {
1099         return params.getLyXTextClass().outputType() == LITERATE;
1100 }
1101
1102
1103 bool Buffer::isDocBook() const
1104 {
1105         return params.getLyXTextClass().outputType() == DOCBOOK;
1106 }
1107
1108
1109 bool Buffer::isSGML() const
1110 {
1111         LyXTextClass const & tclass = params.getLyXTextClass();
1112
1113         return tclass.outputType() == LINUXDOC ||
1114                tclass.outputType() == DOCBOOK;
1115 }
1116
1117
1118 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
1119 {
1120         ofstream ofs(fname.c_str());
1121
1122         if (!ofs) {
1123                 string const file = MakeDisplayPath(fname, 50);
1124                 string text = bformat(_("Could not save the specified document\n%1$s.\n"),
1125                         file);
1126                 Alert::error(_("Could not save document"), text);
1127                 return;
1128         }
1129
1130         niceFile = nice; // this will be used by included files.
1131
1132         LaTeXFeatures features(params);
1133
1134         validate(features);
1135
1136         texrow.reset();
1137
1138         LyXTextClass const & tclass = params.getLyXTextClass();
1139
1140         string top_element = tclass.latexname();
1141
1142         if (!body_only) {
1143                 ofs << "<!doctype linuxdoc system";
1144
1145                 string preamble = params.preamble;
1146                 const string name = nice ? ChangeExtension(filename_, ".sgml")
1147                          : fname;
1148                 preamble += features.getIncludedFiles(name);
1149                 preamble += features.getLyXSGMLEntities();
1150
1151                 if (!preamble.empty()) {
1152                         ofs << " [ " << preamble << " ]";
1153                 }
1154                 ofs << ">\n\n";
1155
1156                 if (params.options.empty())
1157                         sgml::openTag(ofs, 0, false, top_element);
1158                 else {
1159                         string top = top_element;
1160                         top += ' ';
1161                         top += params.options;
1162                         sgml::openTag(ofs, 0, false, top);
1163                 }
1164         }
1165
1166         ofs << "<!-- "  << lyx_docversion
1167             << " created this file. For more info see http://www.lyx.org/"
1168             << " -->\n";
1169
1170         Paragraph::depth_type depth = 0; // paragraph depth
1171         string item_name;
1172         vector<string> environment_stack(5);
1173
1174         users->resetErrorList();
1175
1176         ParagraphList::iterator pit = paragraphs.begin();
1177         ParagraphList::iterator pend = paragraphs.end();
1178         for (; pit != pend; ++pit) {
1179                 LyXLayout_ptr const & style = pit->layout();
1180                 // treat <toc> as a special case for compatibility with old code
1181                 if (pit->isInset(0)) {
1182                         Inset * inset = pit->getInset(0);
1183                         Inset::Code lyx_code = inset->lyxCode();
1184                         if (lyx_code == Inset::TOC_CODE) {
1185                                 string const temp = "toc";
1186                                 sgml::openTag(ofs, depth, false, temp);
1187                                 continue;
1188                         }
1189                 }
1190
1191                 // environment tag closing
1192                 for (; depth > pit->params().depth(); --depth) {
1193                         sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1194                         environment_stack[depth].erase();
1195                 }
1196
1197                 // write opening SGML tags
1198                 switch (style->latextype) {
1199                 case LATEX_PARAGRAPH:
1200                         if (depth == pit->params().depth()
1201                            && !environment_stack[depth].empty()) {
1202                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1203                                 environment_stack[depth].erase();
1204                                 if (depth)
1205                                         --depth;
1206                                 else
1207                                         ofs << "</p>";
1208                         }
1209                         sgml::openTag(ofs, depth, false, style->latexname());
1210                         break;
1211
1212                 case LATEX_COMMAND:
1213                         if (depth != 0)
1214                                 sgmlError(pit, 0,
1215                                           _("Error: Wrong depth for LatexType Command.\n"));
1216
1217                         if (!environment_stack[depth].empty()) {
1218                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1219                                 ofs << "</p>";
1220                         }
1221
1222                         environment_stack[depth].erase();
1223                         sgml::openTag(ofs, depth, false, style->latexname());
1224                         break;
1225
1226                 case LATEX_ENVIRONMENT:
1227                 case LATEX_ITEM_ENVIRONMENT:
1228                 case LATEX_BIB_ENVIRONMENT:
1229                 {
1230                         string const & latexname = style->latexname();
1231
1232                         if (depth == pit->params().depth()
1233                             && environment_stack[depth] != latexname) {
1234                                 sgml::closeTag(ofs, depth, false,
1235                                              environment_stack[depth]);
1236                                 environment_stack[depth].erase();
1237                         }
1238                         if (depth < pit->params().depth()) {
1239                                depth = pit->params().depth();
1240                                environment_stack[depth].erase();
1241                         }
1242                         if (environment_stack[depth] != latexname) {
1243                                 if (depth == 0) {
1244                                         sgml::openTag(ofs, depth, false, "p");
1245                                 }
1246                                 sgml::openTag(ofs, depth, false, latexname);
1247
1248                                 if (environment_stack.size() == depth + 1)
1249                                         environment_stack.push_back("!-- --");
1250                                 environment_stack[depth] = latexname;
1251                         }
1252
1253                         if (style->latexparam() == "CDATA")
1254                                 ofs << "<![CDATA[";
1255
1256                         if (style->latextype == LATEX_ENVIRONMENT) break;
1257
1258                         if (style->labeltype == LABEL_MANUAL)
1259                                 item_name = "tag";
1260                         else
1261                                 item_name = "item";
1262
1263                         sgml::openTag(ofs, depth + 1, false, item_name);
1264                 }
1265                 break;
1266
1267                 default:
1268                         sgml::openTag(ofs, depth, false, style->latexname());
1269                         break;
1270                 }
1271
1272                 simpleLinuxDocOnePar(ofs, pit, depth);
1273
1274                 ofs << "\n";
1275                 // write closing SGML tags
1276                 switch (style->latextype) {
1277                 case LATEX_COMMAND:
1278                         break;
1279                 case LATEX_ENVIRONMENT:
1280                 case LATEX_ITEM_ENVIRONMENT:
1281                 case LATEX_BIB_ENVIRONMENT:
1282                         if (style->latexparam() == "CDATA")
1283                                 ofs << "]]>";
1284                         break;
1285                 default:
1286                         sgml::closeTag(ofs, depth, false, style->latexname());
1287                         break;
1288                 }
1289         }
1290
1291         // Close open tags
1292         for (int i = depth; i >= 0; --i)
1293                 sgml::closeTag(ofs, depth, false, environment_stack[i]);
1294
1295         if (!body_only) {
1296                 ofs << "\n\n";
1297                 sgml::closeTag(ofs, 0, false, top_element);
1298         }
1299
1300         ofs.close();
1301         // How to check for successful close
1302
1303         // we want this to be true outside previews (for insetexternal)
1304         niceFile = true;
1305
1306         users->showErrorList(_("LinuxDoc"));
1307 }
1308
1309
1310 // checks, if newcol chars should be put into this line
1311 // writes newline, if necessary.
1312 namespace {
1313
1314 void sgmlLineBreak(ostream & os, string::size_type & colcount,
1315                           string::size_type newcol)
1316 {
1317         colcount += newcol;
1318         if (colcount > lyxrc.ascii_linelen) {
1319                 os << "\n";
1320                 colcount = newcol; // assume write after this call
1321         }
1322 }
1323
1324 enum PAR_TAG {
1325         NONE=0,
1326         TT = 1,
1327         SF = 2,
1328         BF = 4,
1329         IT = 8,
1330         SL = 16,
1331         EM = 32
1332 };
1333
1334
1335 string tag_name(PAR_TAG const & pt) {
1336         switch (pt) {
1337         case NONE: return "!-- --";
1338         case TT: return "tt";
1339         case SF: return "sf";
1340         case BF: return "bf";
1341         case IT: return "it";
1342         case SL: return "sl";
1343         case EM: return "em";
1344         }
1345         return "";
1346 }
1347
1348
1349 inline
1350 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
1351 {
1352         p1 = static_cast<PAR_TAG>(p1 | p2);
1353 }
1354
1355
1356 inline
1357 void reset(PAR_TAG & p1, PAR_TAG const & p2)
1358 {
1359         p1 = static_cast<PAR_TAG>(p1 & ~p2);
1360 }
1361
1362 } // anon
1363
1364
1365 // Handle internal paragraph parsing -- layout already processed.
1366 void Buffer::simpleLinuxDocOnePar(ostream & os,
1367         ParagraphList::iterator par,
1368         Paragraph::depth_type /*depth*/) const
1369 {
1370         LyXLayout_ptr const & style = par->layout();
1371
1372         string::size_type char_line_count = 5;     // Heuristic choice ;-)
1373
1374         // gets paragraph main font
1375         LyXFont font_old;
1376         bool desc_on;
1377         if (style->labeltype == LABEL_MANUAL) {
1378                 font_old = style->labelfont;
1379                 desc_on = true;
1380         } else {
1381                 font_old = style->font;
1382                 desc_on = false;
1383         }
1384
1385         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
1386         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
1387         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
1388         bool is_em = false;
1389
1390         stack<PAR_TAG> tag_state;
1391         // parsing main loop
1392         for (pos_type i = 0; i < par->size(); ++i) {
1393
1394                 PAR_TAG tag_close = NONE;
1395                 list < PAR_TAG > tag_open;
1396
1397                 LyXFont const font = par->getFont(params, i, outerFont(par, paragraphs));
1398
1399                 if (font_old.family() != font.family()) {
1400                         switch (family_type) {
1401                         case LyXFont::SANS_FAMILY:
1402                                 tag_close |= SF;
1403                                 break;
1404                         case LyXFont::TYPEWRITER_FAMILY:
1405                                 tag_close |= TT;
1406                                 break;
1407                         default:
1408                                 break;
1409                         }
1410
1411                         family_type = font.family();
1412
1413                         switch (family_type) {
1414                         case LyXFont::SANS_FAMILY:
1415                                 tag_open.push_back(SF);
1416                                 break;
1417                         case LyXFont::TYPEWRITER_FAMILY:
1418                                 tag_open.push_back(TT);
1419                                 break;
1420                         default:
1421                                 break;
1422                         }
1423                 }
1424
1425                 if (font_old.series() != font.series()) {
1426                         switch (series_type) {
1427                         case LyXFont::BOLD_SERIES:
1428                                 tag_close |= BF;
1429                                 break;
1430                         default:
1431                                 break;
1432                         }
1433
1434                         series_type = font.series();
1435
1436                         switch (series_type) {
1437                         case LyXFont::BOLD_SERIES:
1438                                 tag_open.push_back(BF);
1439                                 break;
1440                         default:
1441                                 break;
1442                         }
1443
1444                 }
1445
1446                 if (font_old.shape() != font.shape()) {
1447                         switch (shape_type) {
1448                         case LyXFont::ITALIC_SHAPE:
1449                                 tag_close |= IT;
1450                                 break;
1451                         case LyXFont::SLANTED_SHAPE:
1452                                 tag_close |= SL;
1453                                 break;
1454                         default:
1455                                 break;
1456                         }
1457
1458                         shape_type = font.shape();
1459
1460                         switch (shape_type) {
1461                         case LyXFont::ITALIC_SHAPE:
1462                                 tag_open.push_back(IT);
1463                                 break;
1464                         case LyXFont::SLANTED_SHAPE:
1465                                 tag_open.push_back(SL);
1466                                 break;
1467                         default:
1468                                 break;
1469                         }
1470                 }
1471                 // handle <em> tag
1472                 if (font_old.emph() != font.emph()) {
1473                         if (font.emph() == LyXFont::ON) {
1474                                 tag_open.push_back(EM);
1475                                 is_em = true;
1476                         }
1477                         else if (is_em) {
1478                                 tag_close |= EM;
1479                                 is_em = false;
1480                         }
1481                 }
1482
1483                 list < PAR_TAG > temp;
1484                 while (!tag_state.empty() && tag_close) {
1485                         PAR_TAG k =  tag_state.top();
1486                         tag_state.pop();
1487                         os << "</" << tag_name(k) << '>';
1488                         if (tag_close & k)
1489                                 reset(tag_close,k);
1490                         else
1491                                 temp.push_back(k);
1492                 }
1493
1494                 for(list< PAR_TAG >::const_iterator j = temp.begin();
1495                     j != temp.end(); ++j) {
1496                         tag_state.push(*j);
1497                         os << '<' << tag_name(*j) << '>';
1498                 }
1499
1500                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
1501                     j != tag_open.end(); ++j) {
1502                         tag_state.push(*j);
1503                         os << '<' << tag_name(*j) << '>';
1504                 }
1505
1506                 char c = par->getChar(i);
1507
1508                 if (c == Paragraph::META_INSET) {
1509                         Inset * inset = par->getInset(i);
1510                         inset->linuxdoc(this, os);
1511                         font_old = font;
1512                         continue;
1513                 }
1514
1515                 if (style->latexparam() == "CDATA") {
1516                         // "TeX"-Mode on == > SGML-Mode on.
1517                         if (c != '\0')
1518                                 os << c;
1519                         ++char_line_count;
1520                 } else {
1521                         bool ws;
1522                         string str;
1523                         boost::tie(ws, str) = sgml::escapeChar(c);
1524                         if (ws && !style->free_spacing && !par->isFreeSpacing()) {
1525                                 // in freespacing mode, spaces are
1526                                 // non-breaking characters
1527                                 if (desc_on) {// if char is ' ' then...
1528
1529                                         ++char_line_count;
1530                                         sgmlLineBreak(os, char_line_count, 6);
1531                                         os << "</tag>";
1532                                         desc_on = false;
1533                                 } else  {
1534                                         sgmlLineBreak(os, char_line_count, 1);
1535                                         os << c;
1536                                 }
1537                         } else {
1538                                 os << str;
1539                                 char_line_count += str.length();
1540                         }
1541                 }
1542                 font_old = font;
1543         }
1544
1545         while (!tag_state.empty()) {
1546                 os << "</" << tag_name(tag_state.top()) << '>';
1547                 tag_state.pop();
1548         }
1549
1550         // resets description flag correctly
1551         if (desc_on) {
1552                 // <tag> not closed...
1553                 sgmlLineBreak(os, char_line_count, 6);
1554                 os << "</tag>";
1555         }
1556 }
1557
1558
1559 // Print an error message.
1560 void Buffer::sgmlError(ParagraphList::iterator pit, int pos,
1561                        string const & message) const
1562 {
1563         users->addError(ErrorItem(message, string(), pit->id(), pos, pos));
1564 }
1565
1566
1567 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
1568 {
1569         ofstream ofs(fname.c_str());
1570         if (!ofs) {
1571                 string const file = MakeDisplayPath(fname, 50);
1572                 string text = bformat(_("Could not save the specified document\n%1$s.\n"),
1573                         file);
1574                 Alert::error(_("Could not save document"), text);
1575                 return;
1576         }
1577
1578         niceFile = nice; // this will be used by Insetincludes.
1579
1580         LaTeXFeatures features(params);
1581         validate(features);
1582
1583         texrow.reset();
1584
1585         LyXTextClass const & tclass = params.getLyXTextClass();
1586         string top_element = tclass.latexname();
1587
1588         if (!only_body) {
1589                 ofs << "<!DOCTYPE " << top_element
1590                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
1591
1592                 string preamble = params.preamble;
1593                 const string name = nice ? ChangeExtension(filename_, ".sgml")
1594                          : fname;
1595                 preamble += features.getIncludedFiles(name);
1596                 preamble += features.getLyXSGMLEntities();
1597
1598                 if (!preamble.empty()) {
1599                         ofs << "\n [ " << preamble << " ]";
1600                 }
1601                 ofs << ">\n\n";
1602         }
1603
1604         string top = top_element;
1605         top += " lang=\"";
1606         top += params.language->code();
1607         top += '"';
1608
1609         if (!params.options.empty()) {
1610                 top += ' ';
1611                 top += params.options;
1612         }
1613         sgml::openTag(ofs, 0, false, top);
1614
1615         ofs << "<!-- DocBook file was created by " << lyx_docversion
1616             << "\n  See http://www.lyx.org/ for more information -->\n";
1617
1618         vector<string> environment_stack(10);
1619         vector<string> environment_inner(10);
1620         vector<string> command_stack(10);
1621
1622         bool command_flag = false;
1623         Paragraph::depth_type command_depth = 0;
1624         Paragraph::depth_type command_base = 0;
1625         Paragraph::depth_type cmd_depth = 0;
1626         Paragraph::depth_type depth = 0; // paragraph depth
1627
1628         string item_name;
1629         string command_name;
1630
1631         users->resetErrorList();
1632
1633         ParagraphList::iterator par = paragraphs.begin();
1634         ParagraphList::iterator pend = paragraphs.end();
1635
1636         for (; par != pend; ++par) {
1637                 string sgmlparam;
1638                 string c_depth;
1639                 string c_params;
1640                 int desc_on = 0; // description mode
1641
1642                 LyXLayout_ptr const & style = par->layout();
1643
1644                 // environment tag closing
1645                 for (; depth > par->params().depth(); --depth) {
1646                         if (environment_inner[depth] != "!-- --") {
1647                                 item_name = "listitem";
1648                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
1649                                 if (environment_inner[depth] == "varlistentry")
1650                                         sgml::closeTag(ofs, depth+command_depth, false, environment_inner[depth]);
1651                         }
1652                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1653                         environment_stack[depth].erase();
1654                         environment_inner[depth].erase();
1655                 }
1656
1657                 if (depth == par->params().depth()
1658                    && environment_stack[depth] != style->latexname()
1659                    && !environment_stack[depth].empty()) {
1660                         if (environment_inner[depth] != "!-- --") {
1661                                 item_name= "listitem";
1662                                 sgml::closeTag(ofs, command_depth+depth, false, item_name);
1663                                 if (environment_inner[depth] == "varlistentry")
1664                                         sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1665                         }
1666
1667                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1668
1669                         environment_stack[depth].erase();
1670                         environment_inner[depth].erase();
1671                 }
1672
1673                 // Write opening SGML tags.
1674                 switch (style->latextype) {
1675                 case LATEX_PARAGRAPH:
1676                         sgml::openTag(ofs, depth + command_depth,
1677                                     false, style->latexname());
1678                         break;
1679
1680                 case LATEX_COMMAND:
1681                         if (depth != 0)
1682                                 sgmlError(par, 0,
1683                                           _("Error: Wrong depth for LatexType Command.\n"));
1684
1685                         command_name = style->latexname();
1686
1687                         sgmlparam = style->latexparam();
1688                         c_params = split(sgmlparam, c_depth,'|');
1689
1690                         cmd_depth = lyx::atoi(c_depth);
1691
1692                         if (command_flag) {
1693                                 if (cmd_depth < command_base) {
1694                                         for (Paragraph::depth_type j = command_depth;
1695                                              j >= command_base; --j) {
1696                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
1697                                                 ofs << endl;
1698                                         }
1699                                         command_depth = command_base = cmd_depth;
1700                                 } else if (cmd_depth <= command_depth) {
1701                                         for (int j = command_depth;
1702                                              j >= int(cmd_depth); --j) {
1703                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
1704                                                 ofs << endl;
1705                                         }
1706                                         command_depth = cmd_depth;
1707                                 } else
1708                                         command_depth = cmd_depth;
1709                         } else {
1710                                 command_depth = command_base = cmd_depth;
1711                                 command_flag = true;
1712                         }
1713                         if (command_stack.size() == command_depth + 1)
1714                                 command_stack.push_back(string());
1715                         command_stack[command_depth] = command_name;
1716
1717                         // treat label as a special case for
1718                         // more WYSIWYM handling.
1719                         // This is a hack while paragraphs can't have
1720                         // attributes, like id in this case.
1721                         if (par->isInset(0)) {
1722                                 Inset * inset = par->getInset(0);
1723                                 Inset::Code lyx_code = inset->lyxCode();
1724                                 if (lyx_code == Inset::LABEL_CODE) {
1725                                         command_name += " id=\"";
1726                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
1727                                         command_name += '"';
1728                                         desc_on = 3;
1729                                 }
1730                         }
1731
1732                         sgml::openTag(ofs, depth + command_depth, false, command_name);
1733
1734                         item_name = c_params.empty() ? "title" : c_params;
1735                         sgml::openTag(ofs, depth + 1 + command_depth, false, item_name);
1736                         break;
1737
1738                 case LATEX_ENVIRONMENT:
1739                 case LATEX_ITEM_ENVIRONMENT:
1740                         if (depth < par->params().depth()) {
1741                                 depth = par->params().depth();
1742                                 environment_stack[depth].erase();
1743                         }
1744
1745                         if (environment_stack[depth] != style->latexname()) {
1746                                 if (environment_stack.size() == depth + 1) {
1747                                         environment_stack.push_back("!-- --");
1748                                         environment_inner.push_back("!-- --");
1749                                 }
1750                                 environment_stack[depth] = style->latexname();
1751                                 environment_inner[depth] = "!-- --";
1752                                 sgml::openTag(ofs, depth + command_depth, false, environment_stack[depth]);
1753                         } else {
1754                                 if (environment_inner[depth] != "!-- --") {
1755                                         item_name= "listitem";
1756                                         sgml::closeTag(ofs, command_depth + depth, false, item_name);
1757                                         if (environment_inner[depth] == "varlistentry")
1758                                                 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1759                                 }
1760                         }
1761
1762                         if (style->latextype == LATEX_ENVIRONMENT) {
1763                                 if (!style->latexparam().empty()) {
1764                                         if (style->latexparam() == "CDATA")
1765                                                 ofs << "<![CDATA[";
1766                                         else
1767                                                 sgml::openTag(ofs, depth + command_depth, false, style->latexparam());
1768                                 }
1769                                 break;
1770                         }
1771
1772                         desc_on = (style->labeltype == LABEL_MANUAL);
1773
1774                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1775                         sgml::openTag(ofs, depth + 1 + command_depth,
1776                                     false, environment_inner[depth]);
1777
1778                         item_name = desc_on ? "term" : "para";
1779                         sgml::openTag(ofs, depth + 1 + command_depth,
1780                                     false, item_name);
1781                         break;
1782                 default:
1783                         sgml::openTag(ofs, depth + command_depth,
1784                                     false, style->latexname());
1785                         break;
1786                 }
1787
1788                 simpleDocBookOnePar(ofs, par, desc_on,
1789                                     depth + 1 + command_depth);
1790
1791                 string end_tag;
1792                 // write closing SGML tags
1793                 switch (style->latextype) {
1794                 case LATEX_COMMAND:
1795                         end_tag = c_params.empty() ? "title" : c_params;
1796                         sgml::closeTag(ofs, depth + command_depth,
1797                                      false, end_tag);
1798                         break;
1799                 case LATEX_ENVIRONMENT:
1800                         if (!style->latexparam().empty()) {
1801                                 if (style->latexparam() == "CDATA")
1802                                         ofs << "]]>";
1803                                 else
1804                                         sgml::closeTag(ofs, depth + command_depth, false, style->latexparam());
1805                         }
1806                         break;
1807                 case LATEX_ITEM_ENVIRONMENT:
1808                         if (desc_on == 1) break;
1809                         end_tag = "para";
1810                         sgml::closeTag(ofs, depth + 1 + command_depth, false, end_tag);
1811                         break;
1812                 case LATEX_PARAGRAPH:
1813                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
1814                         break;
1815                 default:
1816                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
1817                         break;
1818                 }
1819         }
1820
1821         // Close open tags
1822         for (int d = depth; d >= 0; --d) {
1823                 if (!environment_stack[depth].empty()) {
1824                         if (environment_inner[depth] != "!-- --") {
1825                                 item_name = "listitem";
1826                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
1827                                if (environment_inner[depth] == "varlistentry")
1828                                        sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1829                         }
1830
1831                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1832                 }
1833         }
1834
1835         for (int j = command_depth; j >= 0 ; --j)
1836                 if (!command_stack[j].empty()) {
1837                         sgml::closeTag(ofs, j, false, command_stack[j]);
1838                         ofs << endl;
1839                 }
1840
1841         ofs << "\n\n";
1842         sgml::closeTag(ofs, 0, false, top_element);
1843
1844         ofs.close();
1845         // How to check for successful close
1846
1847         // we want this to be true outside previews (for insetexternal)
1848         niceFile = true;
1849         users->showErrorList(_("DocBook"));
1850 }
1851
1852
1853 void Buffer::simpleDocBookOnePar(ostream & os,
1854                                  ParagraphList::iterator par, int & desc_on,
1855                                  Paragraph::depth_type depth) const
1856 {
1857         bool emph_flag = false;
1858
1859         LyXLayout_ptr const & style = par->layout();
1860
1861         LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
1862
1863         int char_line_count = depth;
1864         //if (!style.free_spacing)
1865         //      os << string(depth,' ');
1866
1867         // parsing main loop
1868         for (pos_type i = 0; i < par->size(); ++i) {
1869                 LyXFont font = par->getFont(params, i, outerFont(par, paragraphs));
1870
1871                 // handle <emphasis> tag
1872                 if (font_old.emph() != font.emph()) {
1873                         if (font.emph() == LyXFont::ON) {
1874                                 if (style->latexparam() == "CDATA")
1875                                         os << "]]>";
1876                                 os << "<emphasis>";
1877                                 if (style->latexparam() == "CDATA")
1878                                         os << "<![CDATA[";
1879                                 emph_flag = true;
1880                         } else if (i) {
1881                                 if (style->latexparam() == "CDATA")
1882                                         os << "]]>";
1883                                 os << "</emphasis>";
1884                                 if (style->latexparam() == "CDATA")
1885                                         os << "<![CDATA[";
1886                                 emph_flag = false;
1887                         }
1888                 }
1889
1890
1891                 if (par->isInset(i)) {
1892                         Inset * inset = par->getInset(i);
1893                         // don't print the inset in position 0 if desc_on == 3 (label)
1894                         if (i || desc_on != 3) {
1895                                 if (style->latexparam() == "CDATA")
1896                                         os << "]]>";
1897                                 inset->docbook(this, os, false);
1898                                 if (style->latexparam() == "CDATA")
1899                                         os << "<![CDATA[";
1900                         }
1901                 } else {
1902                         char c = par->getChar(i);
1903                         bool ws;
1904                         string str;
1905                         boost::tie(ws, str) = sgml::escapeChar(c);
1906
1907                         if (style->pass_thru) {
1908                                 os << c;
1909                         } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
1910                                         os << str;
1911                         } else if (desc_on ==1) {
1912                                 ++char_line_count;
1913                                 os << "\n</term><listitem><para>";
1914                                 desc_on = 2;
1915                         } else {
1916                                 os << ' ';
1917                         }
1918                 }
1919                 font_old = font;
1920         }
1921
1922         if (emph_flag) {
1923                 if (style->latexparam() == "CDATA")
1924                         os << "]]>";
1925                 os << "</emphasis>";
1926                 if (style->latexparam() == "CDATA")
1927                         os << "<![CDATA[";
1928         }
1929
1930         // resets description flag correctly
1931         if (desc_on == 1) {
1932                 // <term> not closed...
1933                 os << "</term>\n<listitem><para>&nbsp;</para>";
1934         }
1935         if (style->free_spacing)
1936                 os << '\n';
1937 }
1938
1939
1940 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1941 // Other flags: -wall -v0 -x
1942 int Buffer::runChktex()
1943 {
1944         if (!users->text) return 0;
1945
1946         users->owner()->busy(true);
1947
1948         // get LaTeX-Filename
1949         string const name = getLatexName();
1950         string path = filePath();
1951
1952         string const org_path = path;
1953         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
1954                 path = tmppath;
1955         }
1956
1957         Path p(path); // path to LaTeX file
1958         users->owner()->message(_("Running chktex..."));
1959
1960         // Remove all error insets
1961         bool const removedErrorInsets = users->removeAutoInsets();
1962
1963         // Generate the LaTeX file if neccessary
1964         LatexRunParams runparams;
1965         runparams.flavor = LatexRunParams::LATEX;
1966         makeLaTeXFile(name, org_path, runparams, false);
1967
1968         TeXErrors terr;
1969         Chktex chktex(lyxrc.chktex_command, name, filePath());
1970         int res = chktex.run(terr); // run chktex
1971
1972         if (res == -1) {
1973                 Alert::error(_("chktex failure"),
1974                         _("Could not run chktex successfully."));
1975         } else if (res > 0) {
1976                 // Insert all errors as errors boxes
1977                 ErrorList el (*this, terr);
1978                 users->setErrorList(el);
1979                 users->showErrorList(_("ChkTeX"));
1980         }
1981
1982         // if we removed error insets before we ran chktex or if we inserted
1983         // error insets after we ran chktex, this must be run:
1984         if (removedErrorInsets || res) {
1985 #warning repaint needed here, or do you mean update() ?
1986                 users->repaint();
1987                 users->fitCursor();
1988         }
1989         users->owner()->busy(false);
1990
1991         return res;
1992 }
1993
1994
1995 void Buffer::validate(LaTeXFeatures & features) const
1996 {
1997         LyXTextClass const & tclass = params.getLyXTextClass();
1998
1999         if (params.tracking_changes) {
2000                 features.require("dvipost");
2001                 features.require("color");
2002         }
2003
2004         // AMS Style is at document level
2005         if (params.use_amsmath == BufferParams::AMS_ON
2006             || tclass.provides(LyXTextClass::amsmath))
2007                 features.require("amsmath");
2008
2009         for_each(paragraphs.begin(), paragraphs.end(),
2010                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
2011
2012         // the bullet shapes are buffer level not paragraph level
2013         // so they are tested here
2014         for (int i = 0; i < 4; ++i) {
2015                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2016                         int const font = params.user_defined_bullets[i].getFont();
2017                         if (font == 0) {
2018                                 int const c = params
2019                                         .user_defined_bullets[i]
2020                                         .getCharacter();
2021                                 if (c == 16
2022                                    || c == 17
2023                                    || c == 25
2024                                    || c == 26
2025                                    || c == 31) {
2026                                         features.require("latexsym");
2027                                 }
2028                         } else if (font == 1) {
2029                                 features.require("amssymb");
2030                         } else if ((font >= 2 && font <= 5)) {
2031                                 features.require("pifont");
2032                         }
2033                 }
2034         }
2035
2036         if (lyxerr.debugging(Debug::LATEX)) {
2037                 features.showStruct();
2038         }
2039 }
2040
2041
2042 vector<string> const Buffer::getLabelList() const
2043 {
2044         /// if this is a child document and the parent is already loaded
2045         /// Use the parent's list instead  [ale990407]
2046         if (!params.parentname.empty()
2047             && bufferlist.exists(params.parentname)) {
2048                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2049                 if (tmp)
2050                         return tmp->getLabelList();
2051         }
2052
2053         vector<string> label_list;
2054         for (inset_iterator it = inset_const_iterator_begin();
2055              it != inset_const_iterator_end(); ++it) {
2056                 vector<string> const l = it->getLabelList();
2057                 label_list.insert(label_list.end(), l.begin(), l.end());
2058         }
2059         return label_list;
2060 }
2061
2062
2063 // This is also a buffer property (ale)
2064 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys) const
2065 {
2066         /// if this is a child document and the parent is already loaded
2067         /// use the parent's list instead  [ale990412]
2068         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
2069                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2070                 if (tmp) {
2071                         tmp->fillWithBibKeys(keys);
2072                         return;
2073                 }
2074         }
2075
2076         for (inset_iterator it = inset_const_iterator_begin();
2077                 it != inset_const_iterator_end(); ++it) {
2078                 if (it->lyxCode() == Inset::BIBTEX_CODE)
2079                         static_cast<InsetBibtex &>(*it).fillWithBibKeys(this, keys);
2080                 else if (it->lyxCode() == Inset::INCLUDE_CODE)
2081                         static_cast<InsetInclude &>(*it).fillWithBibKeys(keys);
2082                 else if (it->lyxCode() == Inset::BIBITEM_CODE) {
2083                         InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
2084                         string const key = bib.getContents();
2085                         string const opt = bib.getOptions();
2086                         string const ref; // = pit->asString(this, false);
2087                         string const info = opt + "TheBibliographyRef" + ref;
2088                         keys.push_back(pair<string, string>(key, info));
2089                 }
2090         }
2091 }
2092
2093
2094 bool Buffer::isDepClean(string const & name) const
2095 {
2096         DepClean::const_iterator it = dep_clean_.find(name);
2097         if (it == dep_clean_.end())
2098                 return true;
2099         return it->second;
2100 }
2101
2102
2103 void Buffer::markDepClean(string const & name)
2104 {
2105         dep_clean_[name] = true;
2106 }
2107
2108
2109 bool Buffer::dispatch(string const & command, bool * result)
2110 {
2111         // Split command string into command and argument
2112         string cmd;
2113         string line = ltrim(command);
2114         string const arg = trim(split(line, cmd, ' '));
2115
2116         return dispatch(lyxaction.LookupFunc(cmd), arg, result);
2117 }
2118
2119
2120 bool Buffer::dispatch(int action, string const & argument, bool * result)
2121 {
2122         bool dispatched = true;
2123
2124         switch (action) {
2125                 case LFUN_EXPORT: {
2126                         bool const tmp = Exporter::Export(this, argument, false);
2127                         if (result)
2128                                 *result = tmp;
2129                         break;
2130                 }
2131
2132                 default:
2133                         dispatched = false;
2134         }
2135         return dispatched;
2136 }
2137
2138
2139 void Buffer::resizeInsets(BufferView * bv)
2140 {
2141         /// then remove all LyXText in text-insets
2142         for_each(paragraphs.begin(), paragraphs.end(),
2143                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2144 }
2145
2146
2147 void Buffer::redraw()
2148 {
2149 #warning repaint needed here, or do you mean update() ?
2150         users->repaint();
2151         users->fitCursor();
2152 }
2153
2154
2155 void Buffer::changeLanguage(Language const * from, Language const * to)
2156 {
2157         lyxerr << "Changing Language!" << endl;
2158
2159         // Take care of l10n/i18n
2160         updateDocLang(to);
2161
2162         ParIterator end = par_iterator_end();
2163         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2164                 (*it)->changeLanguage(params, from, to);
2165 }
2166
2167
2168 void Buffer::updateDocLang(Language const * nlang)
2169 {
2170         messages_.reset(new Messages(nlang->code()));
2171 }
2172
2173
2174 bool Buffer::isMultiLingual()
2175 {
2176         ParIterator end = par_iterator_end();
2177         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2178                 if ((*it)->isMultiLingual(params))
2179                         return true;
2180
2181         return false;
2182 }
2183
2184
2185 void Buffer::inset_iterator::setParagraph()
2186 {
2187         while (pit != pend) {
2188                 it = pit->insetlist.begin();
2189                 if (it != pit->insetlist.end())
2190                         return;
2191                 ++pit;
2192         }
2193 }
2194
2195
2196 Inset * Buffer::getInsetFromID(int id_arg) const
2197 {
2198         for (inset_iterator it = inset_const_iterator_begin();
2199                  it != inset_const_iterator_end(); ++it)
2200         {
2201                 if (it->id() == id_arg)
2202                         return &(*it);
2203                 Inset * in = it->getInsetFromID(id_arg);
2204                 if (in)
2205                         return in;
2206         }
2207         return 0;
2208 }
2209
2210
2211 ParIterator Buffer::getParFromID(int id) const
2212 {
2213 #warning FIXME: const correctness! (Andre)
2214         ParIterator it(const_cast<Buffer*>(this)->par_iterator_begin());
2215         ParIterator end(const_cast<Buffer*>(this)->par_iterator_end());
2216
2217 #warning FIXME, perhaps this func should return a ParIterator? (Lgb)
2218         if (id < 0) {
2219                 // John says this is called with id == -1 from undo
2220                 lyxerr << "getParFromID(), id: " << id << endl;
2221                 return end;
2222         }
2223
2224         for (; it != end; ++it)
2225                 if ((*it)->id() == id)
2226                         return it;
2227
2228         return end;
2229 }
2230
2231
2232 bool Buffer::hasParWithID(int id) const
2233 {
2234         ParIterator it(const_cast<Buffer*>(this)->par_iterator_begin());
2235         ParIterator end(const_cast<Buffer*>(this)->par_iterator_end());
2236
2237         if (id < 0) {
2238                 // John says this is called with id == -1 from undo
2239                 lyxerr << "hasParWithID(), id: " << id << endl;
2240                 return 0;
2241         }
2242
2243         for (; it != end; ++it)
2244                 if ((*it)->id() == id)
2245                         return true;
2246
2247         return false;
2248 }
2249
2250
2251 ParIterator Buffer::par_iterator_begin()
2252 {
2253         return ParIterator(paragraphs.begin(), paragraphs);
2254 }
2255
2256
2257 ParIterator Buffer::par_iterator_end()
2258 {
2259         return ParIterator(paragraphs.end(), paragraphs);
2260 }
2261
2262 ParConstIterator Buffer::par_iterator_begin() const
2263 {
2264         return ParConstIterator(paragraphs.begin(), paragraphs);
2265 }
2266
2267
2268 ParConstIterator Buffer::par_iterator_end() const
2269 {
2270         return ParConstIterator(paragraphs.end(), paragraphs);
2271 }
2272
2273
2274
2275 void Buffer::addUser(BufferView * u)
2276 {
2277         users = u;
2278 }
2279
2280
2281 void Buffer::delUser(BufferView *)
2282 {
2283         users = 0;
2284 }
2285
2286
2287 Language const * Buffer::getLanguage() const
2288 {
2289         return params.language;
2290 }
2291
2292
2293 string const Buffer::B_(string const & l10n) const
2294 {
2295         if (messages_.get()) {
2296                 return messages_->get(l10n);
2297         }
2298
2299         return _(l10n);
2300 }
2301
2302
2303 bool Buffer::isClean() const
2304 {
2305         return lyx_clean;
2306 }
2307
2308
2309 bool Buffer::isBakClean() const
2310 {
2311         return bak_clean;
2312 }
2313
2314
2315 void Buffer::markClean() const
2316 {
2317         if (!lyx_clean) {
2318                 lyx_clean = true;
2319                 updateTitles();
2320         }
2321         // if the .lyx file has been saved, we don't need an
2322         // autosave
2323         bak_clean = true;
2324 }
2325
2326
2327 void Buffer::markBakClean()
2328 {
2329         bak_clean = true;
2330 }
2331
2332
2333 void Buffer::setUnnamed(bool flag)
2334 {
2335         unnamed = flag;
2336 }
2337
2338
2339 bool Buffer::isUnnamed()
2340 {
2341         return unnamed;
2342 }
2343
2344
2345 void Buffer::markDirty()
2346 {
2347         if (lyx_clean) {
2348                 lyx_clean = false;
2349                 updateTitles();
2350         }
2351         bak_clean = false;
2352
2353         DepClean::iterator it = dep_clean_.begin();
2354         DepClean::const_iterator const end = dep_clean_.end();
2355
2356         for (; it != end; ++it) {
2357                 it->second = false;
2358         }
2359 }
2360
2361
2362 string const & Buffer::fileName() const
2363 {
2364         return filename_;
2365 }
2366
2367
2368 string const & Buffer::filePath() const
2369 {
2370         return filepath_;
2371 }
2372
2373
2374 bool Buffer::isReadonly() const
2375 {
2376         return read_only;
2377 }
2378
2379
2380 BufferView * Buffer::getUser() const
2381 {
2382         return users;
2383 }
2384
2385
2386 void Buffer::setParentName(string const & name)
2387 {
2388         params.parentname = name;
2389 }
2390
2391
2392 Buffer::inset_iterator::inset_iterator()
2393         : pit(0), pend(0)
2394 {}
2395
2396
2397 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
2398         : pit(p), pend(e)
2399 {
2400         setParagraph();
2401 }
2402
2403
2404 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
2405 {
2406         if (pit != pend) {
2407                 ++it;
2408                 if (it == pit->insetlist.end()) {
2409                         ++pit;
2410                         setParagraph();
2411                 }
2412         }
2413         return *this;
2414 }
2415
2416
2417 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
2418 {
2419         inset_iterator tmp = *this;
2420         ++*this;
2421         return tmp;
2422 }
2423
2424
2425 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
2426 {
2427         return *it.getInset();
2428 }
2429
2430
2431 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
2432 {
2433         return it.getInset();
2434 }
2435
2436
2437 ParagraphList::iterator Buffer::inset_iterator::getPar() const
2438 {
2439         return pit;
2440 }
2441
2442
2443 lyx::pos_type Buffer::inset_iterator::getPos() const
2444 {
2445         return it.getPos();
2446 }
2447
2448
2449 bool operator==(Buffer::inset_iterator const & iter1,
2450                 Buffer::inset_iterator const & iter2)
2451 {
2452         return iter1.pit == iter2.pit
2453                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
2454 }
2455
2456
2457 bool operator!=(Buffer::inset_iterator const & iter1,
2458                 Buffer::inset_iterator const & iter2)
2459 {
2460         return !(iter1 == iter2);
2461 }