2 * \file frontend_helpers.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Angus Leeming
9 * Full author contact details are available in file CREDITS.
14 #include "frontend_helpers.h"
17 #include "BufferParams.h"
24 #include "frontends/FileDialog.h"
25 #include "frontends/alert.h"
27 #include "support/filetools.h"
28 #include "support/lstrings.h"
29 #include "support/Package.h"
30 #include "support/filetools.h"
31 #include "support/lstrings.h"
32 #include "support/lyxalgo.h"
33 #include "support/os.h"
34 #include "support/Package.h"
35 #include "support/Path.h"
36 #include "support/Systemcall.h"
38 #include <boost/cregex.hpp>
39 #include <boost/regex.hpp>
51 using support::ascii_lowercase;
52 using support::bformat;
53 using support::compare_ascii_no_case;
54 using support::contains;
55 using support::getVectorFromString;
57 using support::prefixIs;
68 vector<string> const init_possible_cite_commands()
70 char const * const pos[] = {
72 "citet", "citep", "citealt", "citealp",
73 "citeauthor", "citeyear", "citeyearpar",
74 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
75 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
76 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
78 "footcite", "footcitet", "footcitep", "footcitealt",
79 "footcitealp", "footciteauthor", "footciteyear",
85 size_t const size_pos = sizeof(pos) / sizeof(pos[0]);
87 return vector<string>(pos, pos + size_pos);
91 vector<string> const & possible_cite_commands()
93 static vector<string> const pos = init_possible_cite_commands();
98 bool is_possible_cite_command(string const & input)
100 vector<string> const & possibles = possible_cite_commands();
101 vector<string>::const_iterator const end = possibles.end();
102 return std::find(possibles.begin(), end, input) != end;
106 string const default_cite_command(CiteEngine engine)
113 case ENGINE_NATBIB_AUTHORYEAR:
116 case ENGINE_NATBIB_NUMERICAL:
127 static const docstring TheBibliographyRef(from_ascii("TheBibliographyRef"));
132 string const asValidLatexCommand(string const & input,
133 CiteEngine const engine)
135 string const default_str = default_cite_command(engine);
136 if (!is_possible_cite_command(input))
142 output = default_str;
145 case ENGINE_NATBIB_AUTHORYEAR:
146 case ENGINE_NATBIB_NUMERICAL:
147 if (input == "cite" || input == "citefield" ||
148 input == "citetitle" || input == "cite*")
149 output = default_str;
150 else if (prefixIs(input, "foot"))
151 output = input.substr(4);
156 case ENGINE_JURABIB: {
157 // Jurabib does not support the 'uppercase' natbib style.
159 output = string(1, 'c') + input.substr(1);
163 // Jurabib does not support the 'full' natbib style.
164 string::size_type const n = output.size() - 1;
165 if (output != "cite*" && output[n] == '*')
166 output = output.substr(0, n);
176 docstring const familyName(docstring const & name)
181 // Very simple parser
182 docstring fname = name;
184 // possible authorname combinations are:
185 // "Surname, FirstName"
187 // "FirstName Surname"
189 docstring::size_type idx = fname.find(',');
190 if (idx != docstring::npos)
191 return ltrim(fname.substr(0, idx));
192 idx = fname.rfind('.');
193 if (idx != docstring::npos && idx + 1 < fname.size())
194 fname = ltrim(fname.substr(idx + 1));
195 // test if we have a LaTeX Space in front
196 if (fname[0] == '\\')
197 return fname.substr(2);
203 docstring const getAbbreviatedAuthor(InfoMap const & map, string const & key)
205 BOOST_ASSERT(!map.empty());
207 InfoMap::const_iterator it = map.find(key);
210 docstring const & data = it->second;
212 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
213 docstring::size_type const pos = data.find(TheBibliographyRef);
214 if (pos != docstring::npos) {
219 docstring const opt = trim(data.substr(0, pos - 1));
224 split(opt, authors, '(');
228 docstring author = parseBibTeX(data, "author");
231 author = parseBibTeX(data, "editor");
233 if (author.empty()) {
234 author = parseBibTeX(data, "key");
237 return from_utf8(key);
241 vector<docstring> const authors = getVectorFromString(author, from_ascii(" and "));
245 if (authors.size() == 2)
246 return bformat(_("%1$s and %2$s"),
247 familyName(authors[0]), familyName(authors[1]));
249 if (authors.size() > 2)
250 return bformat(_("%1$s et al."), familyName(authors[0]));
252 return familyName(authors[0]);
256 docstring const getYear(InfoMap const & map, string const & key)
258 BOOST_ASSERT(!map.empty());
260 InfoMap::const_iterator it = map.find(key);
263 docstring const & data = it->second;
265 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
266 docstring::size_type const pos = data.find(TheBibliographyRef);
267 if (pos != docstring::npos) {
272 docstring const opt =
273 trim(data.substr(0, pos - 1));
278 docstring const tmp = split(opt, authors, '(');
280 split(tmp, year, ')');
285 docstring year = parseBibTeX(data, "year");
295 // A functor for use with std::sort, leading to case insensitive sorting
296 class compareNoCase: public std::binary_function<string, string, bool>
299 bool operator()(string const & s1, string const & s2) const {
300 return compare_ascii_no_case(s1, s2) < 0;
307 vector<string> const getKeys(InfoMap const & map)
309 vector<string> bibkeys;
310 InfoMap::const_iterator it = map.begin();
311 InfoMap::const_iterator end = map.end();
312 for (; it != end; ++it) {
313 bibkeys.push_back(it->first);
316 std::sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
321 docstring const getInfo(InfoMap const & map, string const & key)
323 BOOST_ASSERT(!map.empty());
325 InfoMap::const_iterator it = map.find(key);
328 docstring const & data = it->second;
330 // is the entry a BibTeX one or one from lyx-layout "bibliography"?
331 docstring::size_type const pos = data.find(TheBibliographyRef);
332 if (pos != docstring::npos) {
333 docstring::size_type const pos2 = pos + TheBibliographyRef.size();
334 docstring const info = trim(data.substr(pos2));
338 // Search for all possible "required" keys
339 docstring author = parseBibTeX(data, "author");
341 author = parseBibTeX(data, "editor");
343 docstring year = parseBibTeX(data, "year");
344 docstring title = parseBibTeX(data, "title");
345 docstring booktitle = parseBibTeX(data, "booktitle");
346 docstring chapter = parseBibTeX(data, "chapter");
347 docstring number = parseBibTeX(data, "number");
348 docstring volume = parseBibTeX(data, "volume");
349 docstring pages = parseBibTeX(data, "pages");
350 docstring annote = parseBibTeX(data, "annote");
351 docstring media = parseBibTeX(data, "journal");
353 media = parseBibTeX(data, "publisher");
355 media = parseBibTeX(data, "school");
357 media = parseBibTeX(data, "institution");
359 odocstringstream result;
361 result << author << ", ";
364 if (!booktitle.empty())
365 result << ", in " << booktitle;
366 if (!chapter.empty())
367 result << ", Ch. " << chapter;
369 result << ", " << media;
371 result << ", vol. " << volume;
373 result << ", no. " << number;
375 result << ", pp. " << pages;
377 result << ", " << year;
379 result << "\n\n" << annote;
381 docstring const result_str = rtrim(result.str());
382 if (!result_str.empty())
385 // This should never happen (or at least be very unusual!)
392 // Escape special chars.
393 // All characters are literals except: '.|*?+(){}[]^$\'
394 // These characters are literals when preceded by a "\", which is done here
395 // @todo: This function should be moved to support, and then the test in tests
396 // should be moved there as well.
397 string const escape_special_chars(string const & expr)
399 // Search for all chars '.|*?+(){}[^$]\'
400 // Note that '[' and '\' must be escaped.
401 // This is a limitation of boost::regex, but all other chars in BREs
402 // are assumed literal.
403 boost::regex reg("[].|*?+(){}^$\\[\\\\]");
405 // $& is a perl-like expression that expands to all
406 // of the current match
407 // The '$' must be prefixed with the escape character '\' for
408 // boost to treat it as a literal.
409 // Thus, to prefix a matched expression with '\', we use:
410 return boost::regex_replace(expr, reg, "\\\\$&");
414 // A functor for use with std::find_if, used to ascertain whether a
415 // data entry matches the required regex_
416 // @throws: boost::regex_error if the supplied regex pattern is not valid
417 // @todo: This function should be moved to support.
418 class RegexMatch : public std::unary_function<string, bool>
421 // re and icase are used to construct an instance of boost::RegEx.
422 // if icase is true, then matching is insensitive to case
423 RegexMatch(InfoMap const & m, string const & re, bool icase)
424 : map_(m), regex_(re, icase) {}
426 bool operator()(string const & key) const {
427 // the data searched is the key + its associated BibTeX/biblio
430 InfoMap::const_iterator info = map_.find(key);
431 if (info != map_.end())
433 data += ' ' + to_utf8(info->second);
435 // Attempts to find a match for the current RE
436 // somewhere in data.
437 return boost::regex_search(data, regex_);
441 mutable boost::regex regex_;
447 vector<string>::const_iterator
448 searchKeys(InfoMap const & theMap,
449 vector<string> const & keys,
450 string const & search_expr,
451 vector<string>::const_iterator start,
456 // Preliminary checks
457 if (start < keys.begin() || start >= keys.end())
460 string expr = trim(search_expr);
465 // We must escape special chars in the search_expr so that
466 // it is treated as a simple string by boost::regex.
467 expr = escape_special_chars(expr);
470 // Build the functor that will be passed to find_if.
471 RegexMatch const match(theMap, expr, !caseSensitive);
473 // Search the vector of 'keys' from 'start' for one
474 // that matches the predicate 'match'. Searching can
475 // be forward or backward from start.
477 return std::find_if(start, keys.end(), match);
479 vector<string>::const_reverse_iterator rit(start);
480 vector<string>::const_reverse_iterator rend = keys.rend();
481 rit = std::find_if(rit, rend, match);
485 // This is correct and always safe.
486 // (See Meyer's Effective STL, Item 28.)
487 return (++rit).base();
489 catch (boost::regex_error &) {
495 docstring const parseBibTeX(docstring data, string const & findkey)
497 // at first we delete all characters right of '%' and
498 // replace tabs through a space and remove leading spaces
499 // we read the data line by line so that the \n are
503 docstring dummy = token(data,'\n', Entries);
504 while (!dummy.empty()) {
506 dummy = subst(dummy, '\t', ' ');
508 dummy = ltrim(dummy);
509 // ignore lines with a beginning '%' or ignore all right of %
510 docstring::size_type const idx =
511 dummy.empty() ? docstring::npos : dummy.find('%');
512 if (idx != docstring::npos)
513 // Check if this is really a comment or just "\%"
514 if (idx == 0 || dummy[idx - 1] != '\\')
515 dummy.erase(idx, docstring::npos);
517 // This is "\%", so just erase the '\'
518 dummy.erase(idx - 1, 1);
519 // do we have a new token or a new line of
520 // the same one? In the first case we ignore
521 // the \n and in the second we replace it
523 if (!dummy.empty()) {
524 if (!contains(dummy, '='))
525 data_ += ' ' + dummy;
529 dummy = token(data, '\n', ++Entries);
532 // replace double commas with "" for easy scanning
533 data = subst(data_, from_ascii(",,"), from_ascii("\"\""));
539 // now get only the important line of the bibtex entry.
540 // all entries are devided by ',' except the last one.
542 // now we have same behaviour for all entries because the last one
546 // parsing of title and booktitle is different from the
547 // others, because booktitle contains title
549 dummy = token(data, ',', Entries++);
550 if (!dummy.empty()) {
551 found = contains(ascii_lowercase(dummy), from_ascii(findkey));
552 if (findkey == "title" &&
553 contains(ascii_lowercase(dummy), from_ascii("booktitle")))
556 } while (!found && !dummy.empty());
561 // we are not sure, if we get all, because "key= "blah, blah" is
563 // Therefore we read all until the next "=" character, which follows a
565 docstring keyvalue = dummy;
566 dummy = token(data, ',', Entries++);
567 while (!contains(dummy, '=') && !dummy.empty()) {
568 keyvalue += ',' + dummy;
569 dummy = token(data, ',', Entries++);
572 // replace double "" with originals ,, (two commas)
573 // leaving us with the all-important line
574 data = subst(keyvalue, from_ascii("\"\""), from_ascii(",,"));
579 // 2. if there is no opening '{' then a closing '{' is probably cruft.
580 if (!contains(data, '{'))
581 data = rtrim(data, "}");
582 // happens, when last keyword
583 docstring::size_type const idx =
584 !data.empty() ? data.find('=') : docstring::npos;
586 if (idx == docstring::npos)
589 data = trim(data.substr(idx));
592 if (data.length() < 2 || data[0] != '=')
595 // delete '=' and the following spaces
596 data = ltrim(data, " =");
597 if (data.length() < 2) {
598 // not long enough to find delimiters
601 docstring::size_type keypos = 1;
603 if (data[0] == '{') {
605 } else if (data[0] == '"') {
608 // no {} and no "", pure data but with a
609 // possible ',' at the end
610 return rtrim(data, ",");
612 docstring tmp = data.substr(keypos);
613 while (tmp.find('{') != docstring::npos &&
614 tmp.find('}') != docstring::npos &&
615 tmp.find('{') < tmp.find('}') &&
616 tmp.find('{') < tmp.find(enclosing)) {
618 keypos += tmp.find('{') + 1;
619 tmp = data.substr(keypos);
620 keypos += tmp.find('}') + 1;
621 tmp = data.substr(keypos);
623 if (tmp.find(enclosing) == docstring::npos)
626 keypos += tmp.find(enclosing);
627 return data.substr(1, keypos - 1);
637 char const * const citeCommands[] = {
638 "cite", "citet", "citep", "citealt", "citealp", "citeauthor",
639 "citeyear", "citeyearpar" };
641 unsigned int const nCiteCommands =
642 sizeof(citeCommands) / sizeof(char *);
644 CiteStyle const citeStyles[] = {
645 CITE, CITET, CITEP, CITEALT, CITEALP,
646 CITEAUTHOR, CITEYEAR, CITEYEARPAR };
648 unsigned int const nCiteStyles =
649 sizeof(citeStyles) / sizeof(CiteStyle);
651 CiteStyle const citeStylesFull[] = {
652 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
654 unsigned int const nCiteStylesFull =
655 sizeof(citeStylesFull) / sizeof(CiteStyle);
657 CiteStyle const citeStylesUCase[] = {
658 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
660 unsigned int const nCiteStylesUCase =
661 sizeof(citeStylesUCase) / sizeof(CiteStyle);
666 CitationStyle::CitationStyle(string const & command)
667 : style(CITE), full(false), forceUCase(false)
672 string cmd = command;
678 string::size_type const n = cmd.size() - 1;
679 if (cmd != "cite" && cmd[n] == '*') {
681 cmd = cmd.substr(0,n);
684 char const * const * const last = citeCommands + nCiteCommands;
685 char const * const * const ptr = std::find(citeCommands, last, cmd);
688 size_t idx = ptr - citeCommands;
689 style = citeStyles[idx];
694 string const CitationStyle::asLatexStr() const
696 string cite = citeCommands[style];
698 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
699 if (std::find(citeStylesFull, last, style) != last)
704 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
705 if (std::find(citeStylesUCase, last, style) != last)
713 vector<CiteStyle> const getCiteStyles(CiteEngine const engine)
715 unsigned int nStyles = 0;
716 unsigned int start = 0;
723 case ENGINE_NATBIB_AUTHORYEAR:
724 case ENGINE_NATBIB_NUMERICAL:
725 nStyles = nCiteStyles - 1;
729 nStyles = nCiteStyles;
734 typedef vector<CiteStyle> cite_vec;
736 cite_vec styles(nStyles);
737 cite_vec::size_type i = 0;
739 for (; i != styles.size(); ++i, ++j)
740 styles[i] = citeStyles[j];
746 vector<docstring> const
747 getNumericalStrings(string const & key,
748 InfoMap const & map, vector<CiteStyle> const & styles)
751 return vector<docstring>();
753 docstring const author = getAbbreviatedAuthor(map, key);
754 docstring const year = getYear(map, key);
755 if (author.empty() || year.empty())
756 return vector<docstring>();
758 vector<docstring> vec(styles.size());
759 for (vector<docstring>::size_type i = 0; i != vec.size(); ++i) {
765 str = from_ascii("[#ID]");
769 str = author + " [#ID]";
773 str = author + " #ID";
777 str = from_ascii("#ID");
789 str = '(' + year + ')';
800 vector<docstring> const
801 getAuthorYearStrings(string const & key,
802 InfoMap const & map, vector<CiteStyle> const & styles)
805 return vector<docstring>();
807 docstring const author = getAbbreviatedAuthor(map, key);
808 docstring const year = getYear(map, key);
809 if (author.empty() || year.empty())
810 return vector<docstring>();
812 vector<docstring> vec(styles.size());
813 for (vector<docstring>::size_type i = 0; i != vec.size(); ++i) {
818 // jurabib only: Author/Annotator
819 // (i.e. the "before" field, 2nd opt arg)
820 str = author + "/<" + _("before") + '>';
824 str = author + " (" + year + ')';
828 str = '(' + author + ", " + year + ')';
832 str = author + ' ' + year ;
836 str = author + ", " + year ;
848 str = '(' + year + ')';
858 } // namespace biblio
862 vector<FamilyPair> const getFamilyData()
864 vector<FamilyPair> family(5);
868 pr.first = _("No change");
869 pr.second = Font::IGNORE_FAMILY;
872 pr.first = _("Roman");
873 pr.second = Font::ROMAN_FAMILY;
876 pr.first = _("Sans Serif");
877 pr.second = Font::SANS_FAMILY;
880 pr.first = _("Typewriter");
881 pr.second = Font::TYPEWRITER_FAMILY;
884 pr.first = _("Reset");
885 pr.second = Font::INHERIT_FAMILY;
892 vector<SeriesPair> const getSeriesData()
894 vector<SeriesPair> series(4);
898 pr.first = _("No change");
899 pr.second = Font::IGNORE_SERIES;
902 pr.first = _("Medium");
903 pr.second = Font::MEDIUM_SERIES;
906 pr.first = _("Bold");
907 pr.second = Font::BOLD_SERIES;
910 pr.first = _("Reset");
911 pr.second = Font::INHERIT_SERIES;
918 vector<ShapePair> const getShapeData()
920 vector<ShapePair> shape(6);
924 pr.first = _("No change");
925 pr.second = Font::IGNORE_SHAPE;
928 pr.first = _("Upright");
929 pr.second = Font::UP_SHAPE;
932 pr.first = _("Italic");
933 pr.second = Font::ITALIC_SHAPE;
936 pr.first = _("Slanted");
937 pr.second = Font::SLANTED_SHAPE;
940 pr.first = _("Small Caps");
941 pr.second = Font::SMALLCAPS_SHAPE;
944 pr.first = _("Reset");
945 pr.second = Font::INHERIT_SHAPE;
952 vector<SizePair> const getSizeData()
954 vector<SizePair> size(14);
958 pr.first = _("No change");
959 pr.second = Font::IGNORE_SIZE;
962 pr.first = _("Tiny");
963 pr.second = Font::SIZE_TINY;
966 pr.first = _("Smallest");
967 pr.second = Font::SIZE_SCRIPT;
970 pr.first = _("Smaller");
971 pr.second = Font::SIZE_FOOTNOTE;
974 pr.first = _("Small");
975 pr.second = Font::SIZE_SMALL;
978 pr.first = _("Normal");
979 pr.second = Font::SIZE_NORMAL;
982 pr.first = _("Large");
983 pr.second = Font::SIZE_LARGE;
986 pr.first = _("Larger");
987 pr.second = Font::SIZE_LARGER;
990 pr.first = _("Largest");
991 pr.second = Font::SIZE_LARGEST;
994 pr.first = _("Huge");
995 pr.second = Font::SIZE_HUGE;
998 pr.first = _("Huger");
999 pr.second = Font::SIZE_HUGER;
1002 pr.first = _("Increase");
1003 pr.second = Font::INCREASE_SIZE;
1006 pr.first = _("Decrease");
1007 pr.second = Font::DECREASE_SIZE;
1010 pr.first = _("Reset");
1011 pr.second = Font::INHERIT_SIZE;
1018 vector<BarPair> const getBarData()
1020 vector<BarPair> bar(5);
1024 pr.first = _("No change");
1028 pr.first = _("Emph");
1029 pr.second = EMPH_TOGGLE;
1032 pr.first = _("Underbar");
1033 pr.second = UNDERBAR_TOGGLE;
1036 pr.first = _("Noun");
1037 pr.second = NOUN_TOGGLE;
1040 pr.first = _("Reset");
1041 pr.second = INHERIT;
1048 vector<ColorPair> const getColorData()
1050 vector<ColorPair> color(11);
1054 pr.first = _("No change");
1055 pr.second = Color::ignore;
1058 pr.first = _("No color");
1059 pr.second = Color::none;
1062 pr.first = _("Black");
1063 pr.second = Color::black;
1066 pr.first = _("White");
1067 pr.second = Color::white;
1070 pr.first = _("Red");
1071 pr.second = Color::red;
1074 pr.first = _("Green");
1075 pr.second = Color::green;
1078 pr.first = _("Blue");
1079 pr.second = Color::blue;
1082 pr.first = _("Cyan");
1083 pr.second = Color::cyan;
1086 pr.first = _("Magenta");
1087 pr.second = Color::magenta;
1090 pr.first = _("Yellow");
1091 pr.second = Color::yellow;
1094 pr.first = _("Reset");
1095 pr.second = Color::inherit;
1106 : public std::binary_function<LanguagePair,
1110 bool operator()(LanguagePair const & lhs,
1111 LanguagePair const & rhs) const {
1112 return lhs.first < rhs.first;
1120 bool operator()(Color::color const & lhs,
1121 Color::color const & rhs) const {
1122 return lcolor.getGUIName(lhs) < lcolor.getGUIName(rhs);
1129 vector<LanguagePair> const getLanguageData(bool character_dlg)
1131 vector<LanguagePair>::size_type const size = character_dlg ?
1132 languages.size() + 2 : languages.size();
1134 vector<LanguagePair> langs(size);
1136 if (character_dlg) {
1137 langs[0].first = _("No change");
1138 langs[0].second = "ignore";
1139 langs[1].first = _("Reset");
1140 langs[1].second = "reset";
1143 vector<string>::size_type i = character_dlg ? 2 : 0;
1144 for (Languages::const_iterator cit = languages.begin();
1145 cit != languages.end(); ++cit) {
1146 langs[i].first = _(cit->second.display());
1147 langs[i].second = cit->second.lang();
1151 // Don't sort "ignore" and "reset"
1152 vector<LanguagePair>::iterator begin = character_dlg ?
1153 langs.begin() + 2 : langs.begin();
1155 std::sort(begin, langs.end(), Sorter());
1161 vector<Color_color> const getSortedColors(vector<Color_color> colors)
1164 std::sort(colors.begin(), colors.end(), ColorSorter());
1168 } // namespace frontend
1170 using support::addName;
1171 using support::FileFilterList;
1172 using support::getExtension;
1173 using support::libFileSearch;
1174 using support::makeAbsPath;
1175 using support::makeRelPath;
1176 using support::onlyFilename;
1177 using support::onlyPath;
1178 using support::package;
1179 using support::prefixIs;
1180 using support::removeExtension;
1182 namespace frontend {
1185 docstring const browseFile(docstring const & filename,
1186 docstring const & title,
1187 FileFilterList const & filters,
1189 pair<docstring,docstring> const & dir1,
1190 pair<docstring,docstring> const & dir2)
1192 docstring lastPath = from_ascii(".");
1193 if (!filename.empty())
1194 lastPath = from_utf8(onlyPath(to_utf8(filename)));
1196 FileDialog fileDlg(title, LFUN_SELECT_FILE_SYNC, dir1, dir2);
1198 FileDialog::Result result;
1201 result = fileDlg.save(lastPath, filters,
1202 from_utf8(onlyFilename(to_utf8(filename))));
1204 result = fileDlg.open(lastPath, filters,
1205 from_utf8(onlyFilename(to_utf8(filename))));
1207 return result.second;
1211 docstring const browseRelFile(docstring const & filename,
1212 docstring const & refpath,
1213 docstring const & title,
1214 FileFilterList const & filters,
1216 pair<docstring,docstring> const & dir1,
1217 pair<docstring,docstring> const & dir2)
1219 docstring const fname = from_utf8(makeAbsPath(
1220 to_utf8(filename), to_utf8(refpath)).absFilename());
1222 docstring const outname = browseFile(fname, title, filters, save,
1224 docstring const reloutname = makeRelPath(outname, refpath);
1225 if (prefixIs(reloutname, from_ascii("../")))
1233 docstring const browseLibFile(docstring const & dir,
1234 docstring const & name,
1235 docstring const & ext,
1236 docstring const & title,
1237 FileFilterList const & filters)
1240 pair<docstring, docstring> const dir1(_("System files|#S#s"),
1241 from_utf8(addName(package().system_support().absFilename(), to_utf8(dir))));
1243 pair<docstring, docstring> const dir2(_("User files|#U#u"),
1244 from_utf8(addName(package().user_support().absFilename(), to_utf8(dir))));
1246 docstring const result = browseFile(from_utf8(
1247 libFileSearch(to_utf8(dir), to_utf8(name), to_utf8(ext)).absFilename()),
1248 title, filters, false, dir1, dir2);
1250 // remove the extension if it is the default one
1251 docstring noextresult;
1252 if (from_utf8(getExtension(to_utf8(result))) == ext)
1253 noextresult = from_utf8(removeExtension(to_utf8(result)));
1255 noextresult = result;
1257 // remove the directory, if it is the default one
1258 docstring const file = from_utf8(onlyFilename(to_utf8(noextresult)));
1259 if (from_utf8(libFileSearch(to_utf8(dir), to_utf8(file), to_utf8(ext)).absFilename()) == result)
1266 docstring const browseDir(docstring const & pathname,
1267 docstring const & title,
1268 pair<docstring,docstring> const & dir1,
1269 pair<docstring,docstring> const & dir2)
1271 docstring lastPath = from_ascii(".");
1272 if (!pathname.empty())
1273 lastPath = from_utf8(onlyPath(to_utf8(pathname)));
1275 FileDialog fileDlg(title, LFUN_SELECT_FILE_SYNC, dir1, dir2);
1277 FileDialog::Result const result =
1278 fileDlg.opendir(lastPath, from_utf8(onlyFilename(to_utf8(pathname))));
1280 return result.second;
1284 vector<docstring> const getLatexUnits()
1286 vector<docstring> units;
1288 char const * str = stringFromUnit(i);
1289 for (; str != 0; ++i, str = stringFromUnit(i))
1290 units.push_back(from_ascii(str));
1295 } // namespace frontend
1298 using support::bformat;
1299 using support::contains;
1300 using support::FileName;
1301 using support::getExtension;
1302 using support::getFileContents;
1303 using support::getVectorFromString;
1304 using support::libFileSearch;
1305 using support::onlyFilename;
1306 using support::package;
1307 using support::quoteName;
1308 using support::split;
1309 using support::Systemcall;
1310 using support::token;
1312 namespace frontend {
1314 void rescanTexStyles()
1316 // Run rescan in user lyx directory
1317 support::Path p(package().user_support());
1318 FileName const command = libFileSearch("scripts", "TeXFiles.py");
1320 int const status = one.startscript(Systemcall::Wait,
1321 lyx::support::os::python() + ' ' +
1322 quoteName(command.toFilesystemEncoding()));
1326 Alert::error(_("Could not update TeX information"),
1327 bformat(_("The script `%s' failed."), lyx::from_utf8(command.absFilename())));
1333 // Run texhash in user lyx directory
1334 support::Path p(package().user_support());
1336 //path to texhash through system
1338 one.startscript(Systemcall::Wait,"texhash");
1342 void getTexFileList(string const & filename, std::vector<string> & list)
1345 FileName const file = libFileSearch("", filename);
1349 list = getVectorFromString(getFileContents(file), "\n");
1351 // Normalise paths like /foo//bar ==> /foo/bar
1352 boost::RegEx regex("/{2,}");
1353 std::vector<string>::iterator it = list.begin();
1354 std::vector<string>::iterator end = list.end();
1355 for (; it != end; ++it) {
1356 *it = regex.Merge((*it), "/");
1359 // remove empty items and duplicates
1360 list.erase(std::remove(list.begin(), list.end(), ""), list.end());
1361 eliminate_duplicates(list);
1365 string const getListOfOptions(string const & classname, string const & type)
1367 FileName const filename(getTexFileFromList(classname, type));
1368 if (filename.empty())
1370 string optionList = string();
1371 std::ifstream is(filename.toFilesystemEncoding().c_str());
1375 if (contains(s,"DeclareOption")) {
1376 s = s.substr(s.find("DeclareOption"));
1377 s = split(s,'{'); // cut front
1378 s = token(s,'}',0); // cut end
1379 optionList += (s + '\n');
1386 string const getTexFileFromList(string const & file,
1387 string const & type)
1389 string file_ = file;
1390 // do we need to add the suffix?
1391 if (!(getExtension(file) == type))
1392 file_ += '.' + type;
1394 lyxerr << "Searching for file " << file_ << endl;
1398 lstfile = "clsFiles.lst";
1399 else if (type == "sty")
1400 lstfile = "styFiles.lst";
1401 else if (type == "bst")
1402 lstfile = "bstFiles.lst";
1403 else if (type == "bib")
1404 lstfile = "bibFiles.lst";
1405 FileName const abslstfile = libFileSearch(string(), lstfile);
1406 if (abslstfile.empty()) {
1407 lyxerr << "File `'" << lstfile << "' not found." << endl;
1410 string const allClasses = getFileContents(abslstfile);
1412 string classfile = token(allClasses, '\n', entries);
1414 while ((!contains(classfile, file) ||
1415 (onlyFilename(classfile) != file)) &&
1417 classfile = token(allClasses, '\n', ++entries);
1420 // now we have filename with full path
1421 lyxerr << "with full path: " << classfile << endl;
1426 } // namespace frontend