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