]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
please Angus.
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "support/FileName.h"
16 #include "support/limited_stack.h"
17 #include "support/types.h"
18 #include "support/docstring.h"
19 #include "support/docstream.h"
20
21 #include <iosfwd>
22 #include <string>
23 #include <utility>
24 #include <vector>
25
26
27 namespace lyx {
28
29 class BufferParams;
30 class EmbeddedFiles;
31 class ErrorItem;
32 class ErrorList;
33 class FuncRequest;
34 class Inset;
35 class Font;
36 class Lexer;
37 class LyXRC;
38 class Text;
39 class LyXVC;
40 class LaTeXFeatures;
41 class Language;
42 class MacroData;
43 class OutputParams;
44 class ParConstIterator;
45 class ParIterator;
46 class ParagraphList;
47 class TeXErrors;
48 class TexRow;
49 class TocBackend;
50 class Undo;
51
52 namespace frontend {
53 class GuiBufferDelegate;
54 class WorkAreaManager;
55 }
56
57 /** The buffer object.
58  * This is the buffer object. It contains all the informations about
59  * a document loaded into LyX.
60  * The buffer object owns the Text (wrapped in an InsetText), which
61  * contains the individual paragraphs of the document.
62  *
63  *
64  * I am not sure if the class is complete or
65  * minimal, probably not.
66  * \author Lars Gullik Bjønnes
67  */
68 class Buffer {
69 public:
70         /// What type of log will \c getLogName() return?
71         enum LogType {
72                 latexlog, ///< LaTeX log
73                 buildlog  ///< Literate build log
74         };
75
76         /// Result of \c readFile()
77         enum ReadStatus {
78                 failure, ///< The file could not be read
79                 success, ///< The file could not be read
80                 wrongversion ///< The version of the file does not match ours
81         };
82
83         /// Method to check if a file is externally modified, used by 
84         /// isExternallyModified()
85         /**
86          * timestamp is fast but inaccurate. For example, the granularity
87          * of timestamp on a FAT filesystem is 2 second. Also, various operations
88          * may touch the timestamp of a file even when its content is unchanged.
89          *
90          * checksum is accurate but slow, which can be a problem when it is 
91          * frequently used, or used for a large file on a slow (network) file
92          * system.
93          */
94         enum CheckMethod {
95                 checksum_method,  ///< Use file check sum
96                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
97         };
98         
99         /** Constructor
100             \param file
101             \param b  optional \c false by default
102         */
103         explicit Buffer(std::string const & file, bool b = false);
104
105         /// Destructor
106         ~Buffer();
107
108         /** High-level interface to buffer functionality.
109             This function parses a command string and executes it
110         */
111         bool dispatch(std::string const & command, bool * result = 0);
112
113         /// Maybe we know the function already by number...
114         bool dispatch(FuncRequest const & func, bool * result = 0);
115
116         /// Load the autosaved file.
117         void loadAutoSaveFile();
118
119         /// read a new document from a string
120         bool readString(std::string const &);
121         /// load a new file
122         bool readFile(support::FileName const & filename);
123
124         /// read the header, returns number of unknown tokens
125         int readHeader(Lexer & lex);
126
127         /** Reads a file without header.
128             \param par if != 0 insert the file.
129             \return \c false if file is not completely read.
130         */
131         bool readDocument(Lexer &);
132
133         ///
134         void insertStringAsLines(ParagraphList & plist,
135                 pit_type &, pos_type &,
136                 Font const &, docstring const &, bool);
137         ///
138         ParIterator getParFromID(int id) const;
139         /// do we have a paragraph with this id?
140         bool hasParWithID(int id) const;
141
142         ///
143         frontend::WorkAreaManager & workAreaManager() const;
144
145         /** Save file.
146             Takes care of auto-save files and backup file if requested.
147             Returns \c true if the save is successful, \c false otherwise.
148         */
149         bool save() const;
150
151         /// Write document to stream. Returns \c false if unsuccesful.
152         bool write(std::ostream &) const;
153         /// Write file. Returns \c false if unsuccesful.
154         bool writeFile(support::FileName const &) const;
155
156         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
157         bool makeLaTeXFile(support::FileName const & filename,
158                            std::string const & original_path,
159                            OutputParams const &,
160                            bool output_preamble = true,
161                            bool output_body = true);
162         /** Export the buffer to LaTeX.
163             If \p os is a file stream, and params().inputenc is "auto" or
164             "default", and the buffer contains text in different languages
165             with more than one encoding, then this method will change the
166             encoding associated to \p os. Therefore you must not call this
167             method with a string stream if the output is supposed to go to a
168             file. \code
169             odocfstream ofs;
170             ofs.open("test.tex");
171             writeLaTeXSource(ofs, ...);
172             ofs.close();
173             \endcode is NOT equivalent to \code
174             odocstringstream oss;
175             writeLaTeXSource(oss, ...);
176             odocfstream ofs;
177             ofs.open("test.tex");
178             ofs << oss.str();
179             ofs.close();
180             \endcode
181          */
182         void writeLaTeXSource(odocstream & os,
183                            std::string const & original_path,
184                            OutputParams const &,
185                            bool output_preamble = true,
186                            bool output_body = true);
187         ///
188         void makeDocBookFile(support::FileName const & filename,
189                              OutputParams const & runparams_in,
190                              bool only_body = false);
191         ///
192         void writeDocBookSource(odocstream & os, std::string const & filename,
193                              OutputParams const & runparams_in,
194                              bool only_body = false);
195         /// returns the main language for the buffer (document)
196         Language const * getLanguage() const;
197         /// get l10n translated to the buffers language
198         docstring const B_(std::string const & l10n) const;
199
200         ///
201         int runChktex();
202         /// return true if the main lyx file does not need saving
203         bool isClean() const;
204         ///
205         bool isBakClean() const;
206         ///
207         bool isDepClean(std::string const & name) const;
208
209         /// whether or not disk file has been externally modified
210         bool isExternallyModified(CheckMethod method) const;
211
212         /// save timestamp and checksum of the given file.
213         void saveCheckSum(std::string const & file) const;
214
215         /// mark the main lyx file as not needing saving
216         void markClean() const;
217
218         ///
219         void markBakClean() const;
220
221         ///
222         void markDepClean(std::string const & name);
223
224         ///
225         void setUnnamed(bool flag = true);
226
227         ///
228         bool isUnnamed() const;
229
230         /// Mark this buffer as dirty.
231         void markDirty();
232
233         /// Returns the buffer's filename. It is always an absolute path.
234         std::string const fileName() const;
235
236         /// Returns the the path where the buffer lives.
237         /// It is always an absolute path.
238         std::string const & filePath() const;
239
240         /** A transformed version of the file name, adequate for LaTeX.
241             \param no_path optional if \c true then the path is stripped.
242         */
243         std::string const getLatexName(bool no_path = true) const;
244
245         /// Get thee name and type of the log.
246         std::pair<LogType, std::string> const getLogName() const;
247
248         /// Change name of buffer. Updates "read-only" flag.
249         void setFileName(std::string const & newfile);
250
251         /// Name of the document's parent
252         void setParentName(std::string const &);
253
254         /** Get the document's master (or \c this if this is not a
255             child document)
256          */
257         Buffer const * getMasterBuffer() const;
258         /** Get the document's master (or \c this if this is not a
259             child document)
260          */
261         Buffer * getMasterBuffer();
262
263         /// Is buffer read-only?
264         bool isReadonly() const;
265
266         /// Set buffer read-only flag
267         void setReadonly(bool flag = true);
268
269         /// returns \c true if the buffer contains a LaTeX document
270         bool isLatex() const;
271         /// returns \c true if the buffer contains a DocBook document
272         bool isDocBook() const;
273         /// returns \c true if the buffer contains a Wed document
274         bool isLiterate() const;
275
276         /** Validate a buffer for LaTeX.
277             This validates the buffer, and returns a struct for use by
278             #makeLaTeX# and others. Its main use is to figure out what
279             commands and packages need to be included in the LaTeX file.
280             It (should) also check that the needed constructs are there
281             (i.e. that the \refs points to coresponding \labels). It
282             should perhaps inset "error" insets to help the user correct
283             obvious mistakes.
284         */
285         void validate(LaTeXFeatures &) const;
286
287         /// Update the cache with all bibfiles in use (including bibfiles
288         /// of loaded child documents).
289         void updateBibfilesCache();
290         /// Return the cache with all bibfiles in use (including bibfiles
291         /// of loaded child documents).
292         std::vector<support::FileName> const & getBibfilesCache() const;
293         ///
294         void getLabelList(std::vector<docstring> &) const;
295
296         ///
297         void changeLanguage(Language const * from, Language const * to);
298
299         ///
300         bool isMultiLingual() const;
301
302         /// Does this mean that this is buffer local?
303         limited_stack<Undo> & undostack();
304         limited_stack<Undo> const & undostack() const;
305
306         /// Does this mean that this is buffer local?
307         limited_stack<Undo> & redostack();
308         limited_stack<Undo> const & redostack() const;
309
310         ///
311         BufferParams & params();
312         BufferParams const & params() const;
313
314         /** The list of paragraphs.
315             This is a linked list of paragraph, this list holds the
316             whole contents of the document.
317          */
318         ParagraphList & paragraphs();
319         ParagraphList const & paragraphs() const;
320
321         /// LyX version control object.
322         LyXVC & lyxvc();
323         LyXVC const & lyxvc() const;
324
325         /// Where to put temporary files.
326         std::string const & temppath() const;
327
328         /// Used when typesetting to place errorboxes.
329         TexRow & texrow();
330         TexRow const & texrow() const;
331
332         ///
333         ParIterator par_iterator_begin();
334         ///
335         ParConstIterator par_iterator_begin() const;
336         ///
337         ParIterator par_iterator_end();
338         ///
339         ParConstIterator par_iterator_end() const;
340
341         /** \returns true only when the file is fully loaded.
342          *  Used to prevent the premature generation of previews
343          *  and by the citation inset.
344          */
345         bool fully_loaded() const;
346         /// Set by buffer_funcs' newFile.
347         void fully_loaded(bool);
348
349         /// Our main text (inside the top InsetText)
350         Text & text() const;
351
352         /// Our top InsetText!
353         Inset & inset() const;
354
355         //
356         // Macro handling
357         //
358         ///
359         void buildMacros();
360         ///
361         bool hasMacro(docstring const & name) const;
362         ///
363         MacroData const & getMacro(docstring const & name) const;
364         ///
365         void insertMacro(docstring const & name, MacroData const & data);
366
367         /// Replace the inset contents for insets which Inset::Code is equal
368         /// to the passed \p inset_code.
369         /// FIXME: we pass Inset::Code as an int in order to avoid the inclusion
370         /// of "Inset.h". It would be better to put Inset::Code in its own
371         /// header.
372         void changeRefsIfUnique(docstring const & from, docstring const & to,
373                 int inset_code);
374
375 /// get source code (latex/docbook) for some paragraphs, or all paragraphs
376 /// including preamble
377         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end, bool full_source);
378
379         /// errorLists_ accessors.
380         //@{
381         ErrorList const & errorList(std::string const & type) const;
382         ErrorList & errorList(std::string const & type);
383         //@}
384
385         //@{
386         TocBackend & tocBackend();
387         TocBackend const & tocBackend() const;
388         //@}
389         
390         //@{
391         EmbeddedFiles & embeddedFiles();
392         EmbeddedFiles const & embeddedFiles() const;
393         //@}
394        
395         /// This function is called when the buffer is changed.
396         void changed() const;
397         /// This function is called when the buffer structure is changed.
398         void structureChanged() const;
399         /// This function is called when an embedded file is changed
400         void embeddingChanged() const;
401         /// This function is called when some parsing error shows up.
402         void errors(std::string const & err) const;
403         /// This function is called when the buffer busy status change.
404         void busy(bool on) const;
405         /// This function is called when the buffer readonly status change.
406         void readonly(bool on) const;
407         /// Update window titles of all users.
408         void updateTitles() const;
409         /// Reset autosave timers for all users.
410         void resetAutosaveTimers() const;
411         ///
412         void message(docstring const & msg) const;
413
414         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
415
416         ///
417         void autoSave() const;
418         ///
419         bool writeAs(std::string const & newname = std::string());
420         ///
421         bool menuWrite();
422
423 private:
424         /** Inserts a file into a document
425             \return \c false if method fails.
426         */
427         ReadStatus readFile(Lexer &, support::FileName const & filename,
428                             bool fromString = false);
429
430         /// Use the Pimpl idiom to hide the internals.
431         class Impl;
432         /// The pointer never changes although *pimpl_'s contents may.
433         Impl * const pimpl_;
434
435         /// A cache for the bibfiles (including bibfiles of loaded child
436         /// documents), needed for appropriate update of natbib labels.
437         mutable std::vector<support::FileName> bibfilesCache_;
438
439         frontend::GuiBufferDelegate * gui_;
440 };
441
442
443 } // namespace lyx
444
445 #endif