/*This file is read into a Tw global at startup */
// original phpjs.namespaced.mod from http://phpjs.org/ * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses.
var window = {}; // fix for not being in a browser environment
eval(TW.app.getGlobal("phpjs_namespaced"));
var PhpJs = new PHP_JS();
var $P = PhpJs;
// TW.information(null, 'test', 'Setting up');
const twConst = {
SystemAccess_NotAttempted : -1,
SystemAccess_OK : 0,
SystemAccess_Failed : 1,
SystemAccess_PermissionDenied : 2
}; // end twConst
/* from http://doc.trolltech.com/4.7/qmessagebox.html#StandardButton-enum and discussions on thread http://tug.org/mailman/htdig/texworks/2010q2/002662.html */
const msgBox = {
Ok : 0x00000400, // An "OK" button defined with the AcceptRole.
Open : 0x00002000, // A "Open" button defined with the AcceptRole.
Save : 0x00000800, // A "Save" button defined with the AcceptRole.
Cancel : 0x00400000, // A "Cancel" button defined with the RejectRole.
Close : 0x00200000, // A "Close" button defined with the RejectRole.
Discard : 0x00800000, // A "Discard" or "Don't Save" button, depending on the platform, defined with the DestructiveRole.
Apply : 0x02000000, // An "Apply" button defined with the ApplyRole.
Reset : 0x04000000, // A "Reset" button defined with the ResetRole.
RestoreDefaults : 0x08000000, // A "Restore Defaults" button defined with the ResetRole.
Help : 0x01000000, // A "Help" button defined with the HelpRole.
SaveAll : 0x00001000, // A "Save All" button defined with the AcceptRole.
Yes : 0x00004000, // A "Yes" button defined with the YesRole.
YesToAll : 0x00008000, // A "Yes to All" button defined with the YesRole.
No : 0x00010000, // A "No" button defined with the NoRole.
NoToAll : 0x00020000, // A "No to All" button defined with the NoRole.
Abort : 0x00040000, // An "Abort" button defined with the RejectRole.
Retry : 0x00080000, // A "Retry" button defined with the AcceptRole.
Ignore : 0x00100000, // An "Ignore" button defined with the AcceptRole.
NoButton : 0x00000000 // An invalid button.
};
/* A function tag window entry of this form
//%: ##file_get_contents## : string;
Will use the function in Alt+R, Alt+F - 'Run twPan Stand Alone Functions'
under moduleAndObjects menu
*/
var twPan = {
//%: callingScriptPath() : string ; // Path = dirctory with trailing / of calling script
callingScriptPath : function (scriptFile) // pass __FILE__ in here
{
return scriptFile.substr(0,scriptFile.lastIndexOf("/") +1);
},
//%: Biblio - citationType : array of string ; // Layout of citation format - keep in sync with: insertCite
citationType : ["[1. page 2-3]", "Goossens et al. (1993)","(Goossens et al., 1993)","Goossens, Mittlebach, and Samarin (1993)","(Goossens, Mittlebach, and Samarin, 1993)", "Jones et al.","Jones, Baker, and Williams","1990","(1990)"],
//%: Biblio - insertCite : array of string ; // Command for citation format - keep in sync with: citationType
insertCite : [ "cite", "citet", "citep", "citet*", "citep*", "citeauthor", "citeauthor*", "citeyear", "citeyearpar"],
//%: Biblio - citationOrder : array of string ; // for MySql query dropbox - keep in sync with citeOrderBy
citationOrder : ["By Citation Key", "By Title", "By Author - (on first Name)", "Year", "Journal", "Editor"],
//%: Biblio - citeOrderBy : array of string ; // for MySql query extract dropbox - keep in sync with citationOrder
citeOrderBy : ["cite_key", "title", "author", "year", "journal", "editor"],
//%: bibleNamesAbrvs : array of string ; // Names and Abbreviations of current Bibles
bibleNamesAbrvs : function()
{
var bibleList = this.osCmd('cmd /c getBibleNamesAbrs.php.bat', true);
return bibleList.split('\n');
},
/* See panMagUseAa.sty
%: Count Verses - now loaded directly in .sty
\global\def\versionList{NIV,WEB,NET,ISV,AMP,RSV,KJV,NKJV,UNSP}%
And
%: \showBibleVerseCount
*/
os : "", // prefer to do these in initialise()
//%: initialise : void;
initialise : function() {
this.os = TW.platform() ;
// this.alert("Tw loaded");
}, // End. pan_Tw.initialise();
//%: Web Like Equivalents
//%: select(message, optionsArray) : string
select : function(message, optionsArray){
chosen = TW.getItem(null, message, message, optionsArray, 0, true); // true - editable
if (chosen === null)
{return "";}
return chosen;
}, // End. twPan.select()
//%: chooseFromDirectoryListing(Description, pathDir, fileExtension) : string
chooseFromDirectoryListing : function(Description, pathDir, fileExtension)
{
// pathDir (no trailing slash), fileExtension with . E.g. .txt
/* TW.app.clipboard = "cmd /c dir /b \""
+ pathDir + "\\*" + fileExtension + "\"";
*/
var fileList = this.osCmd("cmd /c dir /b \""
+ pathDir + "\\*" + fileExtension + "\""
, true)
removeExtnsn = new RegExp(fileExtension,"ig");
fileList = fileList.replace(removeExtnsn,"").split(this.LineBreakIs(fileList));
var chosenAnswer =
this.select(Description, fileList);
if (this.emptyString(chosenAnswer) == false)
{
chosenAnswer = chosenAnswer + fileExtension;
}
return chosenAnswer;
}, // End. twPan.chooseFromDirectoryListing
//%: prompt(message) : string
prompt : function(message){
response = TW.getText(null, message, message);
if( response == null)
{response = -1};
return response;
}, // End. pan_Tw.input(message)
//%: confirm(message) : boolean
confirm : function(message){
response = TW.question(null, message, message, msgBox.Yes | msgBox.No, msgBox.Yes);
if (response == msgBox.Yes)
{return true;}
else
{return false;}
}, // End. pan_Tw.confirm(message)
//%: alert(text) : void;
alert : function(text){
TW.information(null, "TeXworks Message", text);
}, // End. pan_Tw.alert();
//%: ##file_get_contents## : string;
file_get_contents : function(){
if (this.file_get_contents.arguments.length == 0)
{
fileNameFullPath = TW.app.getOpenFileName();
}
else
{
fileNameFullPath = this.file_get_contents.arguments[0];
}
var res = TW.readFile(fileNameFullPath);
switch (res.status)
{
case twConst.SystemAccess_PermissionDenied:
case twConst.SystemAccess_Failed:
this.alert(res.message);
var text = undefined;
break;
case twConst.SystemAccess_OK:
var text = res.result;
break;
}
return text;
}, // End. twPan.file_get_contents
//%: file_put_contents : void;
file_put_contents : function(fileNameFullPath , fileContents){
var status = TW.writeFile(fileNameFullPath, fileContents); // pathFileName, Contents (- utf-8)
switch (status)
{
case twConst.SystemAccess_PermissionDenied:
case twConst.SystemAccess_Failed:
this.alert('Please Turn on File Writing in \n\ Edit Menu / Preferences / Scripts');
break;
} // End. switch (status)
}, // End. twPan.file_put_contents
//%: getRelativePath(mainPath, wantedPath)
getRelativePath : function(mainPath, wantedPath){
// require - assume full file paths including filenames
var mainPathLessFile = mainPath.substr(0, mainPath.lastIndexOf('/')+1);
var wantedPathLessFile = wantedPath.substr(0, wantedPath.lastIndexOf('/')+1);
var mainPathJustFile = mainPath.substr(mainPath.lastIndexOf('/')+1);
var wantedPathJustFile = wantedPath.substr(wantedPath.lastIndexOf('/')+1);
if (wantedPathLessFile == mainPathLessFile) // TeX file and graphic in same directory
{return wantedPathJustFile;}
if (wantedPathLessFile.indexOf(mainPathLessFile) > -1) // graphic (2nd) file in lower directory
{return wantedPathLessFile.replace(mainPathLessFile, '')+wantedPathJustFile;}
if (mainPathLessFile.indexOf(wantedPathLessFile) > -1) // graphic (2nd) file in higher directory
{
remainderPath = mainPathLessFile.replace(wantedPathLessFile, '')
var buildSlash = '';
for (chr in remainderPath)
{
if (remainderPath[chr] == '/')
{buildSlash += '../'; }
}
return buildSlash + wantedPathJustFile;
}
else // higher then lower
{
mainPathLessFileArray = mainPathLessFile.split('/');
wantedPathLessFileArray = wantedPathLessFile.split('/');
if (mainPathLessFileArray[0] != wantedPathLessFileArray[0]) // different file tree(?)
{ return wantedPath; // full path of graphic (2nd) file
}
for (var count = 0; count < mainPathLessFileArray.length; count++ )
{
if (mainPathLessFileArray[count] != wantedPathLessFileArray[count])
{
break;
}
}
neededSlashes = mainPathLessFileArray.length - (count + 1);
var buildSlash = '';
for (J = 0; J < neededSlashes; J++)
{
buildSlash += '../';
}
var buildPath ='';
for (K = count; K < (wantedPathLessFileArray.length -1); K++)
// -1 remove trailing slash
{
buildPath += wantedPathLessFileArray[K] + '/';
}
return buildSlash + buildPath + wantedPathJustFile;
}
}, // End. twPan.getRelativePath(mainPath, wantedPath)
//%: finalise : void;
finalise : function(){
// nothing to finalise at the moment
},// End. twPan.finalise
//%: Bible Related
//%: getBibleVersion : object : (abbrv : string | full : string) ; if a string is passed it is a specific for the occasion from User
getBibleVersion : function(){
if (this.getBibleVersion.arguments.length > 0) // User has supplied text
{
var userText = this.getBibleVersion.arguments[0]; // get User's default text
choiceIndex = 0;} // use User's text at top
else
{ // User supplied no text, use standard list with gap at top for User to write in
var userText = '';
choiceIndex = 3; // NET, most frequently used at present
}
// this.bibleNamesAbrvs at top of twPan
var bibleList = this.bibleNamesAbrvs();
var getNamesAbrvs = [userText].concat(bibleList);
userChoice = TW.getItem( null, "Bible Version ?", "Bible Version : ",
getNamesAbrvs , choiceIndex , true ) ;
var result = [];
if( userChoice == undefined)
{
result.abbrv= '';
result.full= '';
}
else
{
var abrvStart = userChoice.lastIndexOf(' ');
result.abbrv = userChoice.substr(abrvStart + 1);
result.full = userChoice.substr(0, abrvStart );
}
return result;
},// End. twPan.getBibleVersion
//%: getBibleVersionName : string // no abrev at end as getBibleVersionFull does
//##getBibleVersionName## - available for use in runtwPanStandaloneFunctions.js
getBibleVersionName : function(){
return this.getBibleVersion().full;
}, // End. getBibleVersionName()
//%: getBibleVersionAbrv : string // no Name at start as getBibleVersionFull does
//##getBibleVersionAbrv## - available for use in runtwPanStandaloneFunctions.js
getBibleVersionAbrv : function(){
return this.getBibleVersion().abbrv;
}, // End. getBibleVersionName()
//%: ##getBibleVersionFull## : object : (abbrv : string | full : string) ; if a string is passed it is a specific for the occasion from User
getBibleVersionFull : function(){
if (this.getBibleVersionFull.arguments.length > 0) // User has supplied text
{
var userText = this.getBibleVersionFull.arguments[0]; // get User's default text
choiceIndex = 0;} // use User's text at top
else
{ // User supplied no text, use standard list with gap at top for User to write in
var userText = '';
choiceIndex = 3; // NET, most frequently used at present
}
// this.bibleNamesAbrvs at top of twPan
var bibleList = this.bibleNamesAbrvs();
var getNamesAbrvs = [userText].concat(bibleList);
userChoice = TW.getItem( null, "Bible Version ?", "Bible Version : ",
getNamesAbrvs , choiceIndex , true ) ;
return userChoice;
}, // End. twPan.getBibleVersionFull
//%: Date Related
//%: ##getSuffixDateTh## : string : (dateNumerals) : string ;
getSuffixDateTh : function(dateNumerals){
var suffices = ['st','nd','rd'];
if (dateNumerals.length > 1)
{
lastDigit = dateNumerals.substr(1);
}
else
{
lastDigit = dateNumerals.substr(0);
}
if (lastDigit < 1 || lastDigit > 3 || (dateNumerals > 9 & dateNumerals < 21))
{
return 'th';
}
else
{
return suffices[lastDigit -1];
}
}, // End. twPan.getSuffixDateTh(dateNumerals)
//%: ##insertSuperscriptDateTh## : string : (dateNumerals) : string ;
insertSuperscriptDateTh : function(dateNumerals){
return dateNumerals
+ "\\superscript{"
+ this.getSuffixDateTh(dateNumerals)
+"}";
}, // End. twPan.insertSuperscriptDateTh(dateNumerals)
//%: ##getDateWords## : () ; // can accept an argument for date format 'dmy' or 'ydm' or 'ymd', if not present dropdown box is shown.
getDateWords : function(){
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'Novemeber', 'December'];
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
// Altered from: http://www.tizag.com/javascriptT/javascriptdate.php
var currentTime = new Date();
var month = months[currentTime.getMonth()];
var day = days[currentTime.getDay()];
var dayNum = currentTime.getDate() + '';
var year = currentTime.getFullYear();
dayNumTh = dayNum + this.getSuffixDateTh(dayNum);
if (this.getDateWords.arguments.length > 0)
{
wantedFormat = this.getDateWords.arguments[0].toLowerCase();
switch (wantedFormat)
{
case 'dmy': // could just use default below HERE FOR COMPLETENESS
result = day + ' ' + dayNumTh + ', ' + month + ', ' + year;
break;
case 'ydm':
result = year + ', ' + day + ' ' + dayNumTh +', ' + month;
break;
case 'ymd':
result = year + ', ' + month + ', ' + day + ' ' + dayNumTh ;
break;
default:
result = day + ' ' + dayNumTh + ', ' + month + ', ' + year;
}
}
else
{
var result = this.select('Select Format',
[ day + ' ' + dayNumTh + ', ' + month + ', ' + year,
year + ', ' + day + ' ' + dayNumTh + ', ' + month,
year + ', ' + month + ', ' + day + ' ' + dayNumTh
]);
}
return result;
}, // End twPan.getDateWords
//%: ##getDate## : () ; // can accept an argument for date format 'dmy' or 'ydm' or 'ymd', if not present dropdown box is shown.
getDate : function(){
// Altered from: http://www.tizag.com/javascriptT/javascriptdate.php
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate() + ''; // force cast for length test
var year = currentTime.getFullYear();
var hour = currentTime.getHours()+ '';
var minute = currentTime.getMinutes()+ '';
var second = currentTime.getSeconds()+ '';
if (day.length < 2){day = "0" + day;}
month = month + ''; // force cast for length test
if (month.length < 2){month = "0" + month;}
if (hour.length < 2){hour = "0" + hour;}
if (minute.length < 2){minute = "0" + minute;}
if (second.length < 2){second = "0" + second;}
if (this.getDate.arguments.length > 0)
{
wantedFormat = this.getDate.arguments[0].toLowerCase();
switch (wantedFormat)
{
case 'dmy': // could just use default below HERE FOR COMPLETENESS
result = day + '-' + month + '-' + year;
break;
case 'ydm':
result = year + '-' + day + '-' + month;
break;
case 'ymd':
result = year + '-' + month + '-' + day;
break;
case 'ymdhms':
result = year + '-' + month + '-' + day
+ '--' + hour + '-' + minute + "-" + second;
break;
default:
result = day + '-' + month + '-' + year;
}
}
else
{
var result = this.select('Select Format',
[ day + '-' + month + '-' + year,
year + '-' + day + '-' + month,
year + '-' + month + '-' + day
]);
}
return result;
}, // End twPan.getDate
//%: String Handling
//%: trim ltrim rtrim
// http://www.somacon.com/p355.php Created 2006-10-19, Last Modified 2007-06-07, © Shailesh N. Humbad Disclaimer: This content is provided as-is. The information may be incorrect.
trim : function(stringToTrim)
{
if(stringToTrim === false)
{return stringToTrim;}
return stringToTrim.replace(/^\s+|\s+$/g,"");
},
ltrim : function(stringToTrim)
{
f(stringToTrim === false)
{return stringToTrim;}
return stringToTrim.replace(/^\s+/,"");
},
rtrim : function(stringToTrim)
{
if(stringToTrim === false)
{return stringToTrim;}
return stringToTrim.replace(/\s+$/,"");
},
//%: ##convertSpeechMarks##(text) : string ; // gets around most fun and games when pasting in form other applications
convertSpeechMarks : function(text){
aposSingle = new RegExp("\u2018"|"\u2019","g");
textChanged = text.replace(aposSingle,"'");
//aposSingle = new RegExp("\u2019","g");
// textChanged = textChanged.replace(aposSingle,"'");
textChanged = textChanged.replace(/\s\'/g,"`");
textChanged = textChanged.replace(/\n\'/g,"\n`");
textChanged = textChanged.replace(/?/g,"`");
textChanged = textChanged.replace(/?/g,"'");
textChanged = textChanged.replace(/’/g,"'");
textChanged = textChanged.replace(/\s\?/g," ``");
textChanged = textChanged.replace(/\n\?/g,"\n``");
textChanged = textChanged.replace(/\s\"/g," ``");
textChanged = textChanged.replace(/^\"/g," ``");
textChanged = textChanged.replace(/^\‘/g," `");
textChanged = textChanged.replace(/\n\"/g,"\n``");
textChanged = textChanged.replace(/\n\“/g,"\n``");
textChanged = textChanged.replace(/?/g,"\'");
textChanged = textChanged.replace(/?/g,"\'\'");
textChanged = textChanged.replace(/\‘$/g,"\'")
textChanged = textChanged.replace(/\"$/g,"\'\'")
textChanged = textChanged.replace(/\“$/g,"\'\'")
textChanged = textChanged.replace(/?/g,"\'\'");
openDouble = new RegExp("\u201C","g");
closeDouble = new RegExp("\u201D","g");
textChanged = textChanged.replace(closeDouble,"\'\'");
textChanged = textChanged.replace(openDouble,"``");
return textChanged;
}, // End. twPan.convertSpeechMarks(text)
//%: LineBreakIs(text) : string ;
LineBreakIs : function(text){
// http://www.codeguru.com/forum/showthread.php?t=253826
if (text.indexOf("\r\n") > -1)
{
var sep = "\r\n"; // Windows
}
else if (text.indexOf("\n") > -1)
{
var sep = "\n"; // *nix, Mac OSX
}
else
{
var sep = "\r"; // classical Mac
}
return sep;
}, // End. twPan.LineBreakIs
//%: lineNumber : integer ;
lineNumber : function(){
var lineSeperator = this.LineBreakIs(TW.target.text);
var lines = TW.target.text.split(this.LineBreakIs(TW.target.text));
var charCount = 0;
var weAreHere = TW.target.selectionStart;
for (line in lines)
{
charCount += (lines[line].length *1)
+ lineSeperator.length; // for loss of separator on .split
if (weAreHere < charCount)
{
return (line * 1) +1; // array zero offset in lines[]
}
}
}, // End. twPan.lineNumber
//%: ##cleanParaMarks##(text) : string ;
cleanParaMarks : function(text){
txt = text.replace(/\\P/g, '\\textcolor{bibleParaMark}{\\P} \\ ');
txt = txt.replace(/?/g, '\\textcolor{bibleParaMark}{\\P} \\ ');
txt = txt.replace(/¶/g, '\\textcolor{bibleParaMark}{\\P} \\ ');
return txt;
}, // End. twPan.cleanParaMarks(text)
//%: osCmd(commandText [, waitResponse]) : string | void ;
osCmd : function(){
var waitResponse = false;
// this.alert(this.osCmd.arguments.length);
switch(this.osCmd.arguments.length)
{
case 0:
var retVal = {'status': twConst.SystemAccess_NotAttempted};
break;
case 1:
var retVal = TW.system(this.osCmd.arguments[0]);
break;
case 2:
waitResponse = this.osCmd.arguments[1];
var retVal = TW.system(this.osCmd.arguments[0], waitResponse);
break;
} // End. switch(this.osCmd.arguments.length)
switch(retVal.status)
{
case twConst.SystemAccess_NotAttempted:
this.alert('Please Specify a Command\n - that the System can Run');
break;
case twConst.SystemAccess_OK:
if (waitResponse == true) {return retVal.output; }
// otherwise no return should be expected
break;
case twConst.SystemAccess_Failed:
this.alert(retVal.message
+ '\nCode: '+ retVal.result // may be empty
+ '\n\n' + retVal.output); // may be empty
// even if (waitResponse == true) {return nothing ; } and fail script
break;
case twConst.SystemAccess_PermissionDenied:
this.alert(retVal.message);
return '';
break;
} // End. switch(retVal.status)
}, // End. twPan.osCmd(commandText [, waitResponse])
//%: findFromScript([string]) : void
findFromScript : function ()
{ with (TW.target)
{
var saveSelStart = selectionStart ;
var saveSelectionLength = selectionLength ;
if (this.findFromScript.arguments.length > 0 && this.findFromScript.arguments[0] != "")
{
useThis = this.findFromScript.arguments[0];
}
else
{
useThis = "Find Text"
}
selectRange(saveSelStart,0); // avoid overwriting existing text if selected
insertText(useThis);
selectRange(saveSelStart,useThis.length);
copyToFind();
insertText("");
selectRange(saveSelStart,saveSelectionLength);
doFindDialog();
}
}, // End. twPan.findFromScript([string]) : void
//%: ##escapeLatex##([string]) : string
escapeLatex : function(LateXtext)
{
LateXtext = LateXtext + " ";
if ( LateXtext == ""
|| LateXtext == " "
|| LateXtext == 'undefined'
|| LateXtext == undefined
|| LateXtext == null
|| LateXtext == "null"
|| LateXtext == "NULL"
)
{ return '' ; }
LateXtext = LateXtext.replace(/\n/g,"zxDcKvb") ;
escapeList = [ "\\\\", "#", "\\$", "%", "&", "~", "_", "\\^", "{", "}"];
for (escapee in escapeList)
{
buildReg = new RegExp( escapeList[escapee],"g");
LateXtext = LateXtext.replace(buildReg, "\\" + escapeList[escapee]);
}
return LateXtext.replace(/zxDcKvb/g,"\n");
}, // End. escapeLatex : function(LateXtext)
//%: ##pasteToLatex##([string]) : string
pasteToLatex : function(text)
{
text = this.escapeLatex(text);
text = this.convertSpeechMarks(text);
return text;
}, // End. pasteToLatex(text)
//%: ##latexFileName##([string]) : string
latexFileName : function(startName)
{
escapeList = ["’", "`", "\"", "'", "#", "\\$", "%", "&", "~", "_", "\\^", "{", "}", " "];
for (escapee in escapeList)
{
buildReg = new RegExp( escapeList[escapee],"g");
startName = startName.replace(buildReg, "-" );
}
return startName;
}, // End. latexFileName : function(startName)
//%: getSnippet(query : string) : { dataRecords_ArrayOfObjectsof_fieldName_And_fieldValue : array, commandUsed : string } : object
getSnippet : function (database, table, chosen_id, chosenColumn)
{
/*
For batch file and php argv[1] ...
%1 DataBase - information_snippets
%2 Table - entries
%3 Id - chosen_titleId
%4 Column - chosenColumn
*/
var command = 'cmd /c getMySqldData.php.bat '
+ database + ', '
+ table +', '
+ chosen_id + ' \"'
+ chosenColumn +'\"';
objectString = this.osCmd(command, true);
if (objectString.indexOf("Qhole query") > -1)
{ this.alert(objectString); }
else{
return {
'dataRecords_ArrayOfObjectsof_fieldName_And_fieldValue': JSON.parse(objectString),
'commandUsed':command
};
}
},// End. getSnippet : function (database, table, chosen_id, chosenColumn)
//%: toTitleCase (text : string) : string
toTitleCase :function(text)
{
return text.replace(/(\\?[\w&`'??"?.@:\/\{\(\[<>_]+-? *)/g, function(match, p1, index, title) {
if (index > 0 && title.charAt(index - 2) !== ":" &&
match.search(/^(a(nd?|s|t)?|b(ut|y)|en|for|is|i[fn]|o[fnr]|t(he|o)|vs?\.?|via)[ \-]/i) > -1) // added is Paul Norman
return match.toLowerCase();
if (title.substring(index - 1, index + 1).search(/['"_{(\[]/) > -1)
return match.charAt(0) + match.charAt(1).toUpperCase() + match.substr(2);
if (match.substr(1).search(/[A-Z]+|&|[\w]+[._][\w]+/) > -1 ||
title.substring(index - 1, index + 1).search(/[\])}]/) > -1)
return match;
return match.charAt(0).toUpperCase() + match.substr(1);
});
}, // End. twPan.toTitleCase (text : string) : string
//%: getArrayIndexKeyFromValue(myArray ,arrayValue) : integer;
getArrayIndexKeyFromValue : function (myArray, arrayValue)
{
for (look in myArray)
{
if (myArray[look] == arrayValue)
{
return look;
}
}
return -1; // not found
}, // End. getArrayIndexKeyFromValue(myArray ,arrayValue) : integer;
//%: cleanLineEnd(lineText) : string; // removes any start end spaces and any trailing new line
cleanLineEnd : function(lineText)
{
var text = twPan.trim(lineText);
do{
if (text.lastIndexOf("\n") == text.length -1)
{
text = text.substr(0, text.length -2);
}
}
while(text.lastIndexOf("\n") == text.length -1);
return text;
}, // End. cleanLineEnd(lineText) : string;
//%: emptyString( something : empty string?) : boolean
// after http://stackoverflow.com/questions/154059/what-is-the-best-way-to-check-for-an-empty-string-in-javascript/3215653#3215653 by Jet
emptyString : function (e)
{
switch(e) {
case "":
case 0:
case "0":
case null:
case false:
case undefined:
return true;
break;
default : return false;
}
} // End. emptyString( something : empty string?) : boolean
}; // end twPan
twPan.initialise();
$tw = twPan; //shorhand
// TW.information(null, 'test', ' function global_load');
function global_load(globalName)
{
if (TW.app.hasGlobal(globalName) === true)
{ return TW.app.getGlobal(globalName);
}
else
{ twPan.alert('Global '+globalName+' not Available');
return undefined;
}
}
// TW.information(null, 'test', ' function create_helper');
function create_helper(globalName) //
{
eval(global_load(globalName));
}
// Do following when needed in individual script, it is possible to overflow the stack
// This form can be called even if twPan is not created
// eval(TW.app.getGlobal("helper_PhpJs"));
//
/*
// Was
file_get_contents : function(fileNameFullPath){
var scriptRoot = this.callingScript.scriptNamePath.substr(0,
this.callingScript.scriptNamePath.lastIndexOf("/")) ;
scriptRoot = scriptRoot.substr(0,scriptRoot.lastIndexOf("/") +1) ;
var loadFile = "\"" + scriptRoot + 'mod_loadFile.php\" \"'
+ fileNameFullPath + '\"'; // \" to quote spaces in files' paths
// Non-windows OSes won't need the cmd /c
var text = TW.app.system('cmd /c php ' + loadFile);
return text;
}
*/
// Following alters the QtScript generic String object to add .toTitleCase()
//%: String.toTitleCase()
/* To Title Case 1.1.1
* David Gouch <http://individed.com>
* 23 May 2008
*
* Copyright (c) 2008 David Gouch
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/* MODIFIED by Jonathan Kew for use with TeXworks: added optional leading
backslash to the word-finding regex, to protect TeX control words */
//%: Array.contains(element)
//from http://www.go4expert.com/forums/showthread.php?t=606>Extending JavaScript Arrays
// http://www.go4expert.com/forums/member.php?u=146 Pradeep
/* some sort of iteration problem for (x in array) over runs
Array.prototype.contains = function (element)
{
for (var i = 0; i < this.length; i++)
{
if (this[i] == element)
{
return true;
}
}
return false;
};
*/
//%: Array.lastIndexOf(element)
/* Altered from http://www.go4expert.com/forums/showthread.php?t=974
http://www.go4expert.com/forums/member.php?u=146 Pradeep
' Returns the index of the element matched from the end'
*/
/* some sort of iteration problem for (x in array) over runs
Array.prototype.lastIndexOf=function(element)
{
var i=this.length;
while(i--)
{
if(this[i]===element)
{
return i;
}
}
return -1;
}
*/
var buildText = "";
var here = this;
function doDocumentation()
{
/*
if ( TW.question(null, "Get text of Object/Function List?", "Get text of Object /Function List?\nor function list (.js)?" , msgBox.Yes | msgBox.No, msgBox.Yes) == msgBox.Yes)
{ var scriptContents = TW.readFile(TW.app.getOpenFileName()).result;
}
else
{
return;
}
*/
var appName = TW.getText(null, "Application Name", "Application Name");
if (appName == undefined)
{
return
}
var appNameDescription = TW.getText(null, "Application Description", "Application Description");
if (appNameDescription == undefined)
{
return;
}
var objFuncName = TW.getText(null, "Object/Function Name", "Object/Function Name", "this");
if (objFuncName !== undefined)
{
if (objFuncName == "Process Function Names")
{
var functionList = scriptContents.match(/\s(function)(?=\s*.*\()\s+[a-zA-Z_\-]*\(/g);
if ( functionList !== false)
{
for (var x in functionList)
{
functionName = ">" + functionList[x].replace(/function|\s+|\(/g,"")+"<";
if (functionName != "><")
{
// TW.information(null,"", functionName);
}
}
// TW.information(null, "results", functionList.toString().replace(/,/g,"\n"));
eval(scriptContents); // scriptFile
docDone = selfDoc(appName, this, appNameDescription);
makeInformation(docDone);
}
return;
}
else
{
docDone = selfDoc(appName, here, appNameDescription);
makeInformation(docDone);
}
}
else
{
return;
}
TW.target.insertText(buildText);
}
function makeInformation(docDone)
{
// TW.information(null, "result", docDone.properties.length);
/*
docDone.properties[p].name
docDone.properties[p].comment
docDone.properties[p].implementation
*/
for (var p in docDone.properties)
{
if (docDone.properties[p].type != "function" || docDone.properties[p].implementation.indexOf("[native code]")>-1) // avoid Tw and Qt globals
{
continue;
}
// twPan.alert( docDone.properties[p].name
// + "\n " + docDone.properties[p].type
// + "\n " + docDone.properties[p].comment
// + "\n " + docDone.properties[p].implementation
// );
buildText += "\\subsection{" + twPan.escapeLatex(docDone.properties[p].name) + "}\n\n";
buildText += "\\noindent " + twPan.escapeLatex(docDone.properties[p].comment) + "\n\n";
buildText += "\\begin{lstlisting}["
+ "caption=" + twPan.escapeLatex(docDone.properties[p].name) + ","
+ "label=script." + twPan.escapeLatex(docDone.properties[p].name) + ","
+ "fontadjust]\n\n";
buildText += docDone.properties[p].implementation + "\n\n";
buildText += "\\end{lstlisting}\\\n\n"
// TW.app.clipboard = buildText;
}
}
// from - https://github.com/rudenoise/selfDoc.js
var selfDoc = (function (maxDepth) {
maxDepth = maxDepth || 10;
var doc, extract, loopProps, matchComment, replaceComment, splitLine, clean;
doc = function (appName, root, overview) {
// Accepts appName/string, root/function/object, overview
// Returns an objects containing all nested properties, with documentation
if (typeof appName === "string" &&
(typeof root === "function" || typeof root === "object")) {
return {
appName: appName,
overview: overview,
comment: doc.parse(root),
properties: loopProps(root)
};
}
return false;
};
doc.parse = function (fun) {
// doc.parse accepts fun/function/string as its argument
// returns an array of strings
// strings are extracted from uninterupted comment blocks at the top of the function (as illustrated here)
fun = typeof fun === "string" ? fun : (fun + "");
// pass in all but first line
fun = fun.split(splitLine).slice(1);
return extract(fun, [], true);
};
// PRIVATE
matchComment = new RegExp("^ *\/\/.*$|^ *\/\\*.*$|^ *\\* .*$");
replaceComment = new RegExp("^ *\/\/ |^ *\\* |^ *\/\\* |^ *\/\\*\\*");
splitLine = new RegExp("\r\n|\n");
clean = new RegExp("\n *//.*|\r\n *//.*", "g");
loopProps = function (prop, depth) {
depth = depth || 1;
var k, arr = [];
for (k in prop) {
if (prop.hasOwnProperty(k)) {
arr.push({
name: k,
type: typeof prop[k],
implementation: (prop[k] + "").replace(clean, ""),
comment: doc.parse(prop[k]),
properties: depth > maxDepth ?
["..."] : loopProps(prop[k], (depth + 1))
});
}
}
return arr;
};
extract = function (lines, comments, uninterupted) {
return lines.length === 0 || uninterupted === false ?
comments :
lines.slice(0, 1)[0].match(matchComment) === null ?
// no match, recurse
extract(lines.slice(1), comments, false) :
// match, collect and recurse
extract(lines.slice(1), comments.
concat(lines.slice(0, 1)[0].
replace(replaceComment, "")), true);
};
return doc;
}());
// TW.information(null, 'test', 'All Set up');
Created with the Personal Edition of HelpNDoc: Create HTML Help, DOC, PDF and print manuals from 1 single source