Re: Script TeXworks per creazione e formattazione di tabelle

#59669
Up
0
Down
::


Ecco quanto mi restituisce il debugger quando lancio il table wizard

`Welcome to the Qt Script debugger.
Debugger commands start with a . (period).
Any other input will be evaluated by the script interpreter.
Type “.help” for help.

Uncaught exception at /home/jack/.TeXworks/scripts/tableWizard.js:72: TypeError: Result of expression 'dialog' [null] is not an object.
72 if (dialog.exec() != 1) {

qsdb> .backtrace
#0 () at /home/jack/.TeXworks/scripts/tableWizard.js:72
#1 () at /home/jack/.TeXworks/scripts/tableWizard.js:174
qsdb> .info locals
i : undefined
chkInsertPadding : undefined
chkAddTerminalEmptyCells : undefined
dialog : null
editors : undefined
cells : undefined
environment : null
rows : 0
addTerminalEmptyCells : false
EnvironmentChanged : undefined
j : undefined
chkEncloseInEnvironment : undefined
items : undefined
spinBoxNumberOfCols : null
ColumnWidthLimitChanged : undefined
chkLimitColumnWidth : undefined
spinBoxNumberOfRows : null
filename : undefined
cols : 0
maxColumnWidth : 15
cmbEnvironment : undefined
spinBoxColumnWidthLimit : undefined
xml : undefined
insertPadding : true
qsdb> .up
#1
() at /home/jack/.TeXworks/scripts/tableWizard.js:174
qsdb> .info locals
Math : [object Math]
NaN : NaN
undefined : undefined
Infinity : Infinity
JSON : [object JSON]
Object : function Object() {
[native code]
}
Function : function Function() {
[native code]
}
Array : function Array() {
[native code]
}
Boolean : function Boolean() {
[native code]
}
String : function String() {
[native code]
}
Number : function Number() {
[native code]
}
Date : function Date() {
[native code]
}
RegExp : function RegExp() {
[native code]
}
Error : function Error() {
[native code]
}
EvalError : function EvalError() {
[native code]
}
RangeError : function RangeError() {
[native code]
}
ReferenceError : function ReferenceError() {
[native code]
}
SyntaxError : function SyntaxError() {
[native code]
}
TypeError : function TypeError() {
[native code]
}
URIError : function URIError() {
[native code]
}
eval : function eval() {
[native code]
}
parseInt : function parseInt() {
[native code]
}
parseFloat : function parseFloat() {
[native code]
}
isNaN : function isNaN() {
[native code]
}
isFinite : function isFinite() {
[native code]
}
escape : function escape() {
[native code]
}
unescape : function unescape() {
[native code]
}
decodeURI : function decodeURI() {
[native code]
}
decodeURIComponent : function decodeURIComponent() {
[native code]
}
encodeURI : function encodeURI() {
[native code]
}
encodeURIComponent : function encodeURIComponent() {
[native code]
}
print : function () {
[native code]
}
gc : function gc() {
[native code]
}
version : function version() {
[native code]
}
TW : TWScriptAPI(name = “”)
__FILE__ : /home/jack/.TeXworks/scripts/tableWizard.js
__LINE__ : -1
CANNOT_OPEN_FILE : Errore: impossibile aprire il file
wizardScript : /home/jack/.TeXworks/scripts/tableWizard.js
formatterScript : /home/jack/.TeXworks/scripts/tableFormatter.js
file : // TeXworksScript
// Title: &Formatta tabella/matrice
// Description: Formatta il codice di una tabella o di una matrice.
// Author: Antonio Macrì
// Version: 0.9.5
// Date: 2011-06-09
// Script-Type: standalone
// Context: TeXDocument
// Shortcut: Ctrl+K, Ctrl+F

var formatterScript = __FILE__ ? __FILE__ : wizardScript.replace(“Wizard.js”,”Formatter.js”);

/**
* Usato per sapere se un ambiente LaTeX richiede l'argomento con gli
* specificatori di colonna (ad esempio: {ccccc}).
*/
function RequiresColumnSpecifiers(environment)
{
return environment == “array” || environment == “tabular”;
}

/**
* Aggiunge un carattere a destra di una stringa fino a raggiungere una data lunghezza.
*
* @param {number} width
* @param {string} c Il carattere da replicare in coda alla stringa.
*/
String.prototype.padRight = function(width, c)
{
return (width > this.length) ? (this + (c == null ? ” ” : c)).padRight(width, c) : this;
}

// Definisco la String.trim() se questa non esiste già (non tutte le versioni Qt la forniscono)
if(typeof(String.prototype.trim) == “undefined”)
{
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, “”); };
}

function TableFormatter()
{
this.Settings = {
AddTerminalEmptyCells: false,
MaxColumnWidth: 15,
InsertPadding: true,
Environment: null
}
}

TableFormatter.prototype.LoadSettings = function()
{
if (TW.app.hasGlobal(“TableFormatterSettings”))
{
this.Settings = TW.app.getGlobal(“TableFormatterSettings”);
return;
}
var settings = TW.readFile(formatterScript.replace(“.js”, “-settings.json”));
if (settings.status != 0) {
// Qualcosa è andata storta: non faccio niente.
return;
}
// Evito di riscrivere tutto Settings, ma aggiorno leggendole dal file solo le
// proprietà già presenti. Così facendo, se nel file ne manca qualcuna, rimane
// quella impostata nel costruttore e se invece ce ne sono di vecchie evito di
// portarmele dietro in eterno.
var properties = JSON.parse(settings.result);
for (var p in properties)
if (typeof(this.Settings[p]) != “undefined”) this.Settings[p] = properties[p];
}

TableFormatter.prototype.SaveSettings = function()
{
TW.app.setGlobal(“TableFormatterSettings”, this.Settings);

var r = TW.writeFile(formatterScript.replace(“.js”, “-settings.json”), JSON.stringify(this.Settings));
if (r == 2) {
// L'utente dovrebbe mettere la spunta a “Allow scripts to write files”:
// non faccio niente e semplicemente non salvo le impostazioni.
}
}

/**
* Analizza il codice LaTeX di una tabella/matrice ricavandone le righe e le colonne.
*
* @param {string} text Il codice LaTeX da analizzare.
*/
TableFormatter.prototype.ParseCode = function(text)
{
// Faccio una cosa molto semplice ma efficace (in prima approssimazione…)
// altrimenti il codice qui si complicherebbe di molto
var regex = /^(?:(?!\\\\).|\n)+(?:\\\\|(?=$))/;
var rows = new Array();
for (var i = 0; (matches = regex.exec(text)) != null; i++)
{
// Purtroppo non è supportato il costrutto di lookbehind nelle espressioni regolari
// Qt (altrimenti potrei fare .split(/(?<!\\)&/) per suddividere la riga in celle). // Mi tocca invece farlo a mano rows[i] = new Array(); var m = rows[i][0] = matches[0]; for (var pos = m.indexOf("&"); pos >= 0; pos = m.indexOf(“&”, pos))
{
if (pos == 0 || m[pos-1] != '\\')
{
rows[rows.length – 1] = m.substr(0, pos).replace(/\s+/g,” “).trim();
m = rows[rows.length] = m.substr(pos + 1);
pos = 0;
}
else pos++;
}
rows[rows.length – 1] = (m.substr(m.length-2) == “\\\\” ? m.substr(0, m.length-2) : m).replace(/\s+/g,” “).trim();

text = text.substring(matches[0].length);
}
this.Table = rows;
}

/**
* Genera il codice LaTeX di una tabella, aggiungendo opzionalmente degli spazi di
* riempimento e racchiudendo eventualmente il tutto in un ambiente.
*
* @param {object} [cells=this.Table] Una matrice bidimensionale di stringhe contenenti il
* testo della rispettiva cella. Righe differenti possono avere numero di colonne diverso.
* @param {number} [maxColumnWidth=this.Settings.MaxColumnWidth] La larghezza massima di
* una colonna del sorgente generato. Se vale zero, allora non viene usato alcun limite.
* @param {boolean} [addTerminalEmptyCells=this.Settings.AddTerminalEmptyCells] Specifica
* se tutte le righe generate devono avere lo stesso numero di colonne (si aggiungeranno,
* cioè, i delimitatori di colonna anche per le celle vuote finali).
* @param {boolean} [insertPadding=this.Settings.InsertPadding] Un booleano che specifica se
* inserire degli spazi di riempimento in modo da avere tutte le colonne del sorgente
* della stessa larghezza (i delimitatori di colonna '&' risulteranno così allineati).
* @param {string} [environment=this.Settings.Environment] Il nome dell'ambiente in cui
* inserire il codice.
*/
TableFormatter.prototype.GenerateCode = function(cells, maxColumnWidth, addTerminalEmptyCells, insertPadding, environment)
{
cells = cells ? cells : this.Table;
maxColumnWidth = maxColumnWidth ? maxColumnWidth : this.Settings.MaxColumnWidth;
addTerminalEmptyCells = typeof(addTerminalEmptyCells) != “undefined” ? addTerminalEmptyCells : this.Settings.AddTerminalEmptyCells;
insertPadding = typeof(insertPadding) != “undefined” ? insertPadding : this.Settings.InsertPadding;
environment = environment ? environment : this.Settings.Environment;

/**
* Divide una stringa in sottostringhe aventi (se possibile) la lunghezza specificata.
* Può accadere che la lunghezza di qualche sottostringa debba essere necessariamente
* maggiore di desiredWidth: tale valore viene comunque restituito al chiamante.
*
* @param {string} text La stringa da suddividere.
* @param {number} desiredWidth La dimensione ideale di ciascuna sottostringa.
* @returns {object} Restituisce un oggetto contenente nella proprietà Result un
* vettore con l'insieme di sottostringhe ottenute e nella proprietà MaxUsedWidth la
* lunghezza massima tra tutte le sottostringhe restituite (che può essere anche
* maggiore o minore del valore passato in desiredWidth).
*/
function SplitText(text, desiredWidth)
{
if (text.length > desiredWidth && desiredWidth != 0)
{
var lines = text.split(/\s+/);

// Prima di tutto prendo la lunghezza di ogni sottostringa e se è maggiore di desiredWidth
// allora quest'ultimo deve essere aggiornato con la lunghezza massima. Faccio questo
// all'inizio così il riaggiustamento della larghezza massima ha effetto anche sulle linee
// precedenti (anziché dal momento in cui lo riaggiusto in poi)
for (var i = 0; i < lines.length; i++) if (desiredWidth < lines[i].length) desiredWidth = lines[i].length; var maxUsedWidth = 0; var line = -1; var current = 0; while (current < lines.length) { line++; lines[line] = lines[current]; current++; while (current < lines.length && lines[line].length + lines[current].length < desiredWidth) { lines[line] += ' ' + lines[current]; current++; } maxUsedWidth = Math.max(maxUsedWidth, lines[line].length); } var result = lines.slice(0, line + 1); return { "Result": result, "MaxUsedWidth": maxUsedWidth }; } var result = new Array(); result[0] = text; return { "Result": result, "MaxUsedWidth": text.length }; } /** * Analizza le celle della tabella e genera una matrice bidimensionale contenente in * ogni elemento (i,j) un array con le linee in cui viene spezzato il testo del sorgente * relativo alla cella (i,j). */ function BuildCellLines() { var toReDo = new Array(); // indica che per le righe da 0 a toReDo[j] della colonna j bisogna ricalcolare la larghezza var colWidths = new Array(); // colWidths[j] contiene la larghezza massima della colonna j su tutte le righe var cellLines = new Array(); // cellLines[i][j] è un array contenente le linee in cui è stato suddiviso il testo della cella (i,j) var rows = cells.length; for (var i = 0; i < rows; i++) { cellLines[i] = new Array(); var cols = cells[i].length; for (var j = 0; j < cols; j++) { var desired = typeof(colWidths[j]) == "undefined" || maxColumnWidth == 0 ? maxColumnWidth : Math.max(maxColumnWidth, colWidths[j]); var returned = SplitText(cells[i][j].trim(), desired); cellLines[i][j] = returned.Result; if (typeof(colWidths[j]) != "undefined") { if(returned.MaxUsedWidth > colWidths[j])
{
// È stata modificata la larghezza, quindi dovrà ricalcolare le sottostringhe per
// le celle precedenti. Da notare che può succedere che toReDo venga sovrascritto,
// ovviamente con un valore maggiore (indici più avanti) ma perché la larghezza
// è ulteriormente aumentata
toReDo[j] = i – 1;
}
else continue;
}
colWidths[j] = returned.MaxUsedWidth;
}
}

for (var j = 0; j < toReDo.length; j++) { var row = toReDo[j]; if(typeof(row) != "undefined") { while (row >= 0)
{
if (cells[row][j])
cellLines[row][j] = SplitText(cells[row][j].trim(), colWidths[j]).Result;
row–;
}
}
}

return { “CellLines”: cellLines, “ColumnWidths”: colWidths };
}

/**
* Genera il codice LaTeX di una tabella, aggiungendo opzionalmente gli spazi di
* riempimento e racchiudendo eventualmente il tutto in un ambiente.
*
* @param {string[][][]} cellLines Una matrice bidimensionale contenente in ogni
* elemento (i,j) un array con le linee in cui è stato spezzato il testo del sorgente
* relativo alla cella (i,j).
* @param {number} colWidths La larghezza (in caratteri) di ciascuna colonna nel sorgente.
*/
function BuildLaTeXCode(cellLines, colWidths)
{
var terminator = “\n”;
var result = “”;
var rows = cellLines.length;
for (var i = 0; i < rows; i++) { var columnStartPosition = 0; var buffer = ""; var cols = cellLines[i].length; for (var j = 0; j < cols; j++) { var cell = cellLines[i][j]; for (var k = 0; k < cell.length; k++) { if (k > 0) {
buffer += terminator + “”.padRight(columnStartPosition);
}
var t = insertPadding ? cell[k].padRight(colWidths[j]) : cell[k];
buffer += t;
if(cell[k].length > 0) {
result += buffer;
buffer = “”;
}
cell[k] = t;
}

columnStartPosition += cell[cell.length – 1].length;
if (j < cols - 1) { buffer += " & "; columnStartPosition += 3; } } if (addTerminalEmptyCells) { result += buffer; for (var j = cols; j < colWidths.length; j++) result += " & " + (insertPadding ? "".padRight(colWidths[j]) : ""); } if (i < rows - 1) result += " \\\\"; result += terminator; } if (environment) { var name = environment.trim(); var columns = RequiresColumnSpecifiers(name) ? "{" + "c".padRight(colWidths.length, "c") + "}" : ""; if (name.length > 0)
result = “\\begin{” + name + “}” + columns + terminator + result + “\\end{” + name + “}” + terminator;
}

return result;
}

var returned = BuildCellLines();
return BuildLaTeXCode(returned.CellLines, returned.ColumnWidths);
}

formatter : [object Object]
selection :
RequiresColumnSpecifiers : function RequiresColumnSpecifiers(environment) {
return environment == “array” || environment == “tabular”;
}
TableFormatter : function TableFormatter() {
this.Settings = {
AddTerminalEmptyCells: false,
MaxColumnWidth: 15,
InsertPadding: true,
Environment: null
}
}
qsdb> .up
Already at top (outermost) frame.`

Go to top