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