├── +Snippet ├── +Element │ ├── Array.m │ ├── Regexp.m │ ├── Tabstop.m │ ├── TabstopMultiChoice.m │ └── Text.m ├── +Variable │ ├── clipBoard.m │ ├── date.m │ ├── dayName.m │ ├── dayNameShort.m │ ├── directory.m │ ├── fileName.m │ ├── fileNameBase.m │ ├── filePath.m │ ├── hour.m │ ├── lineIndex.m │ ├── lineNumber.m │ ├── minute.m │ ├── month.m │ ├── monthName.m │ ├── monthNameShort.m │ ├── second.m │ ├── selectedText.m │ ├── userName.m │ ├── year.m │ └── yearShort.m ├── Element.m └── Snippet.m ├── .gitattributes ├── LICENSE.md ├── MATLAB Snippets.mlappinstall ├── MATLAB Snippets.prj ├── MATLAB Snippets_resources ├── icon_16.png ├── icon_24.png └── icon_48.png ├── README.md ├── dialogs ├── insertSnippetAboutDlg.m └── insertSnippetOptionsDlg.m ├── favoriteCallback.txt ├── graphics ├── about_16_16.png ├── configure_16_16.png ├── edit_16_16.png ├── help_16_16.png ├── insertSnippet_16.png ├── insertSnippet_24.png ├── insertSnippet_48.png ├── open_16_16.png └── screenshot01.png ├── html ├── 02_simple_tabstop.gif ├── 03_simple_tabstop_prefix.gif ├── 04_complex_tabstops.gif ├── 05_plain_snippet.gif ├── 06_block_operations.gif ├── add_to_favorites.png ├── insertSnippet.png ├── matlabSnippets.mlx ├── options.png ├── previewModes.png └── quick_bar.png ├── insertSnippet.m ├── insertSnippetOptions.mat ├── jsonlab-1.5 ├── AUTHORS.txt ├── ChangeLog.txt ├── LICENSE_BSD.txt ├── README.txt ├── examples │ ├── demo_jsonlab_basic.m │ ├── demo_ubjson_basic.m │ ├── example1.json │ ├── example2.json │ ├── example3.json │ ├── example4.json │ ├── jsonlab_basictest.matlab │ ├── jsonlab_selftest.m │ ├── jsonlab_selftest.matlab │ └── jsonlab_speedtest.m ├── jsonopt.m ├── loadjson.m ├── loadubjson.m ├── mergestruct.m ├── savejson.m ├── saveubjson.m ├── struct2jdata.m └── varargin2struct.m ├── matlabSnippets.html ├── snippets ├── matlab-basic.json ├── matlab-custom.json ├── matlab-examples.json ├── matlab-miscellaneous.json ├── matlab-plot.json ├── matlab-separators.json ├── matlab-textformatting.json ├── matlab-uicontrol.json └── matlab-variables.json └── utils ├── addToFavorites.m ├── editor ├── clearWordAtCaretPosion.m ├── getActiveEditor.m ├── getLineAtCaretPosition.m └── getWordAtCaretPosition.m ├── findMatchingClosingBracket.m ├── findjobj_fast.m ├── formatting ├── alignCharacter.m ├── capitalize.m ├── fillEditorLineEndByCharacter.m ├── singleSpace.m └── strAbs.m ├── getAppID.m └── regexp ├── decomposeRegexpPlaceholder.m ├── passFirstIfNotEqual.m ├── passIfEqual.m ├── passIfNotEmpty.m ├── passIfNotEqual.m └── textMate2regexprep.m /+Snippet/+Element/Array.m: -------------------------------------------------------------------------------- 1 | classdef Array < Snippet.Element 2 | % ARRAY represents an array of of snippet elements like static text, 3 | % tabstop, regular expression and array. 4 | 5 | %#ok<*AGROW> 6 | 7 | properties ( Access = protected ) 8 | array % cell array of Spippet.Element objects 9 | end 10 | 11 | methods 12 | 13 | function obj = Array(array) 14 | % ARRAY constructs snippet element array. 15 | % 16 | % Syntax: 17 | % obj = ARRAY(array) 18 | % 19 | % Inputs: 20 | % array ... a cell array of Snippet.Element objects 21 | % 22 | if nargin==0 || isempty(array) 23 | obj.array = {}; 24 | else 25 | if iscell(array) 26 | for i = 1 : length(array) 27 | if ~isa(array{i},'Snippet.Element') 28 | error('The input argument must be a cell array of Snippet.Element objects.'); 29 | end 30 | end 31 | obj.array = array; 32 | else 33 | error('The input argument must be a cell array of Snippet.Element objects.'); 34 | end 35 | end 36 | end 37 | 38 | 39 | 40 | function str = toChar(obj) 41 | if isempty(obj.array) 42 | str = ''; 43 | else 44 | str = strjoin( ... 45 | cellfun(@(c)c.toChar(), obj.array, 'UniformOutput', false), ... 46 | '' ); 47 | end 48 | end 49 | 50 | 51 | 52 | function value = getPlaceholder(obj,number) 53 | value = []; 54 | values = cellfun( ... 55 | @(c)getPlaceholder(c,number), ... 56 | obj.array, 'UniformOutput', false ); 57 | for i = 1 : length(values) 58 | if ~isempty(values{i}) 59 | if isempty(value) 60 | value = values{i}; 61 | elseif ~strcmp(value,values{i}) 62 | %warning(['Tabstop number ' num2str(number) ' has multiple conflicting placeholders "' value '" and "' values{i} '".']); 63 | % --- warning disabled because it might be falsely triggered by 64 | % --- more complex snippets that combine nested regular 65 | % --- expressions. 66 | end 67 | end 68 | end 69 | end 70 | 71 | 72 | 73 | function setPlaceholder(obj,number,value) 74 | cellfun( ... 75 | @(c)setPlaceholder(c,number,value), ... 76 | obj.array ); 77 | end 78 | 79 | 80 | 81 | function placeholderObject = getPlaceholderObject(obj,number) 82 | placeholderObject = []; 83 | objects = cellfun( ... 84 | @(c)getPlaceholderObject(c,number), ... 85 | obj.array, 'UniformOutput', false ); 86 | for i = 1 : length(objects) 87 | if ~isempty(objects{i}) 88 | if isempty(placeholderObject) 89 | placeholderObject = objects{i}; 90 | elseif ~isequal(placeholderObject,objects{i}) 91 | warning(['Tabstop number ' num2str(number) ' has multiple conflicting placeholder definitions.']); 92 | end 93 | end 94 | end 95 | end 96 | 97 | 98 | 99 | function setPlaceholderObject(obj,number,placeholderObject) 100 | cellfun( ... 101 | @(c)setPlaceholderObject(c,number,placeholderObject), ... 102 | obj.array ); 103 | end 104 | 105 | 106 | 107 | function [iStart,iEnd] = getPlaceholderPosition(obj,number) 108 | iStart = []; 109 | iEnd = []; 110 | iend = 0; 111 | for i = 1 : length(obj.array) 112 | element = obj.array{i}; 113 | [iStart_,iEnd_] = getPlaceholderPosition(element,number); 114 | if ~isempty(iStart_) && ~isempty(iEnd_) 115 | if any(iStart_<1) || any( iEnd_ > length(element.toChar()) ) 116 | error('Placeholder indexes out of range.'); 117 | end 118 | iStart = [iStart iend+iStart_]; 119 | iEnd = [iEnd iend+iEnd_]; 120 | end 121 | iend = iend + length(element.toChar()); 122 | end 123 | end 124 | 125 | 126 | 127 | function numbers = getTabstopNumbers(obj) 128 | numbers = []; 129 | for i = 1 : length(obj.array) 130 | number = obj.array{i}.getTabstopNumbers(); 131 | if ~isempty(number) 132 | numbers = [ numbers number ]; 133 | end 134 | end 135 | numbers = sort(unique(numbers)); 136 | end 137 | 138 | 139 | 140 | function tabstopObject = getTabstopObject(obj,number) 141 | tabstopObject = []; 142 | tabstopObjects = cellfun( ... 143 | @(c)getTabstopObject(c,number), ... 144 | obj.array, 'UniformOutput', false ); 145 | for i = 1 : length(tabstopObjects) 146 | if ~isempty(tabstopObjects{i}) 147 | % return either the first object or the first with the 148 | % non-empty "value" property 149 | if isempty(tabstopObject) 150 | tabstopObject = tabstopObjects{i}; 151 | end 152 | hasValue = isprop(tabstopObject,'value') && ~isempty(tabstopObject.value); 153 | if hasValue 154 | return 155 | end 156 | end 157 | end 158 | end 159 | 160 | 161 | 162 | function isMirrored = isMirrored(obj,number) 163 | isMirrored = false; 164 | numberMatches = false(size(obj.array)); 165 | for i = 1 : length(obj.array) 166 | isMirrored = ... 167 | isMirrored || ... 168 | obj.array{i}.isMirrored(number); 169 | numberMatches(i) = ... 170 | ismember(number,obj.array{i}.getTabstopNumbers()); 171 | end 172 | isMirrored = isMirrored || (sum(numberMatches)>=2); 173 | end 174 | 175 | end 176 | 177 | 178 | methods(Access = protected) 179 | function cp = copyElement(obj) 180 | cp = Snippet.Element.Array; 181 | cp.array = {}; 182 | for i = 1 : length(obj.array) 183 | if isa(obj.array{i},'Snippet.Element') 184 | cp.array{i} = copy(obj.array{i}); 185 | else 186 | cp.array{i} = obj.array{i}; 187 | end 188 | end 189 | end 190 | end 191 | 192 | 193 | end -------------------------------------------------------------------------------- /+Snippet/+Element/Regexp.m: -------------------------------------------------------------------------------- 1 | classdef Regexp < Snippet.Element.Tabstop 2 | % REGEXP represents a snippet tabstop element with a regular replacement 3 | % epxression to mirror other tabstops. 4 | 5 | %#ok<*INUSD> 6 | 7 | properties ( Access = private ) 8 | expression % regexprep arument 9 | format % regexprep arument 10 | options % regexprep arument 11 | end 12 | 13 | methods 14 | 15 | function obj = Regexp(number,expression,format,options) 16 | % TABSTOP constructs snippet tabstop element. 17 | % 18 | % Syntax: 19 | % obj = TABSTOP(number,value) 20 | % 21 | % Inputs: 22 | % number ... tabstop number (scalar) 23 | % 24 | % 25 | obj.number = number; 26 | obj.value = ''; 27 | [obj.expression,obj.format,obj.options] = ... 28 | textMate2regexprep(expression,format,options); 29 | end 30 | 31 | 32 | 33 | function str = toChar(obj) 34 | str = toChar@Snippet.Element.Tabstop(obj); 35 | % --- 36 | if ~isempty(obj.expression) 37 | % --- Replace using regular expression 38 | str = regexprep( ... 39 | str, ... 40 | obj.expression, ... 41 | obj.format, ... 42 | obj.options{:}); 43 | % --- Questionable fix: char([13 10]) -> char(10) 44 | str = strrep(str,char([13 10]),char(10)); %#ok 45 | end 46 | end 47 | 48 | 49 | 50 | function value = getPlaceholder(obj,number) 51 | % no result from the regular expression element 52 | value = []; 53 | end 54 | 55 | 56 | 57 | function placeholderObject = getPlaceholderObject(obj,number) 58 | % no result from the regular expression element 59 | placeholderObject = []; 60 | end 61 | 62 | 63 | 64 | function [iStart,iEnd] = getPlaceholderPosition(obj,number) 65 | % no result from the regular expression element 66 | iStart = []; 67 | iEnd = []; 68 | end 69 | 70 | 71 | 72 | function tabstopObject = getTabstopObject(obj,number) 73 | % no result from the regular expression element 74 | tabstopObject = []; 75 | end 76 | 77 | end 78 | 79 | end -------------------------------------------------------------------------------- /+Snippet/+Element/Tabstop.m: -------------------------------------------------------------------------------- 1 | classdef Tabstop < Snippet.Element 2 | % TABSTOP represents a snippet tabstop element with a placeholder 3 | 4 | properties ( Access = protected ) 5 | number % tabstop number 6 | end 7 | 8 | properties 9 | value % placeholder value (character vector or Snippet.Element object) 10 | end 11 | 12 | methods 13 | 14 | function obj = Tabstop(number,value) 15 | % TABSTOP constructs snippet tabstop element. 16 | % 17 | % Syntax: 18 | % obj = TABSTOP(number,value) 19 | % 20 | % Inputs: 21 | % number ... tabstop number (scalar) 22 | % value .... character vector or Snippet.Element object 23 | % 24 | if nargin>0 25 | if ~ischar(value) && ~isa(value,'Snippet.Element') 26 | error(['Value input argument must be either ' ... 27 | 'a character vector or Snippet.Element object.']); 28 | end 29 | obj.number = number; 30 | obj.value = value; 31 | end 32 | end 33 | 34 | 35 | 36 | function str = toChar(obj) 37 | if isa(obj.value,'Snippet.Element') 38 | str = obj.value.toChar(); 39 | else 40 | str = obj.value; 41 | end 42 | end 43 | 44 | 45 | 46 | function value = getPlaceholder(obj,number) 47 | if obj.number == number 48 | value = obj.toChar(); 49 | elseif isa(obj.value,'Snippet.Element') 50 | % --- Nested tabstops with lower "priority" 51 | value = obj.value.getPlaceholder(number); 52 | else 53 | value = []; 54 | end 55 | end 56 | 57 | 58 | 59 | function setPlaceholder(obj,number,value) 60 | if ~ischar(value) 61 | error('Value input argument must be a character vector.'); 62 | end 63 | if obj.number == number 64 | % Any nested placeholders will be deleted 65 | obj.value = value; 66 | elseif isa(obj.value,'Snippet.Element') 67 | obj.value.setPlaceholder(number,value); 68 | end 69 | end 70 | 71 | 72 | 73 | function placeholderObject = getPlaceholderObject(obj,number) 74 | if obj.number == number 75 | placeholderObject = obj.value; 76 | elseif isa(obj.value,'Snippet.Element') 77 | % --- Nested tabstops with lower "priority" 78 | placeholderObject = obj.value.getPlaceholderObject(number); 79 | else 80 | placeholderObject = []; 81 | end 82 | end 83 | 84 | 85 | 86 | function setPlaceholderObject(obj,number,placeholderObject) 87 | if obj.number == number 88 | % Any nested placeholders will be deleted 89 | if isa(placeholderObject,'Snippet.Element') 90 | obj.value = copy( placeholderObject ); % !!! copy !!! 91 | else 92 | obj.value = placeholderObject; 93 | end 94 | elseif isa(obj.value,'Snippet.Element') 95 | obj.value.setPlaceholderObject(number,placeholderObject); 96 | end 97 | end 98 | 99 | 100 | 101 | function [iStart,iEnd] = getPlaceholderPosition(obj,number) 102 | if obj.number == number 103 | iStart = 1; 104 | iEnd = length(obj.toChar()); 105 | elseif isa(obj.value,'Snippet.Element') 106 | % --- Nested tabstops with lower "priority" 107 | [iStart,iEnd] = getPlaceholderPosition(obj.value,number); 108 | else 109 | iStart = []; 110 | iEnd = []; 111 | end 112 | end 113 | 114 | 115 | 116 | function numbers = getTabstopNumbers(obj) 117 | numbers = obj.number; 118 | if isa(obj.value,'Snippet.Element') 119 | numbers = [ numbers getTabstopNumbers(obj.value) ]; 120 | end 121 | numbers = sort(unique(numbers)); 122 | end 123 | 124 | 125 | 126 | function tabstopObject = getTabstopObject(obj,number) 127 | if obj.number == number % && ~isempty(obj.value) 128 | tabstopObject = obj; 129 | elseif isa(obj.value,'Snippet.Element') 130 | % --- Nested tabstops with lower "priority" 131 | tabstopObject = obj.value.getTabstopObject(number); 132 | else 133 | tabstopObject = []; 134 | end 135 | end 136 | 137 | 138 | 139 | function isMirrored = isMirrored(obj,number) 140 | if isa(obj.value,'Snippet.Element') 141 | isMirrored = ... 142 | obj.value.isMirrored(number) || ... 143 | ismember( obj.number, getTabstopNumbers(obj.value)); 144 | else 145 | isMirrored = false; 146 | end 147 | end 148 | 149 | end 150 | 151 | end -------------------------------------------------------------------------------- /+Snippet/+Element/TabstopMultiChoice.m: -------------------------------------------------------------------------------- 1 | classdef TabstopMultiChoice < Snippet.Element 2 | % TABSTOPMULTICHOICE represents a snippet tabstop element with 3 | % a multi-choice placeholder. 4 | 5 | properties ( Access = private ) 6 | number % tabstop number 7 | choices % possible choices (cell array of character vectors) 8 | end 9 | 10 | properties 11 | choiceIndex % current choice index 12 | end 13 | 14 | methods 15 | 16 | function obj = TabstopMultiChoice(number,choices) 17 | % TABSTOPMULTICHOICE constructs snippet tabstop element with 18 | % multiple choices. 19 | % 20 | % Syntax: 21 | % obj = TABSTOPMULTICHOICE(number,choices) 22 | % 23 | % Inputs: 24 | % number .... tabstop number (scalar) 25 | % choices ... possible choices (cell array of character vectors) 26 | % 27 | if isempty(choices) || ~iscell(choices) || ~all(cellfun(@(c)ischar(c),choices)) 28 | error(['The input argument "choices" must be a non-empty ' ... 29 | 'cell array of character vectors.']); 30 | end 31 | obj.number = number; 32 | obj.choices = choices; 33 | obj.choiceIndex = 1; 34 | end 35 | 36 | 37 | 38 | function nextChoice = getNextChoice(obj) 39 | choiceIndex_ = min( obj.choiceIndex+1, length(obj.choices) ); 40 | nextChoice = obj.choices{ choiceIndex_ }; 41 | end 42 | 43 | 44 | 45 | function previousChoice = getPreviousChoice(obj) 46 | choiceIndex_ = max( 1 , obj.choiceIndex-1 ); 47 | previousChoice = obj.choices{ choiceIndex_ }; 48 | end 49 | 50 | 51 | 52 | function str = toChar(obj) 53 | str = obj.choices{obj.choiceIndex}; 54 | end 55 | 56 | 57 | 58 | function value = getPlaceholder(obj,number) 59 | if obj.number == number 60 | value = obj.toChar(); 61 | else 62 | value = []; 63 | end 64 | end 65 | 66 | 67 | 68 | function setPlaceholder(obj,number,value) 69 | if number == obj.number 70 | ind = find( strcmp(obj.choices,value) ); 71 | if isempty(ind) 72 | warning(['Value "' value '" is not in the list of multi-choice placeholder possible choices.']); 73 | ind = 1; 74 | end 75 | obj.choiceIndex = ind(1); 76 | end 77 | end 78 | 79 | 80 | 81 | function placeholderObject = getPlaceholderObject(obj,number) 82 | if obj.number == number 83 | placeholderObject = obj.toChar(); 84 | else 85 | placeholderObject = []; 86 | end 87 | end 88 | 89 | 90 | 91 | function setPlaceholderObject(obj,number,placeholderObject) 92 | if obj.number == number 93 | if ischar(placeholderObject) 94 | obj.setPlaceholder(number,placeholderObject); 95 | else 96 | error('The input argument "placeholderObject" must be a character vector.'); 97 | end 98 | end 99 | end 100 | 101 | 102 | 103 | function [iStart,iEnd] = getPlaceholderPosition(obj,number) 104 | if obj.number == number 105 | iStart = 1; 106 | iEnd = length(obj.toChar()); 107 | else 108 | iStart = []; 109 | iEnd = []; 110 | end 111 | end 112 | 113 | 114 | 115 | function numbers = getTabstopNumbers(obj) 116 | numbers = obj.number; 117 | end 118 | 119 | 120 | 121 | function tabstopObject = getTabstopObject(obj,number) 122 | if obj.number == number && ~isempty(obj.choices) 123 | tabstopObject = obj; 124 | else 125 | tabstopObject = []; 126 | end 127 | end 128 | 129 | end 130 | 131 | end -------------------------------------------------------------------------------- /+Snippet/+Element/Text.m: -------------------------------------------------------------------------------- 1 | classdef Text < Snippet.Element 2 | % TEXT represents a snippet element with a static text 3 | 4 | properties( Access = private ) 5 | text 6 | end 7 | 8 | methods 9 | 10 | function obj = Text(text) 11 | % TEXT constructs snippet text element 12 | % 13 | % Syntax: 14 | % obj = TEXT(text) 15 | % 16 | % Inputs: 17 | % text ... cell array 18 | % 19 | if ~ischar(text) 20 | error('The input argument must a character vector.'); 21 | end 22 | 23 | % --- Restore reserved characters 24 | text = strrep( text, '\$', '$' ); 25 | text = strrep( text, '\`', '`' ); 26 | 27 | obj.text = text; 28 | end 29 | 30 | 31 | 32 | function str = toChar(obj) 33 | str = obj.text; 34 | end 35 | 36 | end 37 | 38 | end 39 | -------------------------------------------------------------------------------- /+Snippet/+Variable/clipBoard.m: -------------------------------------------------------------------------------- 1 | function out = clipBoard() 2 | % The contents of the clipboard 3 | out = clipboard('paste'); 4 | end 5 | -------------------------------------------------------------------------------- /+Snippet/+Variable/date.m: -------------------------------------------------------------------------------- 1 | function out = date() 2 | out = datestr(now,'dd'); 3 | end -------------------------------------------------------------------------------- /+Snippet/+Variable/dayName.m: -------------------------------------------------------------------------------- 1 | function out = dayName() 2 | out = datestr(now,'dddd'); 3 | end -------------------------------------------------------------------------------- /+Snippet/+Variable/dayNameShort.m: -------------------------------------------------------------------------------- 1 | function out = dayNameShort() 2 | out = datestr(now,'ddd'); 3 | end -------------------------------------------------------------------------------- /+Snippet/+Variable/directory.m: -------------------------------------------------------------------------------- 1 | function out = directory() 2 | % The directory of the current document 3 | activeEditor = getActiveEditor(); 4 | if isempty(activeEditor) 5 | out = ''; 6 | else 7 | out = fileparts( char( activeEditor.JavaEditor.getLongName ) ); 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /+Snippet/+Variable/fileName.m: -------------------------------------------------------------------------------- 1 | function out = fileName() 2 | % The filename of the current document 3 | activeEditor = getActiveEditor(); 4 | if isempty(activeEditor) 5 | out = ''; 6 | else 7 | out = char( activeEditor.JavaEditor.getShortName ); 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /+Snippet/+Variable/fileNameBase.m: -------------------------------------------------------------------------------- 1 | function out = fileNameBase() 2 | % The filename of the current document without its extensions 3 | activeEditor = getActiveEditor(); 4 | if isempty(activeEditor) 5 | out = ''; 6 | else 7 | [~,out] = fileparts( char( activeEditor.JavaEditor.getLongName ) ); 8 | end 9 | end -------------------------------------------------------------------------------- /+Snippet/+Variable/filePath.m: -------------------------------------------------------------------------------- 1 | function out = filePath() 2 | %The full file path of the current document 3 | activeEditor = getActiveEditor(); 4 | if isempty(activeEditor) 5 | out = ''; 6 | else 7 | out = char( activeEditor.JavaEditor.getLongName ); 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /+Snippet/+Variable/hour.m: -------------------------------------------------------------------------------- 1 | function out = hour() 2 | out = datestr(now,'HH'); 3 | end -------------------------------------------------------------------------------- /+Snippet/+Variable/lineIndex.m: -------------------------------------------------------------------------------- 1 | function out = lineIndex() 2 | % zero-based 3 | activeEditor = getActiveEditor(); 4 | if isempty(activeEditor) 5 | out = ''; 6 | else 7 | out = num2str( activeEditor.JavaEditor.getLineNumber ); 8 | end 9 | end -------------------------------------------------------------------------------- /+Snippet/+Variable/lineNumber.m: -------------------------------------------------------------------------------- 1 | function out = lineNumber() 2 | % one-based 3 | activeEditor = getActiveEditor(); 4 | if isempty(activeEditor) 5 | out = ''; 6 | else 7 | out = num2str( activeEditor.JavaEditor.getLineNumber+1 ); 8 | end 9 | end -------------------------------------------------------------------------------- /+Snippet/+Variable/minute.m: -------------------------------------------------------------------------------- 1 | function out = minute() 2 | out = datestr(now,'MM'); 3 | end -------------------------------------------------------------------------------- /+Snippet/+Variable/month.m: -------------------------------------------------------------------------------- 1 | function out = month() 2 | out = datestr(now,'mm'); 3 | end -------------------------------------------------------------------------------- /+Snippet/+Variable/monthName.m: -------------------------------------------------------------------------------- 1 | function out = monthName() 2 | out = datestr(now,'mmmm'); 3 | end -------------------------------------------------------------------------------- /+Snippet/+Variable/monthNameShort.m: -------------------------------------------------------------------------------- 1 | function out = monthNameShort() 2 | out = datestr(now,'mmm'); 3 | end -------------------------------------------------------------------------------- /+Snippet/+Variable/second.m: -------------------------------------------------------------------------------- 1 | function out = second() 2 | out = datestr(now,'SS'); 3 | end -------------------------------------------------------------------------------- /+Snippet/+Variable/selectedText.m: -------------------------------------------------------------------------------- 1 | function out = selectedText() 2 | activeEditor = getActiveEditor(); 3 | if isempty(activeEditor) 4 | out = ''; 5 | else 6 | out = activeEditor.SelectedText; 7 | end 8 | end -------------------------------------------------------------------------------- /+Snippet/+Variable/userName.m: -------------------------------------------------------------------------------- 1 | function out = userName() 2 | % Windows user name 3 | out = getenv('USERNAME'); 4 | end 5 | 6 | -------------------------------------------------------------------------------- /+Snippet/+Variable/year.m: -------------------------------------------------------------------------------- 1 | function out = year 2 | out = datestr(now,'yyyy'); 3 | end -------------------------------------------------------------------------------- /+Snippet/+Variable/yearShort.m: -------------------------------------------------------------------------------- 1 | function out = yearShort 2 | out = datestr(now,'yy'); 3 | end -------------------------------------------------------------------------------- /+Snippet/Element.m: -------------------------------------------------------------------------------- 1 | classdef Element < handle & matlab.mixin.CustomDisplay & matlab.mixin.Copyable 2 | % ELEMENT is a superclass for snippet elements like static text, tabstop, 3 | % regular expression and array. 4 | 5 | %#ok<*INUSD> 6 | %#ok<*MANU> 7 | 8 | methods( Abstract ) 9 | 10 | str = toChar(obj) 11 | % TOCHAR converts the snippet element to the character vector. 12 | % 13 | % Syntax: 14 | % str = TOCHAR(obj); 15 | % 16 | % Outputs: 17 | % str ... character vector 18 | % 19 | 20 | end 21 | 22 | methods 23 | 24 | function value = getPlaceholder(obj,number) 25 | % GETPLACEHOLDER gets placeholder for the first tabstop with the 26 | % matching number and nonempty placeholder. 27 | % 28 | % Syntax: 29 | % value = GETPLACEHOLDER(obj,number) 30 | % 31 | % Inputs: 32 | % number ... tabstop number 33 | % 34 | % Outputs: 35 | % value .... character vector 36 | % 37 | value = []; 38 | end 39 | 40 | 41 | 42 | function setPlaceholder(obj,number,value) 43 | % SETPLACEHOLDER sets placeholder to all tabstops with the 44 | % matching number. 45 | % 46 | % Syntax: 47 | % SETPLACEHOLDER(obj,number,value) 48 | % 49 | % Inputs: 50 | % number ... tabstop number 51 | % value .... character vector 52 | % 53 | end 54 | 55 | 56 | 57 | function placeholderObject = getPlaceholderObject(obj,number) 58 | % GETPLACEHOLDER gets placeholder object for the first tabstop with the 59 | % matching number and nonempty placeholder. 60 | % 61 | % Syntax: 62 | % value = GETPLACEHOLDER(obj,number) 63 | % 64 | % Inputs: 65 | % number ... tabstop number 66 | % 67 | % Outputs: 68 | % placeholderObject .... placeholder object (character vector or 69 | % Snippet.Element object) 70 | % 71 | placeholderObject = []; 72 | end 73 | 74 | 75 | 76 | function setPlaceholderObject(obj,number,placeholderObject) 77 | % SETPLACEHOLDEROBJECT sets placeholder object to all tabstops with 78 | % the matching number. 79 | % 80 | % Syntax: 81 | % SETPLACEHOLDEROBJECT(obj,number,placeholderObject) 82 | % 83 | % Inputs: 84 | % number ............... tabstop number 85 | % placeholderObject .... placeholder object (character vector or 86 | % Snippet.Element object) 87 | % 88 | end 89 | 90 | 91 | 92 | function [iStart,iEnd] = getPlaceholderPosition(obj,number) 93 | % GETPLACEHOLDERPOSITION returns position indexes of all 94 | % placeholders with the matching tabstop number. The indexes give 95 | % character positions in the cell array returned by the toChar(). 96 | % 97 | % Syntax: 98 | % [iStart,iEnd] = getPlaceholderPosition(obj,number) 99 | % 100 | % Inputs: 101 | % number ... tabstop number 102 | % 103 | % Outputs: 104 | % iStart ... placeholder first character positions (1,n) 105 | % iEnd ..... placeholder last character positions (1,n) 106 | % 107 | iStart = []; 108 | iEnd = []; 109 | end 110 | 111 | 112 | 113 | function numbers = getTabstopNumbers(obj) 114 | % GETTABSTOPNUMBERS returns an array of sorted unique placeholder 115 | % numbers. 116 | % 117 | % Syntax: 118 | % numbers = getTabstopNumbers(obj) 119 | % 120 | % Outputs: 121 | % number ... an array of unique tabstop numbers 122 | % 123 | numbers = []; 124 | end 125 | 126 | 127 | 128 | function tabstopObject = getTabstopObject(obj,number) 129 | % GETTABSTOPOBJECT gets tabstop object for the first tabstop 130 | % with the matching number and nonempty placeholder. 131 | % 132 | % Syntax: 133 | % tabstopObject = GETTABSTOPOBJECT(obj,number) 134 | % 135 | % Inputs: 136 | % number ... tabstop number 137 | % 138 | % Outputs: 139 | % tabstopObject .... tabstop object (Snippet.Element) 140 | % 141 | tabstopObject = []; 142 | end 143 | 144 | 145 | 146 | function isMirrored = isMirrored(obj,number) 147 | % ISMIRRORED indicates if the tabstop number is mirrored in the 148 | % snippet. 149 | % 150 | % Syntax: 151 | % isMirrored = isMirrored(obj,number) 152 | % 153 | % Inputs: 154 | % number ... tabstop number 155 | % 156 | % Outputs: 157 | % isMirrored .... tabstop mirroring indicator (logical) 158 | % 159 | isMirrored = false; 160 | end 161 | 162 | end 163 | 164 | methods (Access = protected) 165 | 166 | function displayScalarObject(obj) 167 | % DISPLAYSCALARBOJECT displays the object to the command window 168 | fprintf('Snippet:\n'); 169 | disp(obj.toChar()); 170 | disp(' '); 171 | tabstopNumbers = getTabstopNumbers(obj); 172 | fprintf('Tabstop numbers:\n'); 173 | disp(num2str(tabstopNumbers(:)')); 174 | disp(' '); 175 | end 176 | 177 | end 178 | 179 | end 180 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.html linguist-documentation=true 2 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | BSD 2-Clause License 2 | 3 | Copyright (c) 2019, Pavel Trnka 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | * Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 12 | * Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 20 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 21 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 22 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 23 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 24 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | -------------------------------------------------------------------------------- /MATLAB Snippets.mlappinstall: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/MATLAB Snippets.mlappinstall -------------------------------------------------------------------------------- /MATLAB Snippets.prj: -------------------------------------------------------------------------------- 1 | 2 | 3 | MATLAB Snippets 4 | Pavel Trnka 5 | pavel@trnka.name 6 | 7 | ${PROJECT_ROOT}\MATLAB Snippets_resources\icon_24.png 8 | 9 | ${PROJECT_ROOT}\MATLAB Snippets_resources\icon_48.png 10 | ${PROJECT_ROOT}\MATLAB Snippets_resources\icon_24.png 11 | ${PROJECT_ROOT}\MATLAB Snippets_resources\icon_16.png 12 | 13 | Code snippets for the Matlab editor. 14 | Code snippets for the Matlab editor. Adding the app to the Quick Access Toolbar allows you to trigger it by a keyboard shortcut (e.g. ALT+1). Features: 15 | <ul> 16 | <li>snippets can contain tabstops with default values (placeholders)</li> 17 | <li>any tabstop value can be mirrored on multiple locations in the snippet</li> 18 | <li>variables containing currently selected text, currently edited filename, etc. can be used</li> 19 | <li>regular expression replacement can be used</li> 20 | </ul> 21 | Snippets definition uses syntax compatible with <a href="https://code.visualstudio.com/docs/editor/userdefinedsnippets">Visual Studio Code</a> and <a href="https://macromates.com/manual/en/snippets">Textmate</a>. 22 | ${PROJECT_ROOT}\graphics\screenshot01.png 23 | 1.0 24 | 25 | 26 | 27 | 28 | ${PROJECT_ROOT} 29 | 8bfd37e6-10e5-4889-84a4-6c68df10c1c1 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | ${PROJECT_ROOT}\insertSnippet.m 41 | 42 | 43 | ${PROJECT_ROOT}\+Snippet\+Element\Array.m 44 | ${PROJECT_ROOT}\+Snippet\+Element\Regexp.m 45 | ${PROJECT_ROOT}\+Snippet\+Element\Tabstop.m 46 | ${PROJECT_ROOT}\+Snippet\+Element\TabstopMultiChoice.m 47 | ${PROJECT_ROOT}\+Snippet\+Element\Text.m 48 | ${PROJECT_ROOT}\+Snippet\+Variable\clipBoard.m 49 | ${PROJECT_ROOT}\+Snippet\+Variable\date.m 50 | ${PROJECT_ROOT}\+Snippet\+Variable\dayName.m 51 | ${PROJECT_ROOT}\+Snippet\+Variable\dayNameShort.m 52 | ${PROJECT_ROOT}\+Snippet\+Variable\directory.m 53 | ${PROJECT_ROOT}\+Snippet\+Variable\fileName.m 54 | ${PROJECT_ROOT}\+Snippet\+Variable\fileNameBase.m 55 | ${PROJECT_ROOT}\+Snippet\+Variable\filePath.m 56 | ${PROJECT_ROOT}\+Snippet\+Variable\hour.m 57 | ${PROJECT_ROOT}\+Snippet\+Variable\lineIndex.m 58 | ${PROJECT_ROOT}\+Snippet\+Variable\lineNumber.m 59 | ${PROJECT_ROOT}\+Snippet\+Variable\minute.m 60 | ${PROJECT_ROOT}\+Snippet\+Variable\month.m 61 | ${PROJECT_ROOT}\+Snippet\+Variable\monthName.m 62 | ${PROJECT_ROOT}\+Snippet\+Variable\monthNameShort.m 63 | ${PROJECT_ROOT}\+Snippet\+Variable\second.m 64 | ${PROJECT_ROOT}\+Snippet\+Variable\selectedText.m 65 | ${PROJECT_ROOT}\+Snippet\+Variable\userName.m 66 | ${PROJECT_ROOT}\+Snippet\+Variable\year.m 67 | ${PROJECT_ROOT}\+Snippet\+Variable\yearShort.m 68 | ${PROJECT_ROOT}\+Snippet\Element.m 69 | ${PROJECT_ROOT}\+Snippet\Snippet.m 70 | ${PROJECT_ROOT}\dialogs\insertSnippetAboutDlg.m 71 | ${PROJECT_ROOT}\dialogs\insertSnippetOptionsDlg.m 72 | ${PROJECT_ROOT}\utils\addToFavorites.m 73 | ${PROJECT_ROOT}\utils\editor\clearWordAtCaretPosion.m 74 | ${PROJECT_ROOT}\utils\editor\getActiveEditor.m 75 | ${PROJECT_ROOT}\utils\editor\getLineAtCaretPosition.m 76 | ${PROJECT_ROOT}\utils\editor\getWordAtCaretPosition.m 77 | ${PROJECT_ROOT}\utils\findjobj_fast.m 78 | ${PROJECT_ROOT}\utils\findMatchingClosingBracket.m 79 | ${PROJECT_ROOT}\utils\getAppID.m 80 | ${PROJECT_ROOT}\utils\regexp\decomposeRegexpPlaceholder.m 81 | ${PROJECT_ROOT}\utils\regexp\textMate2regexprep.m 82 | 83 | 84 | ${PROJECT_ROOT}\favoriteCallback.txt 85 | ${PROJECT_ROOT}\graphics 86 | ${PROJECT_ROOT}\insertSnippetOptions.mat 87 | ${PROJECT_ROOT}\matlabSnippets.html 88 | ${PROJECT_ROOT}\snippets 89 | ${PROJECT_ROOT}\utils\formatting 90 | 91 | 92 | 93 | C:\work\repo\github\snippets 94 | 95 | 96 | 97 | C:\Program Files\MATLAB\R2019b 98 | 99 | 100 | 101 | 102 | 103 | true 104 | 105 | 106 | 107 | 108 | false 109 | false 110 | true 111 | false 112 | false 113 | false 114 | false 115 | false 116 | 10.0 117 | false 118 | true 119 | win64 120 | true 121 | 122 | 123 | -------------------------------------------------------------------------------- /MATLAB Snippets_resources/icon_16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/MATLAB Snippets_resources/icon_16.png -------------------------------------------------------------------------------- /MATLAB Snippets_resources/icon_24.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/MATLAB Snippets_resources/icon_24.png -------------------------------------------------------------------------------- /MATLAB Snippets_resources/icon_48.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/MATLAB Snippets_resources/icon_48.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MATLAB Snippets App 2 | MATLAB Snippets App adds code snippets to the Matlab editor. Snippets definition uses syntax compatible with the [Visual Studio Code](https://code.visualstudio.com/docs/editor/userdefinedsnippets) and with the [Textmate 1.x](https://macromates.com/manual/en/snippets). The integration to the Matlab editor is loose, the snippets are inserted by a keyboard shortcut (usually **ALT+1**). 3 | 4 | ## Installation 5 | Download the app package [MATLAB Snippets.mlappinstall](https://github.com/trnkap/matlab-snippets/raw/master/MATLAB%20Snippets.mlappinstall) and run it on your computer or install it using the "Install App" button on the Matlab "APPS" ribon. The app icon "MATLAB Snippets" will appear on the "APPS" ribon. Clicking on it for the first time offers you to create a shortcut on the Quick Access Toolbar. 6 | 7 | ![](html/add_to_favorites.png) 8 | 9 | This is important, because each shortcut on the Quick Access Toolbar is associated with a keyboard shortcut. The first position from the left is associated with the **ALT+1** keyboard shortcut. 10 | 11 | ![](html/quick_bar.png) 12 | 13 | ## Using MATLAB Snippets 14 | Press **ALT+1** in the Matlab editor to open the "Insert Snippet" window. 15 | 16 | ![](html/insertSnippet.png) 17 | 18 | It shows a list of available snippets on the left. For each snippet it displays its prefix and a short description. The list of snippets can be filtered by typing to the top left edit box (focused by default). Snippets can be selected by the up/down arrows. The selected snippet is previewed in the right pane. All available actions and keyboard shortcuts for each step are shown in the bottom status bar. 19 | 20 | Press **ENTER** to insert the selected snippet to the Matlab editor. Most snippets have tabstops that allows you to modify the snippet before inserting it to the Matlab editor. To start snippet modification press **TAB** instead of **ENTER**. The cursor will move to the position of the first tabstop where you can either modify the existing placeholder or you can start to type a new value. Pressing **TAB** again will move the cursor to the next tabstop or it will insert the snippet to the Matlab editor if it was the last tabstop. By pressing **Shift+TAB** you can move to the previous tabstop. Note that you can modify only the text of the current tabstop. The cursor can move arbitrarily; however, any changes out of the currently selected tabstop will be discarded. 21 | 22 | The window can be closed anytime without any action by **ESC**. 23 | Each tabstop can be mirrored on multiple locations in the snippet. Target tabstops can adjust the mirrored value by a regular expression and by calling Matlab functions. Tabstops can be also nested, which allows you typically to delete or overwrite a complex placeholder or modify nested tabstops. These features will be shown in the animated examples. 24 | Note that window elements are using the same graphical style as the Matlab editor (font type, font size, syntax coloring, etc.), 25 | 26 | ## Example - Inserting a simple snippet 27 | The animation shows a simple snippet for the double for-loop. After the snippet is selected from the list, use **TAB** to jump to the first tabstop, where you can modify the default placeholder. Press **TAB** again to jump to the next tabstop. Notice that at the first tabstop you can either modify the placeholder `"1 : m"` or you can jump to the second placeholder to modify only the `"m"` (nested placeholders). 28 | 29 | ![](html/02_simple_tabstop.gif) 30 | 31 | Alternatively the prefix can be partially or fully specified in the Matlab editor before pressing **ALT+1**. If the text at the current editor caret matches with some snippet prefix then this snippet is either immediately inserted to the Matlab editor (if it has no tabstops) or the snippet window opens in the tabstop editing mode. 32 | 33 | ![](html/03_simple_tabstop_prefix.gif) 34 | 35 | ## Example - Inserting a complex snippet 36 | The animation shows a more complex snippet for a function header. Notice that the input and output argument names are automatically mirrored in the "Syntax" section and also a detailed description of each argument is prepared in the "Inputs" or "Outputs" section. Similarly the function name is mirrored in the "Syntax" section and also mirrored in the uppercase in the first comment line. This is achieved by the regular expressions in the snippet definition. 37 | 38 | ![](html/04_complex_tabstops.gif) 39 | 40 | ## Example - Inserting a snippet without tabstops 41 | Snippets without tabstops can be quickly inserted without opening the snippet window by typing its prefix and pressing **ALT+1**. 42 | 43 | ![](html/05_plain_snippet.gif) 44 | 45 | ## Example - Selected text formatting 46 | Selecting a block of text in the Matlab editor and pressing **ALT+1** gives a list of snippets that can format it. For example it can be used to align specific symbols like `'='` and `'%'`. 47 | 48 | ![](html/06_block_operations.gif) 49 | 50 | ## Options 51 | The options window has a list of the loaded snippet definition files. Double-clicking the file names will enable and disable them. Clicking on the edit button (with the pen icon) will open the snippet json file in the Matlab editor. Click the "View Snippet Syntax" button to view the snippet file syntax in the external web browser (a link to the Visual Studio Code documentation). 52 | 53 | ![](html/options.png) 54 | 55 | You can select these snippet preview modes: 56 | 57 | ![](html/previewModes.png) 58 | 59 | ## Undocumented Matlab Functions 60 | Some features were possible only by using undocumented Matlab functions that may change or break in future Matlab releases. The App was tested in Matlab R2016a and R2018b. 61 | 62 | ## Acknowledgement 63 | Inspired by the ["Insert a piece of code (a snippet) in the Matlab editor"](https://www.mathworks.com/matlabcentral/fileexchange/41704-insert-a-piece-of-code-a-snippet-in-the-matlab-editor). 64 | 65 | Inspired by the ["MATLAB for Visual Studio Code"](https://marketplace.visualstudio.com/items?itemName=Gimly81.matlab). 66 | 67 | Uses the ["JSONlab"](https://github.com/fangq/jsonlab) to decode JSON files for Matlab R2016a and earlier. 68 | 69 | Uses code based on the ["findjobj"](https://www.mathworks.com/matlabcentral/fileexchange/14317-findjobj-find-java-handles-of-matlab-graphic-objects) to find java handles of Matlab graphic objects. 70 | -------------------------------------------------------------------------------- /dialogs/insertSnippetAboutDlg.m: -------------------------------------------------------------------------------- 1 | function insertSnippetAboutDlg(versionStr) 2 | 3 | figSize = [ 400 300 ]; 4 | 5 | screenSize = get(0, 'ScreenSize'); 6 | hFig = figure( ... 7 | 'WindowStyle', 'modal', ... 8 | 'Position', [ 0.5*screenSize(3:4)-0.5*figSize figSize ], ... 9 | 'DockControls', 'off', ... 10 | 'MenuBar', 'none', ... 11 | 'NumberTitle', 'off', ... 12 | 'Name', 'About', ... 13 | 'KeyPressFcn', @figureKeyPressFcn ... 14 | ); 15 | 16 | hPanel = uipanel(hFig, ... 17 | 'Title','', ... 18 | 'Units','pixels',... 19 | 'Position',[10 figSize(2)-78 380 68] ); 20 | 21 | axes(hPanel,'Units','pixels','Position',[10 10 48 48]); 22 | [img,map] = imread('insertSnippet_48.png'); 23 | map(double(img(1,1))+1,:) = hFig.Color; 24 | imshow(img,map); 25 | 26 | labelStr = [''... 27 | 'MATLAB Snippets
' ... 28 | 'Pavel Trnka (pavel@trnka.name)
' ... 29 | 'Version: ' versionStr '']; 30 | jLabel = javaObjectEDT('javax.swing.JLabel',labelStr); 31 | % --- 32 | oldWarn = warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame'); 33 | warning('off','MATLAB:ui:javacomponent:FunctionToBeRemoved'); 34 | javacomponent(jLabel,[78,10,380-78-10,48],hPanel); 35 | warning(oldWarn); 36 | % --- 37 | 38 | uicontrol(... 39 | 'style', 'edit', ... 40 | 'Position', [10 60 380 80+68], ... 41 | 'BackgroundColor', 0.9*hFig.Color, ... 42 | 'HorizontalAlignment','left', ... 43 | ...'Enable', 'inactive', ... 44 | 'Max',2, ... 45 | 'String', { 46 | 'INSPIRED BY:' 47 | '============' 48 | '"Insert a piece of code (a snippet) in the Matlab editor"' 49 | 'https://www.mathworks.com/matlabcentral/fileexchange/41704-insert-a-piece-of-code-a-snippet-in-the-matlab-editor' 50 | '' 51 | '"MATLAB for Visual Studio Code"' 52 | 'https://marketplace.visualstudio.com/items?itemName=Gimly81.matlab' 53 | '' 54 | 'USES:' 55 | '=====' 56 | '"JSONlab: a toolbox to encode/decode JSON files"' 57 | 'https://www.mathworks.com/matlabcentral/fileexchange/33381-jsonlab-a-toolbox-to-encode-decode-json-files' 58 | '' 59 | '"findjobj - find java handles of Matlab graphic objects"' 60 | 'https://www.mathworks.com/matlabcentral/fileexchange/14317-findjobj-find-java-handles-of-matlab-graphic-objects' 61 | '' 62 | } ... 63 | ); 64 | 65 | uicontrol(... 66 | 'style', 'pushbutton', ... 67 | 'Position', [90+20 15 130 30], ... 68 | 'String', 'Matlab File Exchange', ... 69 | 'Callback', @fileExchangeCallback ... 70 | ); 71 | 72 | uicontrol(... 73 | 'style', 'pushbutton', ... 74 | 'Position', [240+20 15 130 30], ... 75 | 'String', 'GitHub', ... 76 | 'Callback', @gitHubBtnCallback ... 77 | ); 78 | 79 | uicontrol( ... 80 | 'Style', 'text', ... 81 | 'String', 'Visit project page:', ... 82 | 'Position', [10 17 90 20], ... 83 | 'HorizontalAlignment','left' ... 84 | ); 85 | 86 | end 87 | 88 | function gitHubBtnCallback(~,~) 89 | url = 'https://github.com/trnkap/matlab-snippets'; 90 | web(url,'-browser') 91 | end 92 | 93 | function fileExchangeCallback(~,~) 94 | url = 'https://www.mathworks.com/matlabcentral/fileexchange/70524-matlab-snippets'; 95 | web(url,'-browser') 96 | end 97 | 98 | function figureKeyPressFcn(src,keyData) 99 | switch keyData.Key 100 | case 'escape' 101 | close(src); 102 | return 103 | end 104 | end 105 | -------------------------------------------------------------------------------- /dialogs/insertSnippetOptionsDlg.m: -------------------------------------------------------------------------------- 1 | function [opt,closeRequest] = insertSnippetOptionsDlg(opt) 2 | 3 | figSize = [ 400 345+80+10+30+50 ]; 4 | fntSize = 10; 5 | closeRequest = false; 6 | 7 | filterModes = {'MATCH_START','MATCH_ANYWHERE'}; 8 | previewModes = {'RAW','PARSED','EMPHASIZE_PLACEHOLDERS'}; 9 | 10 | screenSize = get(0, 'ScreenSize'); 11 | h.Fig = figure( ... 12 | 'WindowStyle', 'modal', ... 13 | 'Position', [ 0.5*screenSize(3:4)-0.5*figSize figSize ], ... 14 | 'DockControls', 'off', ... 15 | 'MenuBar', 'none', ... 16 | 'NumberTitle', 'off', ... 17 | 'Name', 'Options'); 18 | 19 | % --------------------------------------------------- 20 | 21 | jsonFileNames = opt.jsonFileNames; 22 | isJsonFileEnabled = opt.isJsonFileEnabled; 23 | 24 | hPanelSnippets = uipanel( ... 25 | h.Fig, ... 26 | 'Title','Snippets', ... 27 | 'Units','pixels', ... 28 | 'FontSize', fntSize, ... 29 | 'Position',[15 235+30 370 180+10+50] ); 30 | 31 | uicontrol( ... 32 | 'Parent',hPanelSnippets, ... 33 | 'Style','text', ... 34 | 'String','Definition files (double-click to enable/disable):', ... 35 | 'HorizontalAlignment','left', ... 36 | 'FontSize', fntSize, ... 37 | 'Position', [15 55+80+10+50 340 20] ); 38 | h.fileNameListBox = uicontrol( ... 39 | 'Parent',hPanelSnippets, ... 40 | 'Style','list', ... 41 | 'String',jsonFileNames2HTML(jsonFileNames,isJsonFileEnabled), ... 42 | 'HorizontalAlignment','left', ... 43 | 'FontSize', fntSize, ... 44 | 'Position', [15 32+10 340-45 25+80+50], ... 45 | 'Callback', @fileNameListBoxCallback ); 46 | h.addFileBtn = uicontrol( ... 47 | 'Parent',hPanelSnippets, ... 48 | 'Style', 'pushbutton', ... 49 | 'String', '+', ... 50 | 'Position', [15+340-35 32+80+10+50 30 25], ... 51 | 'Tooltip', 'Add snippet definition file.', ... 52 | 'FontSize', 20, ... 53 | 'Callback', @addFileBtnCallback ... 54 | ); 55 | h.removeFileBtn = uicontrol( ... 56 | 'Parent',hPanelSnippets, ... 57 | 'Style', 'pushbutton', ... 58 | 'String', '-', ... 59 | 'Position', [15+340-35 32+50+10+50 30 25], ... 60 | 'Tooltip', 'Remove selected snippet definition file.', ... 61 | 'FontSize', 20, ... 62 | 'Callback', @removeFileBtnCallback ... 63 | ); 64 | h.editFileBtn = uicontrol( ... 65 | 'Parent',hPanelSnippets, ... 66 | 'Style', 'pushbutton', ... 67 | 'Position', [15+340-35 32+20+10+50 30 25], ... 68 | 'Tooltip', 'Edit selected snippet definition file in the Matlab editor.', ... 69 | 'FontSize', fntSize, ... 70 | 'Callback', @editBtnCallback ... 71 | ); 72 | 73 | h.linkBtn = uicontrol( ... 74 | 'Parent',hPanelSnippets, ... 75 | 'Style','pushbutton', ... 76 | 'String','View Snippet Syntax', ... 77 | 'TooltipString','Opens an external web browser with a link to the Visual Studio Code documentation.', ... 78 | 'HorizontalAlignment','left', ... 79 | 'FontSize', fntSize, ... 80 | 'Position', [15 15 340-45 22], ... 81 | 'Callback',@linkBtnCallback ... 82 | ); 83 | 84 | img = imread('edit_16_16.png'); 85 | img = replaceWhiteColor(img,250,255*0.95*h.editFileBtn.BackgroundColor); 86 | h.editFileBtn.CData = img; 87 | 88 | 89 | % --------------------------------------------------- 90 | 91 | hght = 20; 92 | wdth = 340; 93 | margin = 15; 94 | offset = 30; 95 | bottom = 4*offset + margin; 96 | 97 | hPanelOptions = uipanel( ... 98 | h.Fig, ... 99 | 'Title','Options', ... 100 | 'Units','pixels', ... 101 | 'FontSize', fntSize, ... 102 | 'Position',[15 70 wdth+2*margin 5*offset+2*margin] ); 103 | 104 | uicontrol( ... 105 | 'Parent',hPanelOptions, ... 106 | 'Style','text', ... 107 | 'String','Prefix filter mode', ... 108 | 'HorizontalAlignment','left', ... 109 | 'FontSize', fntSize, ... 110 | 'Position', [margin bottom-3 0.4*wdth hght] ); 111 | h.filterMode = uicontrol( ... 112 | 'Parent',hPanelOptions, ... 113 | 'Style','popupmenu', ... 114 | 'String',{'Match beginning','Match anywhere'}, ... 115 | 'Value',find(strcmp(filterModes,opt.filterMode),1), ... 116 | 'HorizontalAlignment','left', ... 117 | 'FontSize', fntSize, ... 118 | 'Position', [margin+0.4*wdth bottom 0.6*wdth hght] ); 119 | bottom = bottom - offset; 120 | 121 | uicontrol( ... 122 | 'Parent',hPanelOptions, ... 123 | 'Style','text', ... 124 | 'String','Snippet preview mode', ... 125 | 'HorizontalAlignment','left', ... 126 | 'FontSize', fntSize, ... 127 | 'Position', [margin bottom-3 0.4*wdth hght] ); 128 | h.previewMode = uicontrol( ... 129 | 'Parent',hPanelOptions, ... 130 | 'Style','popupmenu', ... 131 | 'String',{'Raw','Parsed','Emphasize placeholders'}, ... 132 | 'Value',find(strcmp(previewModes,opt.previewMode),1), ... 133 | 'HorizontalAlignment','left', ... 134 | 'FontSize', fntSize, ... 135 | 'Position', [margin+0.4*wdth bottom 0.6*wdth hght] ); 136 | bottom = bottom - offset; 137 | 138 | h.keepWindowLoaded = uicontrol( ... 139 | 'Parent',hPanelOptions, ... 140 | 'Style','checkbox', ... 141 | 'String','Keep window loaded to speed-up opening', ... 142 | 'Value', opt.keepWindowLoaded, ... 143 | 'HorizontalAlignment','left', ... 144 | 'FontSize', fntSize, ... 145 | 'Position', [margin bottom wdth hght] ); 146 | bottom = bottom - offset; 147 | 148 | h.filterSnippetsIfTextSelected = uicontrol( ... 149 | 'Parent',hPanelOptions, ... 150 | 'Style','checkbox', ... 151 | 'String','Show snippets with selected text only if text selected', ... 152 | 'TooltipString','Show snippets using the selected text variable only if some text was selected in the active editor. Hides all other snippets in such a case.', ... 153 | 'Value', opt.filterSnippetsIfTextSelected, ... 154 | 'HorizontalAlignment','left', ... 155 | 'FontSize', fntSize, ... 156 | 'Position', [margin bottom wdth hght] ); 157 | bottom = bottom - offset; 158 | 159 | h.deletePartiallyMatchingWordAtCaret = uicontrol( ... 160 | 'Parent',hPanelOptions, ... 161 | 'Style','checkbox', ... 162 | 'String','Delete partial word match at the editor caret', ... 163 | 'TooltipString','Inserting a snippet deletes the word at the editor caret if it matches with the snippet prefix or if it matches with the leading characters.',... 164 | 'Value', opt.deletePartiallyMatchingWordAtCaret, ... 165 | 'HorizontalAlignment','left', ... 166 | 'FontSize', fntSize, ... 167 | 'Position', [margin bottom wdth hght] ); 168 | 169 | 170 | 171 | uicontrol(... 172 | 'Style', 'pushbutton', ... 173 | 'Position', [85 20 100 30], ... 174 | 'String', 'OK', ... 175 | 'FontSize', fntSize, ... 176 | 'Callback', @okBtnCallback ... 177 | ); 178 | 179 | uicontrol(... 180 | 'Style', 'pushbutton', ... 181 | 'Position', [210 20 100 30], ... 182 | 'String', 'Cancel', ... 183 | 'FontSize', fntSize, ... 184 | 'Callback', @cancelBtnCallback ... 185 | ); 186 | 187 | uiwait(h.Fig); % block execution until the figure is closed 188 | 189 | 190 | function okBtnCallback(~,~) 191 | if isempty(jsonFileNames) 192 | warndlg('At least one definition file must be in the list.', ... 193 | 'MATLAB Snippets Configuration'); 194 | return 195 | end 196 | if all(~isJsonFileEnabled) 197 | warndlg('At least one definition file must be enabled.', ... 198 | 'MATLAB Snippets Configuration'); 199 | return 200 | end 201 | opt.jsonFileNames = jsonFileNames; 202 | opt.isJsonFileEnabled = isJsonFileEnabled; 203 | opt.filterMode = filterModes{h.filterMode.Value}; 204 | opt.previewMode = previewModes{h.previewMode.Value}; 205 | opt.keepWindowLoaded = (h.keepWindowLoaded.Value==1); 206 | opt.filterSnippetsIfTextSelected = (h.filterSnippetsIfTextSelected.Value==1); 207 | opt.deletePartiallyMatchingWordAtCaret = (h.deletePartiallyMatchingWordAtCaret.Value==1); 208 | close(h.Fig); 209 | end 210 | 211 | 212 | function cancelBtnCallback(~,~) 213 | close(h.Fig); 214 | end 215 | 216 | 217 | function editBtnCallback(~,~) 218 | fullFileName = getFullFileName(true); 219 | if ~isempty(fullFileName) 220 | close(h.Fig); 221 | matlab.desktop.editor.openDocument(fullFileName); 222 | closeRequest = true; 223 | end 224 | end 225 | 226 | 227 | function addFileBtnCallback(~,~) 228 | fullFileName = getFullFileName(); 229 | if isempty(fullFileName) 230 | [file,path] = uigetfile('*.json','Select file with snippets definition'); 231 | else 232 | [file,path] = uigetfile(fullFileName,'Select file with snippets definition'); 233 | end 234 | if ~isequal(file,0) 235 | fullFileName = [path file]; 236 | fullFileName_ = which(file); 237 | if strcmp(fullFileName,fullFileName_) 238 | % --- selected file on the Matlab search path 239 | fileName = file; 240 | else 241 | fileName = fullFileName; 242 | end 243 | % --- add to the list and sort 244 | jsonFileNames{end+1} = fileName; 245 | isJsonFileEnabled(end+1) = true; 246 | % --- 247 | [jsonFileNames,ind] = sort(jsonFileNames); 248 | isJsonFileEnabled = isJsonFileEnabled(ind); 249 | % --- 250 | h.fileNameListBox.String = ... 251 | jsonFileNames2HTML(jsonFileNames,isJsonFileEnabled); 252 | end 253 | end 254 | 255 | 256 | function removeFileBtnCallback(~,~) 257 | if ~isempty(jsonFileNames) 258 | ilist = h.fileNameListBox.Value; 259 | h.fileNameListBox.Value = min(length(jsonFileNames)-1,ilist); 260 | % --- 261 | jsonFileNames(ilist) = []; 262 | isJsonFileEnabled(ilist) = []; 263 | % --- 264 | h.fileNameListBox.String = ... 265 | jsonFileNames2HTML(jsonFileNames,isJsonFileEnabled); 266 | end 267 | end 268 | 269 | 270 | function fullFileName = getFullFileName(errorEnabled) 271 | if nargin<1 272 | errorEnabled = false; 273 | end 274 | if isempty(jsonFileNames) 275 | fullFileName = ''; 276 | else 277 | ilist = h.fileNameListBox.Value; 278 | fileName = jsonFileNames{ilist}; 279 | [pathstr,~,~] = fileparts(fileName); 280 | if isempty(pathstr) 281 | fullFileName = which(fileName); 282 | if errorEnabled && isempty(fullFileName) 283 | error(['Cannot find "' fileName '" on the Matlab search path.']); 284 | end 285 | else 286 | fullFileName = fileName; 287 | end 288 | end 289 | end 290 | 291 | 292 | function linkBtnCallback(~,~) 293 | web('https://code.visualstudio.com/docs/editor/userdefinedsnippets#_snippet-syntax','-browser'); 294 | end 295 | 296 | 297 | function fileNameListBoxCallback(~,~,~) 298 | if strcmp(get(h.Fig,'selectiontype'),'open') 299 | % list double-click 300 | ilist = h.fileNameListBox.Value; 301 | isJsonFileEnabled(ilist) = ~isJsonFileEnabled(ilist); 302 | jsonFileNamesHTML = jsonFileNames2HTML(jsonFileNames,isJsonFileEnabled); 303 | h.fileNameListBox.String{ilist} = ... 304 | jsonFileNamesHTML{ilist}; 305 | end 306 | end 307 | 308 | 309 | end 310 | 311 | 312 | function img = replaceWhiteColor(img,thr,replacementCol) 313 | for i = 1 : size(img,1) 314 | for j = 1 : size(img,2) 315 | if all(squeeze(img(i,j,:))>=thr*ones(3,1)) 316 | img(i,j,:) = replacementCol; 317 | end 318 | end 319 | end 320 | end 321 | 322 | 323 | function jsonFileNamesHTML = jsonFileNames2HTML(jsonFileNames,isJsonFileEnabled) 324 | jsonFileNamesHTML = jsonFileNames; 325 | for ifile = 1 : length(jsonFileNames) 326 | if isJsonFileEnabled(ifile) 327 | prefix = ''; 328 | postfix = ''; 329 | else 330 | prefix = ''; 331 | postfix = ''; 332 | end 333 | jsonFileNamesHTML{ifile} = ... 334 | [ prefix jsonFileNames{ifile} postfix ]; 335 | end 336 | end -------------------------------------------------------------------------------- /favoriteCallback.txt: -------------------------------------------------------------------------------- 1 | % MATLAB Snippet APP - favorite command callback for a manual installation 2 | % Intended to be copy & pasted and not to be called directly (intentional txt extension). 3 | 4 | if exist('insertSnippet','file') 5 | insertSnippet(); 6 | else 7 | appName = 'MATLAB Snippets'; 8 | id = []; 9 | appinfo = matlab.apputil.getInstalledAppInfo; 10 | if ~isempty(appinfo) 11 | ind = find(strcmp({appinfo.name},appName)); 12 | if length(ind)==1 13 | id = appinfo(ind).id; 14 | else 15 | % --- multiple matches - return the last ID from a sorted list 16 | ID = {appinfo(ind).id}; 17 | ID = sort(ID); 18 | id = ID(end); 19 | end 20 | end 21 | if isempty(id) 22 | f = warndlg([ 'Cannot find the App named "' appName '". Please (re)install it.' ]); 23 | else 24 | matlab.apputil.run(id); 25 | end 26 | end -------------------------------------------------------------------------------- /graphics/about_16_16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/graphics/about_16_16.png -------------------------------------------------------------------------------- /graphics/configure_16_16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/graphics/configure_16_16.png -------------------------------------------------------------------------------- /graphics/edit_16_16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/graphics/edit_16_16.png -------------------------------------------------------------------------------- /graphics/help_16_16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/graphics/help_16_16.png -------------------------------------------------------------------------------- /graphics/insertSnippet_16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/graphics/insertSnippet_16.png -------------------------------------------------------------------------------- /graphics/insertSnippet_24.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/graphics/insertSnippet_24.png -------------------------------------------------------------------------------- /graphics/insertSnippet_48.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/graphics/insertSnippet_48.png -------------------------------------------------------------------------------- /graphics/open_16_16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/graphics/open_16_16.png -------------------------------------------------------------------------------- /graphics/screenshot01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/graphics/screenshot01.png -------------------------------------------------------------------------------- /html/02_simple_tabstop.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/html/02_simple_tabstop.gif -------------------------------------------------------------------------------- /html/03_simple_tabstop_prefix.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/html/03_simple_tabstop_prefix.gif -------------------------------------------------------------------------------- /html/04_complex_tabstops.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/html/04_complex_tabstops.gif -------------------------------------------------------------------------------- /html/05_plain_snippet.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/html/05_plain_snippet.gif -------------------------------------------------------------------------------- /html/06_block_operations.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/html/06_block_operations.gif -------------------------------------------------------------------------------- /html/add_to_favorites.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/html/add_to_favorites.png -------------------------------------------------------------------------------- /html/insertSnippet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/html/insertSnippet.png -------------------------------------------------------------------------------- /html/matlabSnippets.mlx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/html/matlabSnippets.mlx -------------------------------------------------------------------------------- /html/options.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/html/options.png -------------------------------------------------------------------------------- /html/previewModes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/html/previewModes.png -------------------------------------------------------------------------------- /html/quick_bar.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/html/quick_bar.png -------------------------------------------------------------------------------- /insertSnippet.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/insertSnippet.m -------------------------------------------------------------------------------- /insertSnippetOptions.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/insertSnippetOptions.mat -------------------------------------------------------------------------------- /jsonlab-1.5/AUTHORS.txt: -------------------------------------------------------------------------------- 1 | The author of "jsonlab" toolbox is Qianqian Fang. Qianqian 2 | is currently an Assistant Professor in the Department of Bioengineering, 3 | Northeastern University. 4 | 5 | Address: Qianqian Fang 6 | Department of Bioengineering 7 | Northeastern University 8 | 212A Lake Hall 9 | 360 Huntington Ave, Boston, MA 02115, USA 10 | Office: 503 Holmes Hall 11 | Phone[O]: 617-373-3829 12 | URL: http://fanglab.org 13 | Email: and 14 | 15 | 16 | The script loadjson.m was built upon previous works by 17 | 18 | - Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 19 | date: 2009/11/02 20 | - François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 21 | date: 2009/03/22 22 | - Joel Feenstra: http://www.mathworks.com/matlabcentral/fileexchange/20565 23 | date: 2008/07/03 24 | 25 | 26 | This toolbox contains patches submitted by the following contributors: 27 | 28 | - Blake Johnson 29 | part of revision 341 30 | 31 | - Niclas Borlin 32 | various fixes in revision 394, including 33 | - loadjson crashes for all-zero sparse matrix. 34 | - loadjson crashes for empty sparse matrix. 35 | - Non-zero size of 0-by-N and N-by-0 empty matrices is lost after savejson/loadjson. 36 | - loadjson crashes for sparse real column vector. 37 | - loadjson crashes for sparse complex column vector. 38 | - Data is corrupted by savejson for sparse real row vector. 39 | - savejson crashes for sparse complex row vector. 40 | 41 | - Yul Kang 42 | patches for svn revision 415. 43 | - savejson saves an empty cell array as [] instead of null 44 | - loadjson differentiates an empty struct from an empty array 45 | 46 | - Mykhailo Bratukha 47 | (Pull#14) Bug fix: File path is wrongly inerpreted as JSON string 48 | 49 | - Insik Kim 50 | (Pull#12) Bug fix: Resolving bug that cell type is converted to json with transposed data 51 | 52 | - Sertan Senturk 53 | (Pull#10,#11) Feature: Added matlab object saving to savejson and saveubjson 54 | -------------------------------------------------------------------------------- /jsonlab-1.5/ChangeLog.txt: -------------------------------------------------------------------------------- 1 | ============================================================================ 2 | 3 | JSONlab - a toolbox to encode/decode JSON/UBJSON files in MATLAB/Octave 4 | 5 | ---------------------------------------------------------------------------- 6 | 7 | JSONlab ChangeLog (key features marked by *): 8 | 9 | == JSONlab 1.5 (codename: Nominus - alpha), FangQ neu.edu> == 10 | 11 | 2017/01/02 *use Big-endian format to store floating points (d/D) in saveubjson (Issue #25) 12 | 2017/01/02 *speedup parsing large unstructured data by 2x (Issue #9) 13 | 2017/01/01 make parsing independent of white space (Issue #30) 14 | 2016/08/27 allow to parse array of homogeneous elements (Issue 5) 15 | 2016/08/22 permit [] inside file names in savejson 16 | 2016/01/06 fix a bug that prevents saving to a file in savejson 17 | 18 | 19 | == JSONlab 1.2 (codename: Optimus - Update 2), FangQ neu.edu> == 20 | 21 | 2015/12/16 replacing string concatenation by str cells to gain 2x speed in savejson (Issue#17) 22 | 2015/12/11 fix FileName option case bug (SVN rev#495) 23 | 2015/12/11 add SingletCell option, add SingletArray to replace NoRowBracket (Issue#15,#8) 24 | 2015/11/10 fix bug for inerpreting file names as JSON string - by Mykhailo Bratukha (Pull#14) 25 | 2015/10/16 fix bug for cell with transposed data - by Insik Kim (Pull#12) 26 | 2015/09/25 support exporting matlab object to JSON - by Sertan Senturk (Pull#10, #11) 27 | 28 | == JSONlab 1.1 (codename: Optimus - Update 1), FangQ neu.edu> == 29 | 30 | 2015/05/05 *massively accelerating loadjson for parsing large collection of unstructured small objects 31 | 2015/05/05 force array bracket in 1x1 struct to maintain depth (Issue#1) 32 | 2015/05/05 parse logicals in loadjson 33 | 2015/05/05 make options case insensitive 34 | 2015/05/01 reading unicode encoded json files (thanks to Sertan Senturk,Issue#3) 35 | 2015/04/30 allow \uXXXX to represent a unicode in a string (Issue#2) 36 | 2015/03/30 save a 0x0 solid real empty array as null and handel empty struct array 37 | 2015/03/30 properly handle escape characters in a string 38 | 2015/01/24 *implement the UBJSON Draft12 new name format 39 | 2015/01/13 correct cell array indentation inconsistency 40 | 41 | == JSONlab 1.0 (codename: Optimus - Final), FangQ neu.edu> == 42 | 43 | 2015/01/02 polish help info for all major functions, update examples, finalize 1.0 44 | 2014/12/19 fix a bug to strictly respect NoRowBracket in savejson 45 | 46 | == JSONlab 1.0.0-RC2 (codename: Optimus - RC2), FangQ neu.edu> == 47 | 48 | 2014/11/22 show progress bar in loadjson ('ShowProgress') 49 | 2014/11/17 *add Compact option in savejson to output compact JSON format ('Compact') 50 | 2014/11/17 add FastArrayParser in loadjson to specify fast parser applicable levels 51 | 2014/09/18 *start official github mirror: https://github.com/fangq/jsonlab 52 | 53 | == JSONlab 1.0.0-RC1 (codename: Optimus - RC1), FangQ neu.edu> == 54 | 55 | 2014/09/17 fix several compatibility issues when running on octave versions 3.2-3.8 56 | 2014/09/17 *support 2D cell and struct arrays in both savejson and saveubjson 57 | 2014/08/04 escape special characters in a JSON string 58 | 2014/02/16 fix a bug when saving ubjson files 59 | 60 | == JSONlab 0.9.9 (codename: Optimus - beta), FangQ neu.edu> == 61 | 62 | 2014/01/22 use binary read and write in saveubjson and loadubjson 63 | 64 | == JSONlab 0.9.8-1 (codename: Optimus - alpha update 1), FangQ neu.edu> == 65 | 66 | 2013/10/07 better round-trip conservation for empty arrays and structs (patch submitted by Yul Kang) 67 | 68 | == JSONlab 0.9.8 (codename: Optimus - alpha), FangQ neu.edu> == 69 | 2013/08/23 *universal Binary JSON (UBJSON) support, including both saveubjson and loadubjson 70 | 71 | == JSONlab 0.9.1 (codename: Rodimus, update 1), FangQ neu.edu> == 72 | 2012/12/18 *handling of various empty and sparse matrices (fixes submitted by Niclas Borlin) 73 | 74 | == JSONlab 0.9.0 (codename: Rodimus), FangQ neu.edu> == 75 | 76 | 2012/06/17 *new format for an invalid leading char, unpacking hex code in savejson 77 | 2012/06/01 support JSONP in savejson 78 | 2012/05/25 fix the empty cell bug (reported by Cyril Davin) 79 | 2012/04/05 savejson can save to a file (suggested by Patrick Rapin) 80 | 81 | == JSONlab 0.8.1 (codename: Sentiel, Update 1), FangQ neu.edu> == 82 | 83 | 2012/02/28 loadjson quotation mark escape bug, see http://bit.ly/yyk1nS 84 | 2012/01/25 patch to handle root-less objects, contributed by Blake Johnson 85 | 86 | == JSONlab 0.8.0 (codename: Sentiel), FangQ neu.edu> == 87 | 88 | 2012/01/13 *speed up loadjson by 20 fold when parsing large data arrays in matlab 89 | 2012/01/11 remove row bracket if an array has 1 element, suggested by Mykel Kochenderfer 90 | 2011/12/22 *accept sequence of 'param',value input in savejson and loadjson 91 | 2011/11/18 fix struct array bug reported by Mykel Kochenderfer 92 | 93 | == JSONlab 0.5.1 (codename: Nexus Update 1), FangQ neu.edu> == 94 | 95 | 2011/10/21 fix a bug in loadjson, previous code does not use any of the acceleration 96 | 2011/10/20 loadjson supports JSON collections - concatenated JSON objects 97 | 98 | == JSONlab 0.5.0 (codename: Nexus), FangQ neu.edu> == 99 | 100 | 2011/10/16 package and release jsonlab 0.5.0 101 | 2011/10/15 *add json demo and regression test, support cpx numbers, fix double quote bug 102 | 2011/10/11 *speed up readjson dramatically, interpret _Array* tags, show data in root level 103 | 2011/10/10 create jsonlab project, start jsonlab website, add online documentation 104 | 2011/10/07 *speed up savejson by 25x using sprintf instead of mat2str, add options support 105 | 2011/10/06 *savejson works for structs, cells and arrays 106 | 2011/09/09 derive loadjson from JSON parser from MATLAB Central, draft savejson.m 107 | -------------------------------------------------------------------------------- /jsonlab-1.5/LICENSE_BSD.txt: -------------------------------------------------------------------------------- 1 | Copyright 2011-2017 Qianqian Fang neu.edu>. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without modification, are 4 | permitted provided that the following conditions are met: 5 | 6 | 1. Redistributions of source code must retain the above copyright notice, this list of 7 | conditions and the following disclaimer. 8 | 9 | 2. Redistributions in binary form must reproduce the above copyright notice, this list 10 | of conditions and the following disclaimer in the documentation and/or other materials 11 | provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY EXPRESS OR IMPLIED 14 | WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 15 | FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 16 | OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 17 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 18 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 20 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 21 | ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 22 | 23 | The views and conclusions contained in the software and documentation are those of the 24 | authors and should not be interpreted as representing official policies, either expressed 25 | or implied, of the copyright holders. 26 | -------------------------------------------------------------------------------- /jsonlab-1.5/README.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/jsonlab-1.5/README.txt -------------------------------------------------------------------------------- /jsonlab-1.5/examples/demo_jsonlab_basic.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % Demonstration of Basic Utilities of JSONlab 3 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 4 | 5 | rngstate = rand ('state'); 6 | randseed=hex2dec('623F9A9E'); 7 | clear data2json json2data 8 | 9 | fprintf(1,'\n%%=================================================\n') 10 | fprintf(1,'%% a simple scalar value \n') 11 | fprintf(1,'%%=================================================\n\n') 12 | 13 | data2json=pi 14 | savejson('',data2json) 15 | json2data=loadjson(ans) 16 | 17 | fprintf(1,'\n%%=================================================\n') 18 | fprintf(1,'%% a complex number\n') 19 | fprintf(1,'%%=================================================\n\n') 20 | 21 | clear i; 22 | data2json=1+2*i 23 | savejson('',data2json) 24 | json2data=loadjson(ans) 25 | 26 | fprintf(1,'\n%%=================================================\n') 27 | fprintf(1,'%% a complex matrix\n') 28 | fprintf(1,'%%=================================================\n\n') 29 | 30 | data2json=magic(6); 31 | data2json=data2json(:,1:3)+data2json(:,4:6)*i 32 | savejson('',data2json) 33 | json2data=loadjson(ans) 34 | 35 | fprintf(1,'\n%%=================================================\n') 36 | fprintf(1,'%% MATLAB special constants\n') 37 | fprintf(1,'%%=================================================\n\n') 38 | 39 | data2json=[NaN Inf -Inf] 40 | savejson('specials',data2json) 41 | json2data=loadjson(ans) 42 | 43 | fprintf(1,'\n%%=================================================\n') 44 | fprintf(1,'%% a real sparse matrix\n') 45 | fprintf(1,'%%=================================================\n\n') 46 | 47 | data2json=sprand(10,10,0.1) 48 | savejson('sparse',data2json) 49 | json2data=loadjson(ans) 50 | 51 | fprintf(1,'\n%%=================================================\n') 52 | fprintf(1,'%% a complex sparse matrix\n') 53 | fprintf(1,'%%=================================================\n\n') 54 | 55 | data2json=data2json-data2json*i 56 | savejson('complex_sparse',data2json) 57 | json2data=loadjson(ans) 58 | 59 | fprintf(1,'\n%%=================================================\n') 60 | fprintf(1,'%% an all-zero sparse matrix\n') 61 | fprintf(1,'%%=================================================\n\n') 62 | 63 | data2json=sparse(2,3); 64 | savejson('all_zero_sparse',data2json) 65 | json2data=loadjson(ans) 66 | 67 | fprintf(1,'\n%%=================================================\n') 68 | fprintf(1,'%% an empty sparse matrix\n') 69 | fprintf(1,'%%=================================================\n\n') 70 | 71 | data2json=sparse([]); 72 | savejson('empty_sparse',data2json) 73 | json2data=loadjson(ans) 74 | 75 | fprintf(1,'\n%%=================================================\n') 76 | fprintf(1,'%% an empty 0-by-0 real matrix\n') 77 | fprintf(1,'%%=================================================\n\n') 78 | 79 | data2json=[]; 80 | savejson('empty_0by0_real',data2json) 81 | json2data=loadjson(ans) 82 | 83 | fprintf(1,'\n%%=================================================\n') 84 | fprintf(1,'%% an empty 0-by-3 real matrix\n') 85 | fprintf(1,'%%=================================================\n\n') 86 | 87 | data2json=zeros(0,3); 88 | savejson('empty_0by3_real',data2json) 89 | json2data=loadjson(ans) 90 | 91 | fprintf(1,'\n%%=================================================\n') 92 | fprintf(1,'%% a sparse real column vector\n') 93 | fprintf(1,'%%=================================================\n\n') 94 | 95 | data2json=sparse([0,3,0,1,4]'); 96 | savejson('sparse_column_vector',data2json) 97 | json2data=loadjson(ans) 98 | 99 | fprintf(1,'\n%%=================================================\n') 100 | fprintf(1,'%% a sparse complex column vector\n') 101 | fprintf(1,'%%=================================================\n\n') 102 | 103 | data2json=data2json-1i*data2json; 104 | savejson('complex_sparse_column_vector',data2json) 105 | json2data=loadjson(ans) 106 | 107 | fprintf(1,'\n%%=================================================\n') 108 | fprintf(1,'%% a sparse real row vector\n') 109 | fprintf(1,'%%=================================================\n\n') 110 | 111 | data2json=sparse([0,3,0,1,4]); 112 | savejson('sparse_row_vector',data2json) 113 | json2data=loadjson(ans) 114 | 115 | fprintf(1,'\n%%=================================================\n') 116 | fprintf(1,'%% a sparse complex row vector\n') 117 | fprintf(1,'%%=================================================\n\n') 118 | 119 | data2json=data2json-1i*data2json; 120 | savejson('complex_sparse_row_vector',data2json) 121 | json2data=loadjson(ans) 122 | 123 | fprintf(1,'\n%%=================================================\n') 124 | fprintf(1,'%% a structure\n') 125 | fprintf(1,'%%=================================================\n\n') 126 | 127 | data2json=struct('name','Think Different','year',1997,'magic',magic(3),... 128 | 'misfits',[Inf,NaN],'embedded',struct('left',true,'right',false)) 129 | savejson('astruct',data2json,struct('ParseLogical',1)) 130 | json2data=loadjson(ans) 131 | class(json2data.astruct.embedded.left) 132 | 133 | fprintf(1,'\n%%=================================================\n') 134 | fprintf(1,'%% a structure array\n') 135 | fprintf(1,'%%=================================================\n\n') 136 | 137 | data2json=struct('name','Nexus Prime','rank',9); 138 | data2json(2)=struct('name','Sentinel Prime','rank',9); 139 | data2json(3)=struct('name','Optimus Prime','rank',9); 140 | savejson('Supreme Commander',data2json) 141 | json2data=loadjson(ans) 142 | 143 | fprintf(1,'\n%%=================================================\n') 144 | fprintf(1,'%% a cell array\n') 145 | fprintf(1,'%%=================================================\n\n') 146 | 147 | data2json=cell(3,1); 148 | data2json{1}=struct('buzz',1.1,'rex',1.2,'bo',1.3,'hamm',2.0,'slink',2.1,'potato',2.2,... 149 | 'woody',3.0,'sarge',3.1,'etch',4.0,'lenny',5.0,'squeeze',6.0,'wheezy',7.0); 150 | data2json{2}=struct('Ubuntu',['Kubuntu';'Xubuntu';'Lubuntu']); 151 | data2json{3}=[10.04,10.10,11.04,11.10] 152 | savejson('debian',data2json,struct('FloatFormat','%.2f')) 153 | json2data=loadjson(ans) 154 | 155 | fprintf(1,'\n%%=================================================\n') 156 | fprintf(1,'%% invalid field-name handling\n') 157 | fprintf(1,'%%=================================================\n\n') 158 | 159 | json2data=loadjson('{"ValidName":1, "_InvalidName":2, ":Field:":3, "项目":"绝密"}') 160 | 161 | fprintf(1,'\n%%=================================================\n') 162 | fprintf(1,'%% a 2D cell array\n') 163 | fprintf(1,'%%=================================================\n\n') 164 | 165 | data2json={{1,{2,3}},{4,5},{6};{7},{8,9},{10}}; 166 | savejson('data2json',data2json) 167 | json2data=loadjson(ans) % only savejson works for cell arrays, loadjson has issues 168 | 169 | fprintf(1,'\n%%=================================================\n') 170 | fprintf(1,'%% a 2D struct array\n') 171 | fprintf(1,'%%=================================================\n\n') 172 | 173 | data2json=repmat(struct('idx',0,'data','structs'),[2,3]) 174 | for i=1:6 175 | data2json(i).idx=i; 176 | end 177 | savejson('data2json',data2json) 178 | json2data=loadjson(ans) 179 | 180 | rand ('state',rngstate); 181 | 182 | -------------------------------------------------------------------------------- /jsonlab-1.5/examples/demo_ubjson_basic.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % Demonstration of Basic Utilities of JSONlab 3 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 4 | 5 | rngstate = rand ('state'); 6 | randseed=hex2dec('623F9A9E'); 7 | clear data2json json2data 8 | 9 | fprintf(1,'\n%%=================================================\n') 10 | fprintf(1,'%% a simple scalar value \n') 11 | fprintf(1,'%%=================================================\n\n') 12 | 13 | data2json=pi 14 | saveubjson('',data2json) 15 | json2data=loadubjson(ans) 16 | 17 | fprintf(1,'\n%%=================================================\n') 18 | fprintf(1,'%% a complex number\n') 19 | fprintf(1,'%%=================================================\n\n') 20 | 21 | clear i; 22 | data2json=1+2*i 23 | saveubjson('',data2json) 24 | json2data=loadubjson(ans) 25 | 26 | fprintf(1,'\n%%=================================================\n') 27 | fprintf(1,'%% a complex matrix\n') 28 | fprintf(1,'%%=================================================\n\n') 29 | 30 | data2json=magic(6); 31 | data2json=data2json(:,1:3)+data2json(:,4:6)*i 32 | saveubjson('',data2json) 33 | json2data=loadubjson(ans) 34 | 35 | fprintf(1,'\n%%=================================================\n') 36 | fprintf(1,'%% MATLAB special constants\n') 37 | fprintf(1,'%%=================================================\n\n') 38 | 39 | data2json=[NaN Inf -Inf] 40 | saveubjson('specials',data2json) 41 | json2data=loadubjson(ans) 42 | 43 | fprintf(1,'\n%%=================================================\n') 44 | fprintf(1,'%% a real sparse matrix\n') 45 | fprintf(1,'%%=================================================\n\n') 46 | 47 | data2json=sprand(10,10,0.1) 48 | saveubjson('sparse',data2json) 49 | json2data=loadubjson(ans) 50 | 51 | fprintf(1,'\n%%=================================================\n') 52 | fprintf(1,'%% a complex sparse matrix\n') 53 | fprintf(1,'%%=================================================\n\n') 54 | 55 | data2json=data2json-data2json*i 56 | saveubjson('complex_sparse',data2json) 57 | json2data=loadubjson(ans) 58 | 59 | fprintf(1,'\n%%=================================================\n') 60 | fprintf(1,'%% an all-zero sparse matrix\n') 61 | fprintf(1,'%%=================================================\n\n') 62 | 63 | data2json=sparse(2,3); 64 | saveubjson('all_zero_sparse',data2json) 65 | json2data=loadubjson(ans) 66 | 67 | fprintf(1,'\n%%=================================================\n') 68 | fprintf(1,'%% an empty sparse matrix\n') 69 | fprintf(1,'%%=================================================\n\n') 70 | 71 | data2json=sparse([]); 72 | saveubjson('empty_sparse',data2json) 73 | json2data=loadubjson(ans) 74 | 75 | fprintf(1,'\n%%=================================================\n') 76 | fprintf(1,'%% an empty 0-by-0 real matrix\n') 77 | fprintf(1,'%%=================================================\n\n') 78 | 79 | data2json=[]; 80 | saveubjson('empty_0by0_real',data2json) 81 | json2data=loadubjson(ans) 82 | 83 | fprintf(1,'\n%%=================================================\n') 84 | fprintf(1,'%% an empty 0-by-3 real matrix\n') 85 | fprintf(1,'%%=================================================\n\n') 86 | 87 | data2json=zeros(0,3); 88 | saveubjson('empty_0by3_real',data2json) 89 | json2data=loadubjson(ans) 90 | 91 | fprintf(1,'\n%%=================================================\n') 92 | fprintf(1,'%% a sparse real column vector\n') 93 | fprintf(1,'%%=================================================\n\n') 94 | 95 | data2json=sparse([0,3,0,1,4]'); 96 | saveubjson('sparse_column_vector',data2json) 97 | json2data=loadubjson(ans) 98 | 99 | fprintf(1,'\n%%=================================================\n') 100 | fprintf(1,'%% a sparse complex column vector\n') 101 | fprintf(1,'%%=================================================\n\n') 102 | 103 | data2json=data2json-1i*data2json; 104 | saveubjson('complex_sparse_column_vector',data2json) 105 | json2data=loadubjson(ans) 106 | 107 | fprintf(1,'\n%%=================================================\n') 108 | fprintf(1,'%% a sparse real row vector\n') 109 | fprintf(1,'%%=================================================\n\n') 110 | 111 | data2json=sparse([0,3,0,1,4]); 112 | saveubjson('sparse_row_vector',data2json) 113 | json2data=loadubjson(ans) 114 | 115 | fprintf(1,'\n%%=================================================\n') 116 | fprintf(1,'%% a sparse complex row vector\n') 117 | fprintf(1,'%%=================================================\n\n') 118 | 119 | data2json=data2json-1i*data2json; 120 | saveubjson('complex_sparse_row_vector',data2json) 121 | json2data=loadubjson(ans) 122 | 123 | fprintf(1,'\n%%=================================================\n') 124 | fprintf(1,'%% a structure\n') 125 | fprintf(1,'%%=================================================\n\n') 126 | 127 | data2json=struct('name','Think Different','year',1997,'magic',magic(3),... 128 | 'misfits',[Inf,NaN],'embedded',struct('left',true,'right',false)) 129 | saveubjson('astruct',data2json,struct('ParseLogical',1)) 130 | json2data=loadubjson(ans) 131 | 132 | fprintf(1,'\n%%=================================================\n') 133 | fprintf(1,'%% a structure array\n') 134 | fprintf(1,'%%=================================================\n\n') 135 | 136 | data2json=struct('name','Nexus Prime','rank',9); 137 | data2json(2)=struct('name','Sentinel Prime','rank',9); 138 | data2json(3)=struct('name','Optimus Prime','rank',9); 139 | saveubjson('Supreme Commander',data2json) 140 | json2data=loadubjson(ans) 141 | 142 | fprintf(1,'\n%%=================================================\n') 143 | fprintf(1,'%% a cell array\n') 144 | fprintf(1,'%%=================================================\n\n') 145 | 146 | data2json=cell(3,1); 147 | data2json{1}=struct('buzz',1.1,'rex',1.2,'bo',1.3,'hamm',2.0,'slink',2.1,'potato',2.2,... 148 | 'woody',3.0,'sarge',3.1,'etch',4.0,'lenny',5.0,'squeeze',6.0,'wheezy',7.0); 149 | data2json{2}=struct('Ubuntu',['Kubuntu';'Xubuntu';'Lubuntu']); 150 | data2json{3}=[10.04,10.10,11.04,11.10] 151 | saveubjson('debian',data2json,struct('FloatFormat','%.2f')) 152 | json2data=loadubjson(ans) 153 | 154 | fprintf(1,'\n%%=================================================\n') 155 | fprintf(1,'%% invalid field-name handling\n') 156 | fprintf(1,'%%=================================================\n\n') 157 | 158 | json2data=loadubjson(saveubjson('',loadjson('{"ValidName":1, "_InvalidName":2, ":Field:":3, "项目":"绝密"}'))) 159 | 160 | fprintf(1,'\n%%=================================================\n') 161 | fprintf(1,'%% a 2D cell array\n') 162 | fprintf(1,'%%=================================================\n\n') 163 | 164 | data2json={{1,{2,3}},{4,5},{6};{7},{8,9},{10}}; 165 | saveubjson('data2json',data2json) 166 | json2data=loadubjson(ans) % only savejson works for cell arrays, loadjson has issues 167 | 168 | fprintf(1,'\n%%=================================================\n') 169 | fprintf(1,'%% a 2D struct array\n') 170 | fprintf(1,'%%=================================================\n\n') 171 | 172 | data2json=repmat(struct('idx',0,'data','structs'),[2,3]) 173 | for i=1:6 174 | data2json(i).idx=i; 175 | end 176 | saveubjson('data2json',data2json) 177 | json2data=loadubjson(ans) 178 | 179 | rand ('state',rngstate); 180 | 181 | -------------------------------------------------------------------------------- /jsonlab-1.5/examples/example1.json: -------------------------------------------------------------------------------- 1 | { 2 | "firstName": "John", 3 | "lastName": "Smith", 4 | "age": 25, 5 | "address": 6 | { 7 | "streetAddress": "21 2nd Street", 8 | "city": "New York", 9 | "state": "NY", 10 | "postalCode": "10021" 11 | }, 12 | "phoneNumber": 13 | [ 14 | { 15 | "type": "home", 16 | "number": "212 555-1234" 17 | }, 18 | { 19 | "type": "fax", 20 | "number": "646 555-4567" 21 | } 22 | ] 23 | } 24 | -------------------------------------------------------------------------------- /jsonlab-1.5/examples/example2.json: -------------------------------------------------------------------------------- 1 | { 2 | "glossary": { 3 | "title": "example glossary", 4 | "GlossDiv": { 5 | "title": "S", 6 | "GlossList": { 7 | "GlossEntry": { 8 | "ID": "SGML", 9 | "SortAs": "SGML", 10 | "GlossTerm": "Standard Generalized Markup Language", 11 | "Acronym": "SGML", 12 | "Abbrev": "ISO 8879:1986", 13 | "GlossDef": { 14 | "para": "A meta-markup language, used to create markup languages such as DocBook.", 15 | "GlossSeeAlso": ["GML", "XML"] 16 | }, 17 | "GlossSee": "markup" 18 | } 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /jsonlab-1.5/examples/example3.json: -------------------------------------------------------------------------------- 1 | {"menu": { 2 | "id": "file", 3 | "value": "_&File", 4 | "popup": { 5 | "menuitem": [ 6 | {"value": "_&New", "onclick": "CreateNewDoc(\"'\\\"Untitled\\\"'\")"}, 7 | {"value": "_&Open", "onclick": "OpenDoc()"}, 8 | {"value": "_&Close", "onclick": "CloseDoc()"} 9 | ] 10 | } 11 | }} 12 | -------------------------------------------------------------------------------- /jsonlab-1.5/examples/example4.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "sample" : { 4 | "rho" : 1 5 | } 6 | }, 7 | { 8 | "sample" : { 9 | "rho" : 2 10 | } 11 | }, 12 | [ 13 | { 14 | "_ArrayType_" : "double", 15 | "_ArraySize_" : [1,2], 16 | "_ArrayData_" : [1,0] 17 | }, 18 | { 19 | "_ArrayType_" : "double", 20 | "_ArraySize_" : [1,2], 21 | "_ArrayData_" : [1,1] 22 | }, 23 | { 24 | "_ArrayType_" : "double", 25 | "_ArraySize_" : [1,2], 26 | "_ArrayData_" : [1,2] 27 | } 28 | ], 29 | [ 30 | "Paper", 31 | "Scissors", 32 | "Stone" 33 | ], 34 | ["a", "b\\", "c\"","d\\\"","e\"[","f\\\"[","g[\\","h[\\\""] 35 | ] 36 | -------------------------------------------------------------------------------- /jsonlab-1.5/examples/jsonlab_basictest.matlab: -------------------------------------------------------------------------------- 1 | 2 | < M A T L A B (R) > 3 | Copyright 1984-2010 The MathWorks, Inc. 4 | Version 7.11.0.584 (R2010b) 64-bit (glnxa64) 5 | August 16, 2010 6 | 7 | 8 | To get started, type one of these: helpwin, helpdesk, or demo. 9 | For product information, visit www.mathworks.com. 10 | 11 | >> >> >> >> >> >> >> >> >> 12 | %================================================= 13 | >> % a simple scalar value 14 | >> %================================================= 15 | 16 | >> >> 17 | data2json = 18 | 19 | 3.1416 20 | 21 | >> 22 | ans = 23 | 24 | [3.141592654] 25 | 26 | 27 | >> 28 | json2data = 29 | 30 | 3.1416 31 | 32 | >> >> 33 | %================================================= 34 | >> % a complex number 35 | >> %================================================= 36 | 37 | >> >> >> 38 | data2json = 39 | 40 | 1.0000 + 2.0000i 41 | 42 | >> 43 | ans = 44 | 45 | { 46 | "_ArrayType_": "double", 47 | "_ArraySize_": [1,1], 48 | "_ArrayIsComplex_": 1, 49 | "_ArrayData_": [1,2] 50 | } 51 | 52 | 53 | >> 54 | json2data = 55 | 56 | 1.0000 + 2.0000i 57 | 58 | >> >> 59 | %================================================= 60 | >> % a complex matrix 61 | >> %================================================= 62 | 63 | >> >> >> 64 | data2json = 65 | 66 | 35.0000 +26.0000i 1.0000 +19.0000i 6.0000 +24.0000i 67 | 3.0000 +21.0000i 32.0000 +23.0000i 7.0000 +25.0000i 68 | 31.0000 +22.0000i 9.0000 +27.0000i 2.0000 +20.0000i 69 | 8.0000 +17.0000i 28.0000 +10.0000i 33.0000 +15.0000i 70 | 30.0000 +12.0000i 5.0000 +14.0000i 34.0000 +16.0000i 71 | 4.0000 +13.0000i 36.0000 +18.0000i 29.0000 +11.0000i 72 | 73 | >> 74 | ans = 75 | 76 | { 77 | "_ArrayType_": "double", 78 | "_ArraySize_": [6,3], 79 | "_ArrayIsComplex_": 1, 80 | "_ArrayData_": [ 81 | [35,26], 82 | [3,21], 83 | [31,22], 84 | [8,17], 85 | [30,12], 86 | [4,13], 87 | [1,19], 88 | [32,23], 89 | [9,27], 90 | [28,10], 91 | [5,14], 92 | [36,18], 93 | [6,24], 94 | [7,25], 95 | [2,20], 96 | [33,15], 97 | [34,16], 98 | [29,11] 99 | ] 100 | } 101 | 102 | 103 | >> 104 | json2data = 105 | 106 | 35.0000 +26.0000i 1.0000 +19.0000i 6.0000 +24.0000i 107 | 3.0000 +21.0000i 32.0000 +23.0000i 7.0000 +25.0000i 108 | 31.0000 +22.0000i 9.0000 +27.0000i 2.0000 +20.0000i 109 | 8.0000 +17.0000i 28.0000 +10.0000i 33.0000 +15.0000i 110 | 30.0000 +12.0000i 5.0000 +14.0000i 34.0000 +16.0000i 111 | 4.0000 +13.0000i 36.0000 +18.0000i 29.0000 +11.0000i 112 | 113 | >> >> 114 | %================================================= 115 | >> % MATLAB special constants 116 | >> %================================================= 117 | 118 | >> >> 119 | data2json = 120 | 121 | NaN Inf -Inf 122 | 123 | >> 124 | ans = 125 | 126 | { 127 | "specials": ["_NaN_","_Inf_","-_Inf_"] 128 | } 129 | 130 | 131 | >> 132 | json2data = 133 | 134 | specials: [NaN Inf -Inf] 135 | 136 | >> >> 137 | %================================================= 138 | >> % a real sparse matrix 139 | >> %================================================= 140 | 141 | >> >> 142 | data2json = 143 | 144 | (1,2) 0.6557 145 | (9,2) 0.7577 146 | (3,5) 0.8491 147 | (10,5) 0.7431 148 | (10,8) 0.3922 149 | (7,9) 0.6787 150 | (2,10) 0.0357 151 | (6,10) 0.9340 152 | (10,10) 0.6555 153 | 154 | >> 155 | ans = 156 | 157 | { 158 | "sparse": { 159 | "_ArrayType_": "double", 160 | "_ArraySize_": [10,10], 161 | "_ArrayIsSparse_": 1, 162 | "_ArrayData_": [ 163 | [1,2,0.6557406992], 164 | [9,2,0.7577401306], 165 | [3,5,0.8491293059], 166 | [10,5,0.7431324681], 167 | [10,8,0.3922270195], 168 | [7,9,0.6787351549], 169 | [2,10,0.03571167857], 170 | [6,10,0.9339932478], 171 | [10,10,0.6554778902] 172 | ] 173 | } 174 | } 175 | 176 | 177 | >> 178 | json2data = 179 | 180 | sparse: [10x10 double] 181 | 182 | >> >> 183 | %================================================= 184 | >> % a complex sparse matrix 185 | >> %================================================= 186 | 187 | >> >> 188 | data2json = 189 | 190 | (1,2) 0.6557 - 0.6557i 191 | (9,2) 0.7577 - 0.7577i 192 | (3,5) 0.8491 - 0.8491i 193 | (10,5) 0.7431 - 0.7431i 194 | (10,8) 0.3922 - 0.3922i 195 | (7,9) 0.6787 - 0.6787i 196 | (2,10) 0.0357 - 0.0357i 197 | (6,10) 0.9340 - 0.9340i 198 | (10,10) 0.6555 - 0.6555i 199 | 200 | >> 201 | ans = 202 | 203 | { 204 | "complex_sparse": { 205 | "_ArrayType_": "double", 206 | "_ArraySize_": [10,10], 207 | "_ArrayIsComplex_": 1, 208 | "_ArrayIsSparse_": 1, 209 | "_ArrayData_": [ 210 | [1,2,0.6557406992,-0.6557406992], 211 | [9,2,0.7577401306,-0.7577401306], 212 | [3,5,0.8491293059,-0.8491293059], 213 | [10,5,0.7431324681,-0.7431324681], 214 | [10,8,0.3922270195,-0.3922270195], 215 | [7,9,0.6787351549,-0.6787351549], 216 | [2,10,0.03571167857,-0.03571167857], 217 | [6,10,0.9339932478,-0.9339932478], 218 | [10,10,0.6554778902,-0.6554778902] 219 | ] 220 | } 221 | } 222 | 223 | 224 | >> 225 | json2data = 226 | 227 | complex_sparse: [10x10 double] 228 | 229 | >> >> 230 | %================================================= 231 | >> % an all-zero sparse matrix 232 | >> %================================================= 233 | 234 | >> >> >> 235 | ans = 236 | 237 | { 238 | "all_zero_sparse": { 239 | "_ArrayType_": "double", 240 | "_ArraySize_": [2,3], 241 | "_ArrayIsSparse_": 1, 242 | "_ArrayData_": null 243 | } 244 | } 245 | 246 | 247 | >> 248 | json2data = 249 | 250 | all_zero_sparse: [2x3 double] 251 | 252 | >> >> 253 | %================================================= 254 | >> % an empty sparse matrix 255 | >> %================================================= 256 | 257 | >> >> >> 258 | ans = 259 | 260 | { 261 | "empty_sparse": { 262 | "_ArrayType_": "double", 263 | "_ArraySize_": [0,0], 264 | "_ArrayIsSparse_": 1, 265 | "_ArrayData_": null 266 | } 267 | } 268 | 269 | 270 | >> 271 | json2data = 272 | 273 | empty_sparse: [] 274 | 275 | >> >> 276 | %================================================= 277 | >> % an empty 0-by-0 real matrix 278 | >> %================================================= 279 | 280 | >> >> >> 281 | ans = 282 | 283 | { 284 | "empty_0by0_real": null 285 | } 286 | 287 | 288 | >> 289 | json2data = 290 | 291 | empty_0by0_real: [] 292 | 293 | >> >> 294 | %================================================= 295 | >> % an empty 0-by-3 real matrix 296 | >> %================================================= 297 | 298 | >> >> >> 299 | ans = 300 | 301 | { 302 | "empty_0by3_real": { 303 | "_ArrayType_": "double", 304 | "_ArraySize_": [0,3], 305 | "_ArrayData_": null 306 | } 307 | } 308 | 309 | 310 | >> 311 | json2data = 312 | 313 | empty_0by3_real: [0x3 double] 314 | 315 | >> >> 316 | %================================================= 317 | >> % a sparse real column vector 318 | >> %================================================= 319 | 320 | >> >> >> 321 | ans = 322 | 323 | { 324 | "sparse_column_vector": { 325 | "_ArrayType_": "double", 326 | "_ArraySize_": [5,1], 327 | "_ArrayIsSparse_": 1, 328 | "_ArrayData_": [ 329 | [2,3], 330 | [4,1], 331 | [5,4] 332 | ] 333 | } 334 | } 335 | 336 | 337 | >> 338 | json2data = 339 | 340 | sparse_column_vector: [5x1 double] 341 | 342 | >> >> 343 | %================================================= 344 | >> % a sparse complex column vector 345 | >> %================================================= 346 | 347 | >> >> >> 348 | ans = 349 | 350 | { 351 | "complex_sparse_column_vector": { 352 | "_ArrayType_": "double", 353 | "_ArraySize_": [5,1], 354 | "_ArrayIsComplex_": 1, 355 | "_ArrayIsSparse_": 1, 356 | "_ArrayData_": [ 357 | [2,3,-3], 358 | [4,1,-1], 359 | [5,4,-4] 360 | ] 361 | } 362 | } 363 | 364 | 365 | >> 366 | json2data = 367 | 368 | complex_sparse_column_vector: [5x1 double] 369 | 370 | >> >> 371 | %================================================= 372 | >> % a sparse real row vector 373 | >> %================================================= 374 | 375 | >> >> >> 376 | ans = 377 | 378 | { 379 | "sparse_row_vector": { 380 | "_ArrayType_": "double", 381 | "_ArraySize_": [1,5], 382 | "_ArrayIsSparse_": 1, 383 | "_ArrayData_": [ 384 | [2,3], 385 | [4,1], 386 | [5,4] 387 | ] 388 | } 389 | } 390 | 391 | 392 | >> 393 | json2data = 394 | 395 | sparse_row_vector: [0 3 0 1 4] 396 | 397 | >> >> 398 | %================================================= 399 | >> % a sparse complex row vector 400 | >> %================================================= 401 | 402 | >> >> >> 403 | ans = 404 | 405 | { 406 | "complex_sparse_row_vector": { 407 | "_ArrayType_": "double", 408 | "_ArraySize_": [1,5], 409 | "_ArrayIsComplex_": 1, 410 | "_ArrayIsSparse_": 1, 411 | "_ArrayData_": [ 412 | [2,3,-3], 413 | [4,1,-1], 414 | [5,4,-4] 415 | ] 416 | } 417 | } 418 | 419 | 420 | >> 421 | json2data = 422 | 423 | complex_sparse_row_vector: [1x5 double] 424 | 425 | >> >> 426 | %================================================= 427 | >> % a structure 428 | >> %================================================= 429 | 430 | >> >> 431 | data2json = 432 | 433 | name: 'Think Different' 434 | year: 1997 435 | magic: [3x3 double] 436 | misfits: [Inf NaN] 437 | embedded: [1x1 struct] 438 | 439 | >> 440 | ans = 441 | 442 | { 443 | "astruct": { 444 | "name": "Think Different", 445 | "year": 1997, 446 | "magic": [ 447 | [8,1,6], 448 | [3,5,7], 449 | [4,9,2] 450 | ], 451 | "misfits": ["_Inf_","_NaN_"], 452 | "embedded": { 453 | "left": true, 454 | "right": false 455 | } 456 | } 457 | } 458 | 459 | 460 | >> 461 | json2data = 462 | 463 | astruct: [1x1 struct] 464 | 465 | >> 466 | ans = 467 | 468 | logical 469 | 470 | >> >> 471 | %================================================= 472 | >> % a structure array 473 | >> %================================================= 474 | 475 | >> >> >> >> >> 476 | ans = 477 | 478 | { 479 | "Supreme Commander": [ 480 | { 481 | "name": "Nexus Prime", 482 | "rank": 9 483 | }, 484 | { 485 | "name": "Sentinel Prime", 486 | "rank": 9 487 | }, 488 | { 489 | "name": "Optimus Prime", 490 | "rank": 9 491 | } 492 | ] 493 | } 494 | 495 | 496 | >> 497 | json2data = 498 | 499 | Supreme_0x20_Commander: {[1x1 struct] [1x1 struct] [1x1 struct]} 500 | 501 | >> >> 502 | %================================================= 503 | >> % a cell array 504 | >> %================================================= 505 | 506 | >> >> >> >> >> 507 | data2json = 508 | 509 | [1x1 struct] 510 | [1x1 struct] 511 | [1x4 double] 512 | 513 | >> 514 | ans = 515 | 516 | { 517 | "debian": [ 518 | [ 519 | { 520 | "buzz": 1.10, 521 | "rex": 1.20, 522 | "bo": 1.30, 523 | "hamm": 2.00, 524 | "slink": 2.10, 525 | "potato": 2.20, 526 | "woody": 3.00, 527 | "sarge": 3.10, 528 | "etch": 4.00, 529 | "lenny": 5.00, 530 | "squeeze": 6.00, 531 | "wheezy": 7.00 532 | } 533 | ], 534 | [ 535 | { 536 | "Ubuntu": [ 537 | "Kubuntu", 538 | "Xubuntu", 539 | "Lubuntu" 540 | ] 541 | } 542 | ], 543 | [ 544 | [10.04,10.10,11.04,11.10] 545 | ] 546 | ] 547 | } 548 | 549 | 550 | >> 551 | json2data = 552 | 553 | debian: {{1x1 cell} {1x1 cell} [10.0400 10.1000 11.0400 11.1000]} 554 | 555 | >> >> 556 | %================================================= 557 | >> % invalid field-name handling 558 | >> %================================================= 559 | 560 | >> >> 561 | json2data = 562 | 563 | ValidName: 1 564 | x0x5F_InvalidName: 2 565 | x0x3A_Field_0x3A_: 3 566 | x0xE9A1B9__0xE79BAE_: '绝密' 567 | 568 | >> >> 569 | %================================================= 570 | >> % a 2D cell array 571 | >> %================================================= 572 | 573 | >> >> >> 574 | ans = 575 | 576 | { 577 | "data2json": [ 578 | [ 579 | [ 580 | 1, 581 | [ 582 | 2, 583 | 3 584 | ] 585 | ], 586 | [ 587 | 4, 588 | 5 589 | ], 590 | [ 591 | 6 592 | ] 593 | ], 594 | [ 595 | [ 596 | 7 597 | ], 598 | [ 599 | 8, 600 | 9 601 | ], 602 | [ 603 | 10 604 | ] 605 | ] 606 | ] 607 | } 608 | 609 | 610 | >> 611 | json2data = 612 | 613 | data2json: {{3x1 cell} {3x1 cell}} 614 | 615 | >> >> 616 | %================================================= 617 | >> % a 2D struct array 618 | >> %================================================= 619 | 620 | >> >> 621 | data2json = 622 | 623 | 2x3 struct array with fields: 624 | idx 625 | data 626 | 627 | >> >> 628 | ans = 629 | 630 | { 631 | "data2json": [ 632 | [ 633 | { 634 | "idx": 1, 635 | "data": "structs" 636 | }, 637 | { 638 | "idx": 2, 639 | "data": "structs" 640 | } 641 | ], 642 | [ 643 | { 644 | "idx": 3, 645 | "data": "structs" 646 | }, 647 | { 648 | "idx": 4, 649 | "data": "structs" 650 | } 651 | ], 652 | [ 653 | { 654 | "idx": 5, 655 | "data": "structs" 656 | }, 657 | { 658 | "idx": 6, 659 | "data": "structs" 660 | } 661 | ] 662 | ] 663 | } 664 | 665 | 666 | >> 667 | json2data = 668 | 669 | data2json: {{1x2 cell} {1x2 cell} {1x2 cell}} 670 | 671 | >> >> >> >> -------------------------------------------------------------------------------- /jsonlab-1.5/examples/jsonlab_selftest.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % Regression Test Unit of loadjson and savejson 3 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 4 | 5 | for i=1:4 6 | fname=sprintf('example%d.json',i); 7 | if(exist(fname,'file')==0) break; end 8 | fprintf(1,'===============================================\n>> %s\n',fname); 9 | json=savejson('data',loadjson(fname)); 10 | fprintf(1,'%s\n',json); 11 | fprintf(1,'%s\n',savejson('data',loadjson(fname),'Compact',1)); 12 | data=loadjson(json); 13 | savejson('data',data,'selftest.json'); 14 | data=loadjson('selftest.json'); 15 | end 16 | 17 | for i=1:4 18 | fname=sprintf('example%d.json',i); 19 | if(exist(fname,'file')==0) break; end 20 | fprintf(1,'===============================================\n>> %s\n',fname); 21 | json=saveubjson('data',loadjson(fname)); 22 | fprintf(1,'%s\n',json); 23 | data=loadubjson(json); 24 | savejson('',data); 25 | saveubjson('data',data,'selftest.ubj'); 26 | data=loadubjson('selftest.ubj'); 27 | end 28 | -------------------------------------------------------------------------------- /jsonlab-1.5/examples/jsonlab_selftest.matlab: -------------------------------------------------------------------------------- 1 | 2 | < M A T L A B (R) > 3 | Copyright 1984-2010 The MathWorks, Inc. 4 | Version 7.11.0.584 (R2010b) 64-bit (glnxa64) 5 | August 16, 2010 6 | 7 | 8 | To get started, type one of these: helpwin, helpdesk, or demo. 9 | For product information, visit www.mathworks.com. 10 | 11 | >> >> >> >> >> =============================================== 12 | >> example1.json 13 | { 14 | "data": { 15 | "firstName": "John", 16 | "lastName": "Smith", 17 | "age": 25, 18 | "address": { 19 | "streetAddress": "21 2nd Street", 20 | "city": "New York", 21 | "state": "NY", 22 | "postalCode": "10021" 23 | }, 24 | "phoneNumber": [ 25 | { 26 | "type": "home", 27 | "number": "212 555-1234" 28 | }, 29 | { 30 | "type": "fax", 31 | "number": "646 555-4567" 32 | } 33 | ] 34 | } 35 | } 36 | 37 | {"data": {"firstName": "John","lastName": "Smith","age": 25,"address": {"streetAddress": "21 2nd Street","city": "New York","state": "NY","postalCode": "10021"},"phoneNumber": [{"type": "home","number": "212 555-1234"},{"type": "fax","number": "646 555-4567"}]}} 38 | 39 | =============================================== 40 | >> example2.json 41 | { 42 | "data": { 43 | "glossary": { 44 | "title": "example glossary", 45 | "GlossDiv": { 46 | "title": "S", 47 | "GlossList": { 48 | "GlossEntry": { 49 | "ID": "SGML", 50 | "SortAs": "SGML", 51 | "GlossTerm": "Standard Generalized Markup Language", 52 | "Acronym": "SGML", 53 | "Abbrev": "ISO 8879:1986", 54 | "GlossDef": { 55 | "para": "A meta-markup language, used to create markup languages such as DocBook.", 56 | "GlossSeeAlso": [ 57 | "GML", 58 | "XML" 59 | ] 60 | }, 61 | "GlossSee": "markup" 62 | } 63 | } 64 | } 65 | } 66 | } 67 | } 68 | 69 | {"data": {"glossary": {"title": "example glossary","GlossDiv": {"title": "S","GlossList": {"GlossEntry": {"ID": "SGML","SortAs": "SGML","GlossTerm": "Standard Generalized Markup Language","Acronym": "SGML","Abbrev": "ISO 8879:1986","GlossDef": {"para": "A meta-markup language, used to create markup languages such as DocBook.","GlossSeeAlso": ["GML","XML"]},"GlossSee": "markup"}}}}}} 70 | 71 | =============================================== 72 | >> example3.json 73 | { 74 | "data": { 75 | "menu": { 76 | "id": "file", 77 | "value": "_&File", 78 | "popup": { 79 | "menuitem": [ 80 | { 81 | "value": "_&New", 82 | "onclick": "CreateNewDoc(\"'\\\"Untitled\\\"'\")" 83 | }, 84 | { 85 | "value": "_&Open", 86 | "onclick": "OpenDoc()" 87 | }, 88 | { 89 | "value": "_&Close", 90 | "onclick": "CloseDoc()" 91 | } 92 | ] 93 | } 94 | } 95 | } 96 | } 97 | 98 | {"data": {"menu": {"id": "file","value": "_&File","popup": {"menuitem": [{"value": "_&New","onclick": "CreateNewDoc(\"'\\\"Untitled\\\"'\")"},{"value": "_&Open","onclick": "OpenDoc()"},{"value": "_&Close","onclick": "CloseDoc()"}]}}}} 99 | 100 | =============================================== 101 | >> example4.json 102 | { 103 | "data": [ 104 | { 105 | "sample": { 106 | "rho": 1 107 | } 108 | }, 109 | { 110 | "sample": { 111 | "rho": 2 112 | } 113 | }, 114 | [ 115 | [1,0], 116 | [1,1], 117 | [1,2] 118 | ], 119 | [ 120 | "Paper", 121 | "Scissors", 122 | "Stone" 123 | ], 124 | [ 125 | "a", 126 | "b\\", 127 | "c\"", 128 | "d\\\"", 129 | "e\"[", 130 | "f\\\"[", 131 | "g[\\", 132 | "h[\\\"" 133 | ] 134 | ] 135 | } 136 | 137 | {"data": [{"sample": {"rho": 1}},{"sample": {"rho": 2}},[[1,0],[1,1],[1,2]],["Paper","Scissors","Stone"],["a","b\\","c\"","d\\\"","e\"[","f\\\"[","g[\\","h[\\\""]]} 138 | 139 | >> >> =============================================== 140 | >> example1.json 141 | {Udata{U firstNameSUJohnUlastNameSUSmithUageiUaddress{U streetAddressSU 21 2nd StreetUcitySUNew YorkUstateSUNYU 142 | postalCodeSU10021}U phoneNumber[{UtypeSUhomeUnumberSU 212 555-1234}{UtypeSUfaxUnumberSU 646 555-4567}]}} 143 | =============================================== 144 | >> example2.json 145 | {Udata{Uglossary{UtitleSUexample glossaryUGlossDiv{UtitleCSU GlossList{U 146 | GlossEntry{UIDSUSGMLUSortAsSUSGMLU GlossTermSU$Standard Generalized Markup LanguageUAcronymSUSGMLUAbbrevSU ISO 8879:1986UGlossDef{UparaSUHA meta-markup language, used to create markup languages such as DocBook.U GlossSeeAlso[SUGMLSUXML]}UGlossSeeSUmarkup}}}}}} 147 | =============================================== 148 | >> example3.json 149 | {Udata{Umenu{UidSUfileUvalueSU_&FileUpopup{Umenuitem[{UvalueSU_&NewUonclickSUCreateNewDoc("'\"Untitled\"'")}{UvalueSU_&OpenUonclickSU OpenDoc()}{UvalueSU_&CloseUonclickSU 150 | CloseDoc()}]}}}} 151 | =============================================== 152 | >> example4.json 153 | {Udata[{Usample{Urhoi}}{Usample{Urhoi}}[[$i#U[$i#U[$i#U][SUPaperSUScissorsSUStone][CaSUb\SUc"SUd\"SUe"[SUf\"[SUg[\SUh[\"]]} 154 | >> -------------------------------------------------------------------------------- /jsonlab-1.5/examples/jsonlab_speedtest.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % Benchmarking processing speed of savejson and loadjson 3 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 4 | 5 | datalen=[1e3 1e4 1e5 1e6]; 6 | len=length(datalen); 7 | tsave=zeros(len,1); 8 | tload=zeros(len,1); 9 | for i=1:len 10 | tic; 11 | json=savejson('data',struct('d1',rand(datalen(i),3),'d2',rand(datalen(i),3)>0.5)); 12 | tsave(i)=toc; 13 | data=loadjson(json); 14 | tload(i)=toc-tsave(i); 15 | fprintf(1,'matrix size: %d\n',datalen(i)); 16 | end 17 | 18 | loglog(datalen,tsave,'o-',datalen,tload,'r*-'); 19 | legend('savejson runtime (s)','loadjson runtime (s)'); 20 | xlabel('array size'); 21 | ylabel('running time (s)'); 22 | -------------------------------------------------------------------------------- /jsonlab-1.5/jsonopt.m: -------------------------------------------------------------------------------- 1 | function val=jsonopt(key,default,varargin) 2 | % 3 | % val=jsonopt(key,default,optstruct) 4 | % 5 | % setting options based on a struct. The struct can be produced 6 | % by varargin2struct from a list of 'param','value' pairs 7 | % 8 | % authors:Qianqian Fang (q.fang neu.edu) 9 | % 10 | % $Id: loadjson.m 371 2012-06-20 12:43:06Z fangq $ 11 | % 12 | % input: 13 | % key: a string with which one look up a value from a struct 14 | % default: if the key does not exist, return default 15 | % optstruct: a struct where each sub-field is a key 16 | % 17 | % output: 18 | % val: if key exists, val=optstruct.key; otherwise val=default 19 | % 20 | % license: 21 | % BSD License, see LICENSE_BSD.txt files for details 22 | % 23 | % -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) 24 | % 25 | 26 | val=default; 27 | if(nargin<=2) return; end 28 | opt=varargin{1}; 29 | if(isstruct(opt)) 30 | if(isfield(opt,key)) 31 | val=getfield(opt,key); 32 | elseif(isfield(opt,lower(key))) 33 | val=getfield(opt,lower(key)); 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /jsonlab-1.5/loadjson.m: -------------------------------------------------------------------------------- 1 | function data = loadjson(fname,varargin) 2 | % 3 | % data=loadjson(fname,opt) 4 | % or 5 | % data=loadjson(fname,'param1',value1,'param2',value2,...) 6 | % 7 | % parse a JSON (JavaScript Object Notation) file or string 8 | % 9 | % authors:Qianqian Fang (q.fang neu.edu) 10 | % created on 2011/09/09, including previous works from 11 | % 12 | % Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 13 | % created on 2009/11/02 14 | % François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 15 | % created on 2009/03/22 16 | % Joel Feenstra: 17 | % http://www.mathworks.com/matlabcentral/fileexchange/20565 18 | % created on 2008/07/03 19 | % 20 | % $Id$ 21 | % 22 | % input: 23 | % fname: input file name, if fname contains "{}" or "[]", fname 24 | % will be interpreted as a JSON string 25 | % opt: a struct to store parsing options, opt can be replaced by 26 | % a list of ('param',value) pairs - the param string is equivallent 27 | % to a field in opt. opt can have the following 28 | % fields (first in [.|.] is the default) 29 | % 30 | % opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat 31 | % for each element of the JSON data, and group 32 | % arrays based on the cell2mat rules. 33 | % opt.FastArrayParser [1|0 or integer]: if set to 1, use a 34 | % speed-optimized array parser when loading an 35 | % array object. The fast array parser may 36 | % collapse block arrays into a single large 37 | % array similar to rules defined in cell2mat; 0 to 38 | % use a legacy parser; if set to a larger-than-1 39 | % value, this option will specify the minimum 40 | % dimension to enable the fast array parser. For 41 | % example, if the input is a 3D array, setting 42 | % FastArrayParser to 1 will return a 3D array; 43 | % setting to 2 will return a cell array of 2D 44 | % arrays; setting to 3 will return to a 2D cell 45 | % array of 1D vectors; setting to 4 will return a 46 | % 3D cell array. 47 | % opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar. 48 | % 49 | % output: 50 | % dat: a cell array, where {...} blocks are converted into cell arrays, 51 | % and [...] are converted to arrays 52 | % 53 | % examples: 54 | % dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}') 55 | % dat=loadjson(['examples' filesep 'example1.json']) 56 | % dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1) 57 | % 58 | % license: 59 | % BSD License, see LICENSE_BSD.txt files for details 60 | % 61 | % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) 62 | % 63 | 64 | global pos index_esc isoct arraytoken 65 | 66 | if(regexp(fname,'^\s*(?:\[.*\])|(?:\{.*\})\s*$','once')) 67 | string=fname; 68 | elseif(exist(fname,'file')) 69 | try 70 | string = fileread(fname); 71 | catch 72 | try 73 | string = urlread(['file://',fname]); 74 | catch 75 | string = urlread(['file://',fullfile(pwd,fname)]); 76 | end 77 | end 78 | else 79 | error('input file does not exist'); 80 | end 81 | 82 | pos = 1; len = length(string); inStr = string; 83 | isoct=exist('OCTAVE_VERSION','builtin'); 84 | arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); 85 | jstr=regexprep(inStr,'\\\\',' '); 86 | escquote=regexp(jstr,'\\"'); 87 | arraytoken=sort([arraytoken escquote]); 88 | 89 | % String delimiters and escape chars identified to improve speed: 90 | esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); 91 | index_esc = 1; 92 | 93 | opt=varargin2struct(varargin{:}); 94 | 95 | if(jsonopt('ShowProgress',0,opt)==1) 96 | opt.progressbar_=waitbar(0,'loading ...'); 97 | end 98 | jsoncount=1; 99 | while pos <= len 100 | switch(next_char(inStr)) 101 | case '{' 102 | data{jsoncount} = parse_object(inStr, esc, opt); 103 | case '[' 104 | data{jsoncount} = parse_array(inStr, esc, opt); 105 | otherwise 106 | error_pos('Outer level structure must be an object or an array',inStr); 107 | end 108 | jsoncount=jsoncount+1; 109 | end % while 110 | 111 | jsoncount=length(data); 112 | if(jsoncount==1 && iscell(data)) 113 | data=data{1}; 114 | end 115 | 116 | if(isfield(opt,'progressbar_')) 117 | close(opt.progressbar_); 118 | end 119 | 120 | %%------------------------------------------------------------------------- 121 | function object = parse_object(inStr, esc, varargin) 122 | parse_char(inStr, '{'); 123 | object = []; 124 | if next_char(inStr) ~= '}' 125 | while 1 126 | str = parseStr(inStr, esc, varargin{:}); 127 | if isempty(str) 128 | error_pos('Name of value at position %d cannot be empty',inStr); 129 | end 130 | parse_char(inStr, ':'); 131 | val = parse_value(inStr, esc, varargin{:}); 132 | object.(valid_field(str))=val; 133 | if next_char(inStr) == '}' 134 | break; 135 | end 136 | parse_char(inStr, ','); 137 | end 138 | end 139 | parse_char(inStr, '}'); 140 | if(isstruct(object)) 141 | object=struct2jdata(object); 142 | end 143 | 144 | %%------------------------------------------------------------------------- 145 | 146 | function object = parse_array(inStr, esc, varargin) % JSON array is written in row-major order 147 | global pos isoct 148 | parse_char(inStr, '['); 149 | object = cell(0, 1); 150 | dim2=[]; 151 | arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); 152 | pbar=-1; 153 | if(isfield(varargin{1},'progressbar_')) 154 | pbar=varargin{1}.progressbar_; 155 | end 156 | 157 | if next_char(inStr) ~= ']' 158 | if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) 159 | [endpos, e1l, e1r]=matching_bracket(inStr,pos); 160 | arraystr=['[' inStr(pos:endpos)]; 161 | arraystr=regexprep(arraystr,'"_NaN_"','NaN'); 162 | arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); 163 | arraystr(arraystr==sprintf('\n'))=[]; 164 | arraystr(arraystr==sprintf('\r'))=[]; 165 | %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed 166 | if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D 167 | astr=inStr((e1l+1):(e1r-1)); 168 | astr=regexprep(astr,'"_NaN_"','NaN'); 169 | astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); 170 | astr(astr==sprintf('\n'))=[]; 171 | astr(astr==sprintf('\r'))=[]; 172 | astr(astr==' ')=''; 173 | if(isempty(find(astr=='[', 1))) % array is 2D 174 | dim2=length(sscanf(astr,'%f,',[1 inf])); 175 | end 176 | else % array is 1D 177 | astr=arraystr(2:end-1); 178 | astr(astr==' ')=''; 179 | [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); 180 | if(nextidx>=length(astr)-1) 181 | object=obj; 182 | pos=endpos; 183 | parse_char(inStr, ']'); 184 | return; 185 | end 186 | end 187 | 188 | try 189 | if(~isempty(dim2)) 190 | astr=arraystr; 191 | astr(astr=='[')=''; 192 | astr(astr==']')=''; 193 | astr=regexprep(astr,'\s*$',''); 194 | astr(astr==' ')=''; 195 | [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf); 196 | if(nextidx>=length(astr)-1) 197 | object=reshape(obj,dim2,numel(obj)/dim2)'; 198 | pos=endpos; 199 | parse_char(inStr, ']'); 200 | if(pbar>0) 201 | waitbar(pos/length(inStr),pbar,'loading ...'); 202 | end 203 | return; 204 | end 205 | end 206 | arraystr=regexprep(arraystr,'\]\s*,','];'); 207 | catch 208 | end 209 | else 210 | arraystr='['; 211 | end 212 | try 213 | arraystr=regexprep(arraystr,'^\s*\[','{','once'); 214 | arraystr=regexprep(arraystr,'\]\s*$','}','once'); 215 | if(isoct && regexp(arraystr,'"','once')) 216 | error('Octave eval can produce empty cells for JSON-like input'); 217 | end 218 | object=eval(arraystr); 219 | pos=endpos; 220 | catch 221 | while 1 222 | newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); 223 | val = parse_value(inStr, esc, newopt); 224 | object{end+1} = val; 225 | if next_char(inStr) == ']' 226 | break; 227 | end 228 | parse_char(inStr, ','); 229 | end 230 | end 231 | end 232 | if(jsonopt('SimplifyCell',0,varargin{:})==1) 233 | try 234 | oldobj=object; 235 | object=cell2mat(object')'; 236 | if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) 237 | object=oldobj; 238 | elseif(size(object,1)>1 && ismatrix(object)) 239 | object=object'; 240 | end 241 | catch 242 | end 243 | end 244 | parse_char(inStr, ']'); 245 | 246 | if(pbar>0) 247 | waitbar(pos/length(inStr),pbar,'loading ...'); 248 | end 249 | %%------------------------------------------------------------------------- 250 | 251 | function parse_char(inStr, c) 252 | global pos 253 | pos=skip_whitespace(pos, inStr); 254 | if pos > length(inStr) || inStr(pos) ~= c 255 | error_pos(sprintf('Expected %c at position %%d', c),inStr); 256 | else 257 | pos = pos + 1; 258 | pos=skip_whitespace(pos, inStr); 259 | end 260 | 261 | %%------------------------------------------------------------------------- 262 | 263 | function c = next_char(inStr) 264 | global pos 265 | pos=skip_whitespace(pos, inStr); 266 | if pos > length(inStr) 267 | c = []; 268 | else 269 | c = inStr(pos); 270 | end 271 | 272 | %%------------------------------------------------------------------------- 273 | 274 | function newpos=skip_whitespace(pos, inStr) 275 | newpos=pos; 276 | while newpos <= length(inStr) && isspace(inStr(newpos)) 277 | newpos = newpos + 1; 278 | end 279 | 280 | %%------------------------------------------------------------------------- 281 | function str = parseStr(inStr, esc, varargin) 282 | global pos index_esc 283 | % len, ns = length(inStr), keyboard 284 | if inStr(pos) ~= '"' 285 | error_pos('String starting with " expected at position %d',inStr); 286 | else 287 | pos = pos + 1; 288 | end 289 | str = ''; 290 | while pos <= length(inStr) 291 | while index_esc <= length(esc) && esc(index_esc) < pos 292 | index_esc = index_esc + 1; 293 | end 294 | if index_esc > length(esc) 295 | str = [str inStr(pos:end)]; 296 | pos = length(inStr) + 1; 297 | break; 298 | else 299 | str = [str inStr(pos:esc(index_esc)-1)]; 300 | pos = esc(index_esc); 301 | end 302 | nstr = length(str); 303 | switch inStr(pos) 304 | case '"' 305 | pos = pos + 1; 306 | if(~isempty(str)) 307 | if(strcmp(str,'_Inf_')) 308 | str=Inf; 309 | elseif(strcmp(str,'-_Inf_')) 310 | str=-Inf; 311 | elseif(strcmp(str,'_NaN_')) 312 | str=NaN; 313 | end 314 | end 315 | return; 316 | case '\' 317 | if pos+1 > length(inStr) 318 | error_pos('End of file reached right after escape character',inStr); 319 | end 320 | pos = pos + 1; 321 | switch inStr(pos) 322 | case {'"' '\' '/'} 323 | str(nstr+1) = inStr(pos); 324 | pos = pos + 1; 325 | case {'b' 'f' 'n' 'r' 't'} 326 | str(nstr+1) = sprintf(['\' inStr(pos)]); 327 | pos = pos + 1; 328 | case 'u' 329 | if pos+4 > length(inStr) 330 | error_pos('End of file reached in escaped unicode character',inStr); 331 | end 332 | str(nstr+(1:6)) = inStr(pos-1:pos+4); 333 | pos = pos + 5; 334 | end 335 | otherwise % should never happen 336 | str(nstr+1) = inStr(pos); 337 | keyboard; 338 | pos = pos + 1; 339 | end 340 | end 341 | error_pos('End of file while expecting end of inStr',inStr); 342 | 343 | %%------------------------------------------------------------------------- 344 | 345 | function num = parse_number(inStr, varargin) 346 | global pos isoct 347 | currstr=inStr(pos:min(pos+30,end)); 348 | if(isoct~=0) 349 | numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); 350 | [num] = sscanf(currstr, '%f', 1); 351 | delta=numstr+1; 352 | else 353 | [num, one, err, delta] = sscanf(currstr, '%f', 1); 354 | if ~isempty(err) 355 | error_pos('Error reading number at position %d',inStr); 356 | end 357 | end 358 | pos = pos + delta-1; 359 | 360 | %%------------------------------------------------------------------------- 361 | 362 | function val = parse_value(inStr, esc, varargin) 363 | global pos 364 | len=length(inStr); 365 | if(isfield(varargin{1},'progressbar_')) 366 | waitbar(pos/len,varargin{1}.progressbar_,'loading ...'); 367 | end 368 | 369 | switch(inStr(pos)) 370 | case '"' 371 | val = parseStr(inStr, esc, varargin{:}); 372 | return; 373 | case '[' 374 | val = parse_array(inStr, esc, varargin{:}); 375 | return; 376 | case '{' 377 | val = parse_object(inStr, esc, varargin{:}); 378 | return; 379 | case {'-','0','1','2','3','4','5','6','7','8','9'} 380 | val = parse_number(inStr, varargin{:}); 381 | return; 382 | case 't' 383 | if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') 384 | val = true; 385 | pos = pos + 4; 386 | return; 387 | end 388 | case 'f' 389 | if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') 390 | val = false; 391 | pos = pos + 5; 392 | return; 393 | end 394 | case 'n' 395 | if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') 396 | val = []; 397 | pos = pos + 4; 398 | return; 399 | end 400 | end 401 | error_pos('Value expected at position %d',inStr); 402 | %%------------------------------------------------------------------------- 403 | 404 | function error_pos(msg, inStr) 405 | global pos len 406 | poShow = max(min([pos-15 pos-1 pos pos+20],len),1); 407 | if poShow(3) == poShow(2) 408 | poShow(3:4) = poShow(2)+[0 -1]; % display nothing after 409 | end 410 | msg = [sprintf(msg, pos) ': ' ... 411 | inStr(poShow(1):poShow(2)) '' inStr(poShow(3):poShow(4)) ]; 412 | error( ['JSONparser:invalidFormat: ' msg] ); 413 | 414 | %%------------------------------------------------------------------------- 415 | 416 | function str = valid_field(str) 417 | global isoct 418 | % From MATLAB doc: field names must begin with a letter, which may be 419 | % followed by any combination of letters, digits, and underscores. 420 | % Invalid characters will be converted to underscores, and the prefix 421 | % "x0x[Hex code]_" will be added if the first character is not a letter. 422 | pos=regexp(str,'^[^A-Za-z]','once'); 423 | if(~isempty(pos)) 424 | if(~isoct && str(1)+0 > 255) 425 | str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); 426 | else 427 | str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); 428 | end 429 | end 430 | if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) 431 | return; 432 | end 433 | if(~isoct) 434 | str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); 435 | else 436 | pos=regexp(str,'[^0-9A-Za-z_]'); 437 | if(isempty(pos)) 438 | return; 439 | end 440 | str0=str; 441 | pos0=[0 pos(:)' length(str)]; 442 | str=''; 443 | for i=1:length(pos) 444 | str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; 445 | end 446 | if(pos(end)~=length(str)) 447 | str=[str str0(pos0(end-1)+1:pos0(end))]; 448 | end 449 | end 450 | %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; 451 | 452 | %%------------------------------------------------------------------------- 453 | function endpos = matching_quote(str,pos) 454 | len=length(str); 455 | while(pos1 && str(pos-1)=='\')) 458 | endpos=pos; 459 | return; 460 | end 461 | end 462 | pos=pos+1; 463 | end 464 | error('unmatched quotation mark'); 465 | %%------------------------------------------------------------------------- 466 | function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) 467 | global arraytoken 468 | level=1; 469 | maxlevel=level; 470 | endpos=0; 471 | bpos=arraytoken(arraytoken>=pos); 472 | tokens=str(bpos); 473 | len=length(tokens); 474 | pos=1; 475 | e1l=[]; 476 | e1r=[]; 477 | while(pos<=len) 478 | c=tokens(pos); 479 | if(c==']') 480 | level=level-1; 481 | if(isempty(e1r)) 482 | e1r=bpos(pos); 483 | end 484 | if(level==0) 485 | endpos=bpos(pos); 486 | return 487 | end 488 | end 489 | if(c=='[') 490 | if(isempty(e1l)) 491 | e1l=bpos(pos); 492 | end 493 | level=level+1; 494 | maxlevel=max(maxlevel,level); 495 | end 496 | if(c=='"') 497 | pos=matching_quote(tokens,pos+1); 498 | end 499 | pos=pos+1; 500 | end 501 | if(endpos==0) 502 | error('unmatched "]"'); 503 | end 504 | -------------------------------------------------------------------------------- /jsonlab-1.5/loadubjson.m: -------------------------------------------------------------------------------- 1 | function data = loadubjson(fname,varargin) 2 | % 3 | % data=loadubjson(fname,opt) 4 | % or 5 | % data=loadubjson(fname,'param1',value1,'param2',value2,...) 6 | % 7 | % parse a JSON (JavaScript Object Notation) file or string 8 | % 9 | % authors:Qianqian Fang (q.fang neu.edu) 10 | % created on 2013/08/01 11 | % 12 | % $Id$ 13 | % 14 | % input: 15 | % fname: input file name, if fname contains "{}" or "[]", fname 16 | % will be interpreted as a UBJSON string 17 | % opt: a struct to store parsing options, opt can be replaced by 18 | % a list of ('param',value) pairs - the param string is equivallent 19 | % to a field in opt. opt can have the following 20 | % fields (first in [.|.] is the default) 21 | % 22 | % opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat 23 | % for each element of the JSON data, and group 24 | % arrays based on the cell2mat rules. 25 | % opt.IntEndian [B|L]: specify the endianness of the integer fields 26 | % in the UBJSON input data. B - Big-Endian format for 27 | % integers (as required in the UBJSON specification); 28 | % L - input integer fields are in Little-Endian order. 29 | % opt.NameIsString [0|1]: for UBJSON Specification Draft 8 or 30 | % earlier versions (JSONLab 1.0 final or earlier), 31 | % the "name" tag is treated as a string. To load 32 | % these UBJSON data, you need to manually set this 33 | % flag to 1. 34 | % 35 | % output: 36 | % dat: a cell array, where {...} blocks are converted into cell arrays, 37 | % and [...] are converted to arrays 38 | % 39 | % examples: 40 | % obj=struct('string','value','array',[1 2 3]); 41 | % ubjdata=saveubjson('obj',obj); 42 | % dat=loadubjson(ubjdata) 43 | % dat=loadubjson(['examples' filesep 'example1.ubj']) 44 | % dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1) 45 | % 46 | % license: 47 | % BSD License, see LICENSE_BSD.txt files for details 48 | % 49 | % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) 50 | % 51 | 52 | global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian 53 | 54 | if(regexp(fname,'[\{\}\]\[]','once')) 55 | string=fname; 56 | elseif(exist(fname,'file')) 57 | fid = fopen(fname,'rb'); 58 | string = fread(fid,inf,'uint8=>char')'; 59 | fclose(fid); 60 | else 61 | error('input file does not exist'); 62 | end 63 | 64 | pos = 1; len = length(string); inStr = string; 65 | isoct=exist('OCTAVE_VERSION','builtin'); 66 | arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); 67 | jstr=regexprep(inStr,'\\\\',' '); 68 | escquote=regexp(jstr,'\\"'); 69 | arraytoken=sort([arraytoken escquote]); 70 | 71 | % String delimiters and escape chars identified to improve speed: 72 | esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); 73 | index_esc = 1; len_esc = length(esc); 74 | 75 | opt=varargin2struct(varargin{:}); 76 | fileendian=upper(jsonopt('IntEndian','B',opt)); 77 | [os,maxelem,systemendian]=computer; 78 | 79 | jsoncount=1; 80 | while pos <= len 81 | switch(next_char) 82 | case '{' 83 | data{jsoncount} = parse_object(opt); 84 | case '[' 85 | data{jsoncount} = parse_array(opt); 86 | otherwise 87 | error_pos('Outer level structure must be an object or an array'); 88 | end 89 | jsoncount=jsoncount+1; 90 | end % while 91 | 92 | jsoncount=length(data); 93 | if(jsoncount==1 && iscell(data)) 94 | data=data{1}; 95 | end 96 | 97 | %%------------------------------------------------------------------------- 98 | function object = parse_object(varargin) 99 | parse_char('{'); 100 | object = []; 101 | type=''; 102 | count=-1; 103 | if(next_char == '$') 104 | type=inStr(pos+1); % TODO 105 | pos=pos+2; 106 | end 107 | if(next_char == '#') 108 | pos=pos+1; 109 | count=double(parse_number()); 110 | end 111 | if next_char ~= '}' 112 | num=0; 113 | while 1 114 | if(jsonopt('NameIsString',0,varargin{:})) 115 | str = parseStr(varargin{:}); 116 | else 117 | str = parse_name(varargin{:}); 118 | end 119 | if isempty(str) 120 | error_pos('Name of value at position %d cannot be empty'); 121 | end 122 | %parse_char(':'); 123 | val = parse_value(varargin{:}); 124 | num=num+1; 125 | object.(valid_field(str))=val; 126 | if next_char == '}' || (count>=0 && num>=count) 127 | break; 128 | end 129 | %parse_char(','); 130 | end 131 | end 132 | if(count==-1) 133 | parse_char('}'); 134 | end 135 | if(isstruct(object)) 136 | object=struct2jdata(object); 137 | end 138 | 139 | %%------------------------------------------------------------------------- 140 | function [cid,len]=elem_info(type) 141 | id=strfind('iUIlLdD',type); 142 | dataclass={'int8','uint8','int16','int32','int64','single','double'}; 143 | bytelen=[1,1,2,4,8,4,8]; 144 | if(id>0) 145 | cid=dataclass{id}; 146 | len=bytelen(id); 147 | else 148 | error_pos('unsupported type at position %d'); 149 | end 150 | %%------------------------------------------------------------------------- 151 | 152 | 153 | function [data, adv]=parse_block(type,count,varargin) 154 | global pos inStr isoct fileendian systemendian 155 | [cid,len]=elem_info(type); 156 | datastr=inStr(pos:pos+len*count-1); 157 | if(isoct) 158 | newdata=int8(datastr); 159 | else 160 | newdata=uint8(datastr); 161 | end 162 | id=strfind('iUIlLdD',type); 163 | if(fileendian~=systemendian) 164 | newdata=swapbytes(typecast(newdata,cid)); 165 | end 166 | data=typecast(newdata,cid); 167 | adv=double(len*count); 168 | 169 | %%------------------------------------------------------------------------- 170 | 171 | 172 | function object = parse_array(varargin) % JSON array is written in row-major order 173 | global pos inStr 174 | parse_char('['); 175 | object = cell(0, 1); 176 | dim=[]; 177 | type=''; 178 | count=-1; 179 | if(next_char == '$') 180 | type=inStr(pos+1); 181 | pos=pos+2; 182 | end 183 | if(next_char == '#') 184 | pos=pos+1; 185 | if(next_char=='[') 186 | dim=parse_array(varargin{:}); 187 | count=prod(double(dim)); 188 | else 189 | count=double(parse_number()); 190 | end 191 | end 192 | if(~isempty(type)) 193 | if(count>=0) 194 | [object, adv]=parse_block(type,count,varargin{:}); 195 | if(~isempty(dim)) 196 | object=reshape(object,dim); 197 | end 198 | pos=pos+adv; 199 | return; 200 | else 201 | endpos=matching_bracket(inStr,pos); 202 | [cid,len]=elem_info(type); 203 | count=(endpos-pos)/len; 204 | [object, adv]=parse_block(type,count,varargin{:}); 205 | pos=pos+adv; 206 | parse_char(']'); 207 | return; 208 | end 209 | end 210 | if next_char ~= ']' 211 | while 1 212 | val = parse_value(varargin{:}); 213 | object{end+1} = val; 214 | if next_char == ']' 215 | break; 216 | end 217 | %parse_char(','); 218 | end 219 | end 220 | if(jsonopt('SimplifyCell',0,varargin{:})==1) 221 | try 222 | oldobj=object; 223 | object=cell2mat(object')'; 224 | if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) 225 | object=oldobj; 226 | elseif(size(object,1)>1 && ismatrix(object)) 227 | object=object'; 228 | end 229 | catch 230 | end 231 | end 232 | if(count==-1) 233 | parse_char(']'); 234 | end 235 | 236 | %%------------------------------------------------------------------------- 237 | 238 | function parse_char(c) 239 | global pos inStr len 240 | skip_whitespace; 241 | if pos > len || inStr(pos) ~= c 242 | error_pos(sprintf('Expected %c at position %%d', c)); 243 | else 244 | pos = pos + 1; 245 | skip_whitespace; 246 | end 247 | 248 | %%------------------------------------------------------------------------- 249 | 250 | function c = next_char 251 | global pos inStr len 252 | skip_whitespace; 253 | if pos > len 254 | c = []; 255 | else 256 | c = inStr(pos); 257 | end 258 | 259 | %%------------------------------------------------------------------------- 260 | 261 | function skip_whitespace 262 | global pos inStr len 263 | while pos <= len && isspace(inStr(pos)) 264 | pos = pos + 1; 265 | end 266 | 267 | %%------------------------------------------------------------------------- 268 | function str = parse_name(varargin) 269 | global pos inStr 270 | bytelen=double(parse_number()); 271 | if(length(inStr)>=pos+bytelen-1) 272 | str=inStr(pos:pos+bytelen-1); 273 | pos=pos+bytelen; 274 | else 275 | error_pos('End of file while expecting end of name'); 276 | end 277 | %%------------------------------------------------------------------------- 278 | 279 | function str = parseStr(varargin) 280 | global pos inStr 281 | % len, ns = length(inStr), keyboard 282 | type=inStr(pos); 283 | if type ~= 'S' && type ~= 'C' && type ~= 'H' 284 | error_pos('String starting with S expected at position %d'); 285 | else 286 | pos = pos + 1; 287 | end 288 | if(type == 'C') 289 | str=inStr(pos); 290 | pos=pos+1; 291 | return; 292 | end 293 | bytelen=double(parse_number()); 294 | if(length(inStr)>=pos+bytelen-1) 295 | str=inStr(pos:pos+bytelen-1); 296 | pos=pos+bytelen; 297 | else 298 | error_pos('End of file while expecting end of inStr'); 299 | end 300 | 301 | %%------------------------------------------------------------------------- 302 | 303 | function num = parse_number(varargin) 304 | global pos inStr isoct fileendian systemendian 305 | id=strfind('iUIlLdD',inStr(pos)); 306 | if(isempty(id)) 307 | error_pos('expecting a number at position %d'); 308 | end 309 | type={'int8','uint8','int16','int32','int64','single','double'}; 310 | bytelen=[1,1,2,4,8,4,8]; 311 | datastr=inStr(pos+1:pos+bytelen(id)); 312 | if(isoct) 313 | newdata=int8(datastr); 314 | else 315 | newdata=uint8(datastr); 316 | end 317 | if(fileendian~=systemendian) 318 | newdata=swapbytes(typecast(newdata,type{id})); 319 | end 320 | num=typecast(newdata,type{id}); 321 | pos = pos + bytelen(id)+1; 322 | 323 | %%------------------------------------------------------------------------- 324 | 325 | function val = parse_value(varargin) 326 | global pos inStr 327 | 328 | switch(inStr(pos)) 329 | case {'S','C','H'} 330 | val = parseStr(varargin{:}); 331 | return; 332 | case '[' 333 | val = parse_array(varargin{:}); 334 | return; 335 | case '{' 336 | val = parse_object(varargin{:}); 337 | return; 338 | case {'i','U','I','l','L','d','D'} 339 | val = parse_number(varargin{:}); 340 | return; 341 | case 'T' 342 | val = true; 343 | pos = pos + 1; 344 | return; 345 | case 'F' 346 | val = false; 347 | pos = pos + 1; 348 | return; 349 | case {'Z','N'} 350 | val = []; 351 | pos = pos + 1; 352 | return; 353 | end 354 | error_pos('Value expected at position %d'); 355 | %%------------------------------------------------------------------------- 356 | 357 | function error_pos(msg) 358 | global pos inStr len 359 | poShow = max(min([pos-15 pos-1 pos pos+20],len),1); 360 | if poShow(3) == poShow(2) 361 | poShow(3:4) = poShow(2)+[0 -1]; % display nothing after 362 | end 363 | msg = [sprintf(msg, pos) ': ' ... 364 | inStr(poShow(1):poShow(2)) '' inStr(poShow(3):poShow(4)) ]; 365 | error( ['JSONparser:invalidFormat: ' msg] ); 366 | 367 | %%------------------------------------------------------------------------- 368 | 369 | function str = valid_field(str) 370 | global isoct 371 | % From MATLAB doc: field names must begin with a letter, which may be 372 | % followed by any combination of letters, digits, and underscores. 373 | % Invalid characters will be converted to underscores, and the prefix 374 | % "x0x[Hex code]_" will be added if the first character is not a letter. 375 | pos=regexp(str,'^[^A-Za-z]','once'); 376 | if(~isempty(pos)) 377 | if(~isoct) 378 | str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); 379 | else 380 | str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); 381 | end 382 | end 383 | if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) 384 | return; 385 | end 386 | if(~isoct) 387 | str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); 388 | else 389 | pos=regexp(str,'[^0-9A-Za-z_]'); 390 | if(isempty(pos)) 391 | return; 392 | end 393 | str0=str; 394 | pos0=[0 pos(:)' length(str)]; 395 | str=''; 396 | for i=1:length(pos) 397 | str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; 398 | end 399 | if(pos(end)~=length(str)) 400 | str=[str str0(pos0(end-1)+1:pos0(end))]; 401 | end 402 | end 403 | %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; 404 | 405 | %%------------------------------------------------------------------------- 406 | function endpos = matching_quote(str,pos) 407 | len=length(str); 408 | while(pos1 && str(pos-1)=='\')) 411 | endpos=pos; 412 | return; 413 | end 414 | end 415 | pos=pos+1; 416 | end 417 | error('unmatched quotation mark'); 418 | %%------------------------------------------------------------------------- 419 | function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) 420 | global arraytoken 421 | level=1; 422 | maxlevel=level; 423 | endpos=0; 424 | bpos=arraytoken(arraytoken>=pos); 425 | tokens=str(bpos); 426 | len=length(tokens); 427 | pos=1; 428 | e1l=[]; 429 | e1r=[]; 430 | while(pos<=len) 431 | c=tokens(pos); 432 | if(c==']') 433 | level=level-1; 434 | if(isempty(e1r)) 435 | e1r=bpos(pos); 436 | end 437 | if(level==0) 438 | endpos=bpos(pos); 439 | return 440 | end 441 | end 442 | if(c=='[') 443 | if(isempty(e1l)) 444 | e1l=bpos(pos); 445 | end 446 | level=level+1; 447 | maxlevel=max(maxlevel,level); 448 | end 449 | if(c=='"') 450 | pos=matching_quote(tokens,pos+1); 451 | end 452 | pos=pos+1; 453 | end 454 | if(endpos==0) 455 | error('unmatched "]"'); 456 | end 457 | 458 | -------------------------------------------------------------------------------- /jsonlab-1.5/mergestruct.m: -------------------------------------------------------------------------------- 1 | function s=mergestruct(s1,s2) 2 | % 3 | % s=mergestruct(s1,s2) 4 | % 5 | % merge two struct objects into one 6 | % 7 | % authors:Qianqian Fang (q.fang neu.edu) 8 | % date: 2012/12/22 9 | % 10 | % input: 11 | % s1,s2: a struct object, s1 and s2 can not be arrays 12 | % 13 | % output: 14 | % s: the merged struct object. fields in s1 and s2 will be combined in s. 15 | % 16 | % license: 17 | % BSD License, see LICENSE_BSD.txt files for details 18 | % 19 | % -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) 20 | % 21 | 22 | if(~isstruct(s1) || ~isstruct(s2)) 23 | error('input parameters contain non-struct'); 24 | end 25 | if(length(s1)>1 || length(s2)>1) 26 | error('can not merge struct arrays'); 27 | end 28 | fn=fieldnames(s2); 29 | s=s1; 30 | for i=1:length(fn) 31 | s=setfield(s,fn{i},getfield(s2,fn{i})); 32 | end 33 | 34 | -------------------------------------------------------------------------------- /jsonlab-1.5/saveubjson.m: -------------------------------------------------------------------------------- 1 | function json=saveubjson(rootname,obj,varargin) 2 | % 3 | % json=saveubjson(rootname,obj,filename) 4 | % or 5 | % json=saveubjson(rootname,obj,opt) 6 | % json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...) 7 | % 8 | % convert a MATLAB object (cell, struct or array) into a Universal 9 | % Binary JSON (UBJSON) binary string 10 | % 11 | % author: Qianqian Fang (q.fang neu.edu) 12 | % created on 2013/08/17 13 | % 14 | % $Id$ 15 | % 16 | % input: 17 | % rootname: the name of the root-object, when set to '', the root name 18 | % is ignored, however, when opt.ForceRootName is set to 1 (see below), 19 | % the MATLAB variable name will be used as the root name. 20 | % obj: a MATLAB object (array, cell, cell array, struct, struct array, 21 | % class instance) 22 | % filename: a string for the file name to save the output UBJSON data 23 | % opt: a struct for additional options, ignore to use default values. 24 | % opt can have the following fields (first in [.|.] is the default) 25 | % 26 | % opt.FileName [''|string]: a file name to save the output JSON data 27 | % opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D 28 | % array in JSON array format; if sets to 1, an 29 | % array will be shown as a struct with fields 30 | % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for 31 | % sparse arrays, the non-zero elements will be 32 | % saved to _ArrayData_ field in triplet-format i.e. 33 | % (ix,iy,val) and "_ArrayIsSparse_" will be added 34 | % with a value of 1; for a complex array, the 35 | % _ArrayData_ array will include two columns 36 | % (4 for sparse) to record the real and imaginary 37 | % parts, and also "_ArrayIsComplex_":1 is added. 38 | % opt.ParseLogical [1|0]: if this is set to 1, logical array elem 39 | % will use true/false rather than 1/0. 40 | % opt.SingletArray [0|1]: if this is set to 1, arrays with a single 41 | % numerical element will be shown without a square 42 | % bracket, unless it is the root object; if 0, square 43 | % brackets are forced for any numerical arrays. 44 | % opt.SingletCell [1|0]: if 1, always enclose a cell with "[]" 45 | % even it has only one element; if 0, brackets 46 | % are ignored when a cell has only 1 element. 47 | % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson 48 | % will use the name of the passed obj variable as the 49 | % root object name; if obj is an expression and 50 | % does not have a name, 'root' will be used; if this 51 | % is set to 0 and rootname is empty, the root level 52 | % will be merged down to the lower level. 53 | % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), 54 | % for example, if opt.JSON='foo', the JSON data is 55 | % wrapped inside a function call as 'foo(...);' 56 | % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson 57 | % back to the string form 58 | % 59 | % opt can be replaced by a list of ('param',value) pairs. The param 60 | % string is equivallent to a field in opt and is case sensitive. 61 | % output: 62 | % json: a binary string in the UBJSON format (see http://ubjson.org) 63 | % 64 | % examples: 65 | % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... 66 | % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... 67 | % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... 68 | % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... 69 | % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... 70 | % 'SpecialData',[nan, inf, -inf]); 71 | % saveubjson('jsonmesh',jsonmesh) 72 | % saveubjson('jsonmesh',jsonmesh,'meshdata.ubj') 73 | % 74 | % license: 75 | % BSD License, see LICENSE_BSD.txt files for details 76 | % 77 | % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) 78 | % 79 | 80 | if(nargin==1) 81 | varname=inputname(1); 82 | obj=rootname; 83 | if(isempty(varname)) 84 | varname='root'; 85 | end 86 | rootname=varname; 87 | else 88 | varname=inputname(2); 89 | end 90 | if(length(varargin)==1 && ischar(varargin{1})) 91 | opt=struct('filename',varargin{1}); 92 | else 93 | opt=varargin2struct(varargin{:}); 94 | end 95 | opt.IsOctave=exist('OCTAVE_VERSION','builtin'); 96 | if(isfield(opt,'norowbracket')) 97 | warning('Option ''NoRowBracket'' is depreciated, please use ''SingletArray'' and set its value to not(NoRowBracket)'); 98 | if(~isfield(opt,'singletarray')) 99 | opt.singletarray=not(opt.norowbracket); 100 | end 101 | end 102 | rootisarray=0; 103 | rootlevel=1; 104 | forceroot=jsonopt('ForceRootName',0,opt); 105 | if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || ... 106 | iscell(obj) || isobject(obj)) && isempty(rootname) && forceroot==0) 107 | rootisarray=1; 108 | rootlevel=0; 109 | else 110 | if(isempty(rootname)) 111 | rootname=varname; 112 | end 113 | end 114 | if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) 115 | rootname='root'; 116 | end 117 | json=obj2ubjson(rootname,obj,rootlevel,opt); 118 | if(~rootisarray) 119 | json=['{' json '}']; 120 | end 121 | 122 | jsonp=jsonopt('JSONP','',opt); 123 | if(~isempty(jsonp)) 124 | json=[jsonp '(' json ')']; 125 | end 126 | 127 | % save to a file if FileName is set, suggested by Patrick Rapin 128 | filename=jsonopt('FileName','',opt); 129 | if(~isempty(filename)) 130 | fid = fopen(filename, 'wb'); 131 | fwrite(fid,json); 132 | fclose(fid); 133 | end 134 | 135 | %%------------------------------------------------------------------------- 136 | function txt=obj2ubjson(name,item,level,varargin) 137 | 138 | if(iscell(item)) 139 | txt=cell2ubjson(name,item,level,varargin{:}); 140 | elseif(isstruct(item)) 141 | txt=struct2ubjson(name,item,level,varargin{:}); 142 | elseif(ischar(item)) 143 | txt=str2ubjson(name,item,level,varargin{:}); 144 | elseif(isobject(item)) 145 | txt=matlabobject2ubjson(name,item,level,varargin{:}); 146 | else 147 | txt=mat2ubjson(name,item,level,varargin{:}); 148 | end 149 | 150 | %%------------------------------------------------------------------------- 151 | function txt=cell2ubjson(name,item,level,varargin) 152 | txt=''; 153 | if(~iscell(item)) 154 | error('input is not a cell'); 155 | end 156 | 157 | dim=size(item); 158 | if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now 159 | item=reshape(item,dim(1),numel(item)/dim(1)); 160 | dim=size(item); 161 | end 162 | bracketlevel=~jsonopt('singletcell',1,varargin{:}); 163 | len=numel(item); % let's handle 1D cell first 164 | if(len>bracketlevel) 165 | if(~isempty(name)) 166 | txt=[N_(checkname(name,varargin{:})) '[']; name=''; 167 | else 168 | txt='['; 169 | end 170 | elseif(len==0) 171 | if(~isempty(name)) 172 | txt=[N_(checkname(name,varargin{:})) 'Z']; name=''; 173 | else 174 | txt='Z'; 175 | end 176 | end 177 | for j=1:dim(2) 178 | if(dim(1)>1) 179 | txt=[txt '[']; 180 | end 181 | for i=1:dim(1) 182 | txt=[txt obj2ubjson(name,item{i,j},level+(len>bracketlevel),varargin{:})]; 183 | end 184 | if(dim(1)>1) 185 | txt=[txt ']']; 186 | end 187 | end 188 | if(len>bracketlevel) 189 | txt=[txt ']']; 190 | end 191 | 192 | %%------------------------------------------------------------------------- 193 | function txt=struct2ubjson(name,item,level,varargin) 194 | txt=''; 195 | if(~isstruct(item)) 196 | error('input is not a struct'); 197 | end 198 | dim=size(item); 199 | if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now 200 | item=reshape(item,dim(1),numel(item)/dim(1)); 201 | dim=size(item); 202 | end 203 | len=numel(item); 204 | forcearray= (len>1 || (jsonopt('SingletArray',0,varargin{:})==1 && level>0)); 205 | 206 | if(~isempty(name)) 207 | if(forcearray) 208 | txt=[N_(checkname(name,varargin{:})) '[']; 209 | end 210 | else 211 | if(forcearray) 212 | txt='['; 213 | end 214 | end 215 | for j=1:dim(2) 216 | if(dim(1)>1) 217 | txt=[txt '[']; 218 | end 219 | for i=1:dim(1) 220 | names = fieldnames(item(i,j)); 221 | if(~isempty(name) && len==1 && ~forcearray) 222 | txt=[txt N_(checkname(name,varargin{:})) '{']; 223 | else 224 | txt=[txt '{']; 225 | end 226 | if(~isempty(names)) 227 | for e=1:length(names) 228 | txt=[txt obj2ubjson(names{e},item(i,j).(names{e}),... 229 | level+(dim(1)>1)+1+forcearray,varargin{:})]; 230 | end 231 | end 232 | txt=[txt '}']; 233 | end 234 | if(dim(1)>1) 235 | txt=[txt ']']; 236 | end 237 | end 238 | if(forcearray) 239 | txt=[txt ']']; 240 | end 241 | 242 | %%------------------------------------------------------------------------- 243 | function txt=str2ubjson(name,item,level,varargin) 244 | txt=''; 245 | if(~ischar(item)) 246 | error('input is not a string'); 247 | end 248 | item=reshape(item, max(size(item),[1 0])); 249 | len=size(item,1); 250 | 251 | if(~isempty(name)) 252 | if(len>1) 253 | txt=[N_(checkname(name,varargin{:})) '[']; 254 | end 255 | else 256 | if(len>1) 257 | txt='['; 258 | end 259 | end 260 | for e=1:len 261 | val=item(e,:); 262 | if(len==1) 263 | obj=[N_(checkname(name,varargin{:})) '' '',S_(val),'']; 264 | if(isempty(name)) 265 | obj=['',S_(val),'']; 266 | end 267 | txt=[txt,'',obj]; 268 | else 269 | txt=[txt,'',['',S_(val),'']]; 270 | end 271 | end 272 | if(len>1) 273 | txt=[txt ']']; 274 | end 275 | 276 | %%------------------------------------------------------------------------- 277 | function txt=mat2ubjson(name,item,level,varargin) 278 | if(~isnumeric(item) && ~islogical(item)) 279 | error('input is not an array'); 280 | end 281 | 282 | if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... 283 | (isempty(item) && any(size(item))) ||jsonopt('ArrayToStruct',0,varargin{:})) 284 | cid=I_(uint32(max(size(item)))); 285 | if(isempty(name)) 286 | txt=['{' N_('_ArrayType_'),S_(class(item)),N_('_ArraySize_'),I_a(size(item),cid(1)) ]; 287 | else 288 | if(isempty(item)) 289 | txt=[N_(checkname(name,varargin{:})),'Z']; 290 | return; 291 | else 292 | txt=[N_(checkname(name,varargin{:})),'{',N_('_ArrayType_'),S_(class(item)),N_('_ArraySize_'),I_a(size(item),cid(1))]; 293 | end 294 | end 295 | else 296 | if(isempty(name)) 297 | txt=matdata2ubjson(item,level+1,varargin{:}); 298 | else 299 | if(numel(item)==1 && jsonopt('SingletArray',0,varargin{:})==0) 300 | numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); 301 | txt=[N_(checkname(name,varargin{:})) numtxt]; 302 | else 303 | txt=[N_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})]; 304 | end 305 | end 306 | return; 307 | end 308 | if(issparse(item)) 309 | [ix,iy]=find(item); 310 | data=full(item(find(item))); 311 | if(~isreal(item)) 312 | data=[real(data(:)),imag(data(:))]; 313 | if(size(item,1)==1) 314 | % Kludge to have data's 'transposedness' match item's. 315 | % (Necessary for complex row vector handling below.) 316 | data=data'; 317 | end 318 | txt=[txt,N_('_ArrayIsComplex_'),'T']; 319 | end 320 | txt=[txt,N_('_ArrayIsSparse_'),'T']; 321 | if(size(item,1)==1) 322 | % Row vector, store only column indices. 323 | txt=[txt,N_('_ArrayData_'),... 324 | matdata2ubjson([iy(:),data'],level+2,varargin{:})]; 325 | elseif(size(item,2)==1) 326 | % Column vector, store only row indices. 327 | txt=[txt,N_('_ArrayData_'),... 328 | matdata2ubjson([ix,data],level+2,varargin{:})]; 329 | else 330 | % General case, store row and column indices. 331 | txt=[txt,N_('_ArrayData_'),... 332 | matdata2ubjson([ix,iy,data],level+2,varargin{:})]; 333 | end 334 | else 335 | if(isreal(item)) 336 | txt=[txt,N_('_ArrayData_'),... 337 | matdata2ubjson(item(:)',level+2,varargin{:})]; 338 | else 339 | txt=[txt,N_('_ArrayIsComplex_'),'T']; 340 | txt=[txt,N_('_ArrayData_'),... 341 | matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; 342 | end 343 | end 344 | txt=[txt,'}']; 345 | 346 | %%------------------------------------------------------------------------- 347 | function txt=matlabobject2ubjson(name,item,level,varargin) 348 | if numel(item) == 0 %empty object 349 | st = struct(); 350 | else 351 | % "st = struct(item);" would produce an inmutable warning, because it 352 | % make the protected and private properties visible. Instead we get the 353 | % visible properties 354 | propertynames = properties(item); 355 | for p = 1:numel(propertynames) 356 | for o = numel(item):-1:1 % aray of objects 357 | st(o).(propertynames{p}) = item(o).(propertynames{p}); 358 | end 359 | end 360 | end 361 | txt=struct2ubjson(name,st,level,varargin{:}); 362 | 363 | %%------------------------------------------------------------------------- 364 | function txt=matdata2ubjson(mat,level,varargin) 365 | if(isempty(mat)) 366 | txt='Z'; 367 | return; 368 | end 369 | type=''; 370 | hasnegtive=(mat<0); 371 | if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0))) 372 | if(isempty(hasnegtive)) 373 | if(max(mat(:))<=2^8) 374 | type='U'; 375 | end 376 | end 377 | if(isempty(type)) 378 | % todo - need to consider negative ones separately 379 | id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]); 380 | if(isempty(id~=0)) 381 | error('high-precision data is not yet supported'); 382 | end 383 | key='iIlL'; 384 | type=key(id~=0); 385 | end 386 | txt=[I_a(mat(:),type,size(mat))]; 387 | elseif(islogical(mat)) 388 | logicalval='FT'; 389 | if(numel(mat)==1) 390 | txt=logicalval(mat+1); 391 | else 392 | txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')]; 393 | end 394 | else 395 | if(numel(mat)==1) 396 | txt=['[' D_(mat) ']']; 397 | else 398 | txt=D_a(mat(:),'D',size(mat)); 399 | end 400 | end 401 | 402 | %txt=regexprep(mat2str(mat),'\s+',','); 403 | %txt=regexprep(txt,';',sprintf('],[')); 404 | % if(nargin>=2 && size(mat,1)>1) 405 | % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); 406 | % end 407 | if(any(isinf(mat(:)))) 408 | txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); 409 | end 410 | if(any(isnan(mat(:)))) 411 | txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); 412 | end 413 | 414 | %%------------------------------------------------------------------------- 415 | function newname=checkname(name,varargin) 416 | isunpack=jsonopt('UnpackHex',1,varargin{:}); 417 | newname=name; 418 | if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) 419 | return 420 | end 421 | if(isunpack) 422 | isoct=jsonopt('IsOctave',0,varargin{:}); 423 | if(~isoct) 424 | newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); 425 | else 426 | pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); 427 | pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); 428 | if(isempty(pos)) 429 | return; 430 | end 431 | str0=name; 432 | pos0=[0 pend(:)' length(name)]; 433 | newname=''; 434 | for i=1:length(pos) 435 | newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; 436 | end 437 | if(pos(end)~=length(name)) 438 | newname=[newname str0(pos0(end-1)+1:pos0(end))]; 439 | end 440 | end 441 | end 442 | %%------------------------------------------------------------------------- 443 | function val=N_(str) 444 | val=[I_(int32(length(str))) str]; 445 | %%------------------------------------------------------------------------- 446 | function val=S_(str) 447 | if(length(str)==1) 448 | val=['C' str]; 449 | else 450 | val=['S' I_(int32(length(str))) str]; 451 | end 452 | %%------------------------------------------------------------------------- 453 | function val=I_(num) 454 | if(~isinteger(num)) 455 | error('input is not an integer'); 456 | end 457 | if(num>=0 && num<255) 458 | val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')]; 459 | return; 460 | end 461 | key='iIlL'; 462 | cid={'int8','int16','int32','int64'}; 463 | for i=1:4 464 | if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1))) 465 | val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')]; 466 | return; 467 | end 468 | end 469 | error('unsupported integer'); 470 | 471 | %%------------------------------------------------------------------------- 472 | function val=D_(num) 473 | if(~isfloat(num)) 474 | error('input is not a float'); 475 | end 476 | 477 | if(isa(num,'single')) 478 | val=['d' data2byte(swapbytes(num),'uint8')]; 479 | else 480 | val=['D' data2byte(swapbytes(num),'uint8')]; 481 | end 482 | %%------------------------------------------------------------------------- 483 | function data=I_a(num,type,dim,format) 484 | id=find(ismember('iUIlL',type)); 485 | 486 | if(id==0) 487 | error('unsupported integer array'); 488 | end 489 | 490 | % based on UBJSON specs, all integer types are stored in big endian format 491 | 492 | if(id==1) 493 | data=data2byte(swapbytes(int8(num)),'uint8'); 494 | blen=1; 495 | elseif(id==2) 496 | data=data2byte(swapbytes(uint8(num)),'uint8'); 497 | blen=1; 498 | elseif(id==3) 499 | data=data2byte(swapbytes(int16(num)),'uint8'); 500 | blen=2; 501 | elseif(id==4) 502 | data=data2byte(swapbytes(int32(num)),'uint8'); 503 | blen=4; 504 | elseif(id==5) 505 | data=data2byte(swapbytes(int64(num)),'uint8'); 506 | blen=8; 507 | end 508 | 509 | if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) 510 | format='opt'; 511 | end 512 | if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) 513 | if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) 514 | cid=I_(uint32(max(dim))); 515 | data=['$' type '#' I_a(dim,cid(1)) data(:)']; 516 | else 517 | data=['$' type '#' I_(int32(numel(data)/blen)) data(:)']; 518 | end 519 | data=['[' data(:)']; 520 | else 521 | data=reshape(data,blen,numel(data)/blen); 522 | data(2:blen+1,:)=data; 523 | data(1,:)=type; 524 | data=data(:)'; 525 | data=['[' data(:)' ']']; 526 | end 527 | %%------------------------------------------------------------------------- 528 | function data=D_a(num,type,dim,format) 529 | id=find(ismember('dD',type)); 530 | 531 | if(id==0) 532 | error('unsupported float array'); 533 | end 534 | 535 | if(id==1) 536 | data=data2byte(swapbytes(single(num)),'uint8'); 537 | elseif(id==2) 538 | data=data2byte(swapbytes(double(num)),'uint8'); 539 | end 540 | 541 | if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) 542 | format='opt'; 543 | end 544 | if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) 545 | if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) 546 | cid=I_(uint32(max(dim))); 547 | data=['$' type '#' I_a(dim,cid(1)) data(:)']; 548 | else 549 | data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)']; 550 | end 551 | data=['[' data]; 552 | else 553 | data=reshape(data,(id*4),length(data)/(id*4)); 554 | data(2:(id*4+1),:)=data; 555 | data(1,:)=type; 556 | data=data(:)'; 557 | data=['[' data(:)' ']']; 558 | end 559 | %%------------------------------------------------------------------------- 560 | function bytes=data2byte(varargin) 561 | bytes=typecast(varargin{:}); 562 | bytes=bytes(:)'; 563 | -------------------------------------------------------------------------------- /jsonlab-1.5/struct2jdata.m: -------------------------------------------------------------------------------- 1 | function newdata=struct2jdata(data,varargin) 2 | % 3 | % newdata=struct2jdata(data,opt,...) 4 | % 5 | % convert a JData object (in the form of a struct array) into an array 6 | % 7 | % authors:Qianqian Fang (q.fang neu.edu) 8 | % 9 | % input: 10 | % data: a struct array. If data contains JData keywords in the first 11 | % level children, these fields are parsed and regrouped into a 12 | % data object (arrays, trees, graphs etc) based on JData 13 | % specification. The JData keywords are 14 | % "_ArrayType_", "_ArraySize_", "_ArrayData_" 15 | % "_ArrayIsSparse_", "_ArrayIsComplex_" 16 | % opt: (optional) a list of 'Param',value pairs for additional options 17 | % The supported options include 18 | % 'Recursive', if set to 1, will apply the conversion to 19 | % every child; 0 to disable 20 | % 21 | % output: 22 | % newdata: the covnerted data if the input data does contain a JData 23 | % structure; otherwise, the same as the input. 24 | % 25 | % examples: 26 | % obj=struct('_ArrayType_','double','_ArraySize_',[2 3], 27 | % '_ArrayIsSparse_',1 ,'_ArrayData_',null); 28 | % ubjdata=struct2jdata(obj); 29 | % 30 | % license: 31 | % BSD License, see LICENSE_BSD.txt files for details 32 | % 33 | % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) 34 | % 35 | 36 | fn=fieldnames(data); 37 | newdata=data; 38 | len=length(data); 39 | if(jsonopt('Recursive',0,varargin{:})==1) 40 | for i=1:length(fn) % depth-first 41 | for j=1:len 42 | if(isstruct(getfield(data(j),fn{i}))) 43 | newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); 44 | end 45 | end 46 | end 47 | end 48 | if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) 49 | newdata=cell(len,1); 50 | for j=1:len 51 | ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); 52 | iscpx=0; 53 | if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) 54 | if(data(j).x0x5F_ArrayIsComplex_) 55 | iscpx=1; 56 | end 57 | end 58 | if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) 59 | if(data(j).x0x5F_ArrayIsSparse_) 60 | if(~isempty(strmatch('x0x5F_ArraySize_',fn))) 61 | dim=double(data(j).x0x5F_ArraySize_); 62 | if(iscpx && size(ndata,2)==4-any(dim==1)) 63 | ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); 64 | end 65 | if isempty(ndata) 66 | % All-zeros sparse 67 | ndata=sparse(dim(1),prod(dim(2:end))); 68 | elseif dim(1)==1 69 | % Sparse row vector 70 | ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); 71 | elseif dim(2)==1 72 | % Sparse column vector 73 | ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); 74 | else 75 | % Generic sparse array. 76 | ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); 77 | end 78 | else 79 | if(iscpx && size(ndata,2)==4) 80 | ndata(:,3)=complex(ndata(:,3),ndata(:,4)); 81 | end 82 | ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); 83 | end 84 | end 85 | elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) 86 | if(iscpx && size(ndata,2)==2) 87 | ndata=complex(ndata(:,1),ndata(:,2)); 88 | end 89 | ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); 90 | end 91 | newdata{j}=ndata; 92 | end 93 | if(len==1) 94 | newdata=newdata{1}; 95 | end 96 | end -------------------------------------------------------------------------------- /jsonlab-1.5/varargin2struct.m: -------------------------------------------------------------------------------- 1 | function opt=varargin2struct(varargin) 2 | % 3 | % opt=varargin2struct('param1',value1,'param2',value2,...) 4 | % or 5 | % opt=varargin2struct(...,optstruct,...) 6 | % 7 | % convert a series of input parameters into a structure 8 | % 9 | % authors:Qianqian Fang (q.fang neu.edu) 10 | % date: 2012/12/22 11 | % 12 | % input: 13 | % 'param', value: the input parameters should be pairs of a string and a value 14 | % optstruct: if a parameter is a struct, the fields will be merged to the output struct 15 | % 16 | % output: 17 | % opt: a struct where opt.param1=value1, opt.param2=value2 ... 18 | % 19 | % license: 20 | % BSD License, see LICENSE_BSD.txt files for details 21 | % 22 | % -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) 23 | % 24 | 25 | len=length(varargin); 26 | opt=struct; 27 | if(len==0) return; end 28 | i=1; 29 | while(i<=len) 30 | if(isstruct(varargin{i})) 31 | opt=mergestruct(opt,varargin{i}); 32 | elseif(ischar(varargin{i}) && i 33 | 34 | try 35 | fc = com.mathworks.mlwidgets.favoritecommands.FavoriteCommands.getInstance(); 36 | 37 | newFavoriteCommand = com.mathworks.mlwidgets.favoritecommands.FavoriteCommandProperties(); 38 | newFavoriteCommand.setLabel('Insert Snippet'); 39 | newFavoriteCommand.setCategoryLabel('MATLAB SNIPPETS'); 40 | newFavoriteCommand.setCode(code); 41 | newFavoriteCommand.setIsOnQuickToolBar(true); 42 | newFavoriteCommand.setIconName(iconFileName); 43 | newFavoriteCommand.setIconPath(iconPath); 44 | fc.addCommand(newFavoriteCommand); 45 | %msgbox('Quick lunch icon successfully added. Try to trigger it by ALT+1.','Matlab Snippets'); 46 | catch 47 | f = warndlg(['Adding the quick lunch icon failed. ' manualInstallationRequest]); 48 | uiwait(f); 49 | end 50 | end -------------------------------------------------------------------------------- /utils/editor/clearWordAtCaretPosion.m: -------------------------------------------------------------------------------- 1 | function clearWordAtCaretPosion() 2 | [wordAtCaret,i1,i2] = getWordAtCaretPosition(); 3 | if ~isempty(wordAtCaret) 4 | activeEditor = getActiveEditor(); 5 | % --- Select the word 6 | activeEditor.JavaEditor.setSelection(i1-1,i2); 7 | % --- Insert empty text to delete the selected word 8 | activeEditor.JavaEditor.insertTextAtCaret(''); 9 | end 10 | end -------------------------------------------------------------------------------- /utils/editor/getActiveEditor.m: -------------------------------------------------------------------------------- 1 | function activeEditor = getActiveEditor() 2 | % GETACTIVEEDITOR gets the active document in the editor. 3 | % 4 | % Syntax: 5 | % activeEditor = getActiveEditor() 6 | % 7 | % Outputs: 8 | % activeEditor - active editor object (matlab.desktop.editor.Document) 9 | % 10 | % Based on: 11 | % https://nl.mathworks.com/matlabcentral/fileexchange/41704-insert-a-piece-of-code-a-snippet-in-the-matlab-editor 12 | % 13 | if verLessThan('matlab', '8.1.0') 14 | activeEditor = editorservices.getActive; 15 | else 16 | activeEditor = matlab.desktop.editor.getActive; 17 | end 18 | end 19 | 20 | -------------------------------------------------------------------------------- /utils/editor/getLineAtCaretPosition.m: -------------------------------------------------------------------------------- 1 | function [lineAtCaret,i1,i2] = getLineAtCaretPosition() 2 | % Get a word at the current editor caret positon. 3 | % 4 | lineAtCaret = ''; 5 | i1 = []; 6 | i2 = []; 7 | 8 | activeEditor = getActiveEditor(); 9 | if ~isempty(activeEditor) 10 | caretPosition = activeEditor.JavaEditor.getCaretPosition; 11 | text = activeEditor.Text; 12 | 13 | if isempty(text) 14 | % --- Empty document 15 | else 16 | % --- Text before caret 17 | [startIndex,endIndex] = regexp(text(1:caretPosition),'[^\n]*$'); 18 | if isempty(startIndex) 19 | % --- Caret at the line begining 20 | else 21 | lineAtCaret = [ lineAtCaret text(startIndex(1):endIndex(1)) ]; 22 | i1 = startIndex(1); 23 | i2 = endIndex(1); 24 | end 25 | % --- Text after caret 26 | [startIndex,endIndex] = regexp(text(caretPosition+1:end),'^[^\n]*'); 27 | if isempty(lineAtCaret) 28 | if isempty(startIndex) 29 | % --- Caret on an empty line 30 | else 31 | % --- Caret at the begining of a non-empty line 32 | lineAtCaret = [ lineAtCaret text(caretPosition+(startIndex(1):endIndex(1))) ]; 33 | i1 = caretPosition+startIndex(1); 34 | i2 = caretPosition+endIndex(1); 35 | end 36 | else 37 | if isempty(startIndex) 38 | % --- Caret at the line end 39 | else 40 | lineAtCaret = [ lineAtCaret text(caretPosition+(startIndex(1):endIndex(1))) ]; 41 | i2 = caretPosition+endIndex(1); 42 | end 43 | end 44 | 45 | end 46 | end 47 | end -------------------------------------------------------------------------------- /utils/editor/getWordAtCaretPosition.m: -------------------------------------------------------------------------------- 1 | function [wordAtCaret,i1,i2] = getWordAtCaretPosition() 2 | % Get a word at the current editor caret positon. 3 | % 4 | wordAtCaret = ''; 5 | i1 = []; 6 | i2 = []; 7 | 8 | activeEditor = getActiveEditor(); 9 | if ~isempty(activeEditor) 10 | caretPosition = activeEditor.JavaEditor.getCaretPosition; 11 | text = activeEditor.Text; 12 | 13 | [startIndex,endIndex] = regexp(text(1:caretPosition),'\S*$'); 14 | if ~isempty(startIndex) 15 | wordAtCaret = [ wordAtCaret text(startIndex(1):endIndex(1)) ]; 16 | i1 = startIndex(1); 17 | i2 = endIndex(1); 18 | end 19 | [startIndex,endIndex] = regexp(text(caretPosition+1:end),'^\S*'); 20 | if ~isempty(startIndex) 21 | wordAtCaret = [ wordAtCaret text(caretPosition+(startIndex(1):endIndex(1))) ]; 22 | if isempty(i1) 23 | i1 = caretPosition+startIndex(1); 24 | end 25 | i2 = caretPosition+endIndex(1); 26 | end 27 | end 28 | end -------------------------------------------------------------------------------- /utils/findMatchingClosingBracket.m: -------------------------------------------------------------------------------- 1 | function closingBracketIndex = findMatchingClosingBracket(str,closingBracket) 2 | % FINDMATCHINGCLOSINGBRACKET Finds matching closing bracket '}' in the character 3 | % vector. 4 | % 5 | % Syntax: 6 | % closingBracketIndex = findMatchingClosingBracket(str,bracket) 7 | % 8 | % Inputs: 9 | % str .............. searched character array 10 | % closingBracket ... closing bracket character (')','}','>',']') 11 | % (optional, default = '}') 12 | % 13 | % Outputs: 14 | % clsingBracketIndex ... closing bracket index in "str" input argument, 15 | % returns [] if no closing bracket was found 16 | % 17 | % Examples: 18 | % 19 | % >> findMatchingClosingBracket('text}') 20 | % ans = 21 | % 5 22 | % 23 | % >> findMatchingClosingBracket('{text}}') 24 | % ans = 25 | % 7 26 | % 27 | % >> findMatchingClosingBracket('{text}') 28 | % ans = 29 | % Empty matrix: 1-by-0 30 | % 31 | if nargin<2 32 | closingBracket = '}'; 33 | end 34 | 35 | % --- Determine opening bracket character 36 | openingBrackets = '({<['; 37 | closingBrackets = ')}>]'; 38 | ind = find(closingBrackets==closingBracket,1); 39 | if isempty(ind) 40 | closingBracketsList = strjoin(arrayfun(@(c)['"' c '"'],closingBrackets,'UniformOutput',false),', '); 41 | error(['Cannot find the closing bracket character "' closingBracket ... 42 | '" in the list of supported closing bracket types: ' closingBracketsList '.']); 43 | end 44 | openingBracket = openingBrackets(ind); 45 | 46 | openingBracketIndicators = (str==openingBracket); 47 | closingBracketIndicators = (str==closingBracket); 48 | closingBracketIndex = find( ... 49 | cumsum(closingBracketIndicators) > cumsum(openingBracketIndicators), ... 50 | 1); 51 | end -------------------------------------------------------------------------------- /utils/findjobj_fast.m: -------------------------------------------------------------------------------- 1 | function jComponent = findjobj_fast(hFig,toolTipText) 2 | % Based on Yair Altman "findjobj" 3 | drawnow; pause(0.02); 4 | oldWarn = warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame'); 5 | warning('off','MATLAB:ui:javaframe:PropertyToBeRemoved'); 6 | jframe = get(hFig,'JavaFrame'); 7 | warning(oldWarn); 8 | jContainer = jframe.getFigurePanelContainer.getComponent(0); 9 | jComponent = findComponent(jContainer,toolTipText); 10 | 11 | function jComponent = findComponent(jContainer,toolTipText) 12 | jComponent = []; 13 | containerToolTipText = ''; 14 | try 15 | containerToolTipText = get(jContainer,'ToolTipText'); 16 | catch 17 | end 18 | if strcmp(containerToolTipText,toolTipText) 19 | jComponent = handle(jContainer,'callbackproperties'); 20 | else 21 | for i = 1 : jContainer.getComponentCount 22 | jComponent = findComponent(jContainer.getComponent(i-1),toolTipText); 23 | if ~isempty(jComponent) 24 | return 25 | end 26 | end 27 | end 28 | end 29 | end -------------------------------------------------------------------------------- /utils/formatting/alignCharacter.m: -------------------------------------------------------------------------------- 1 | function text = alignCharacter(text,alignmentCharacter) 2 | % ALIGNCHARACTER aligns selected character in cell array of character vectors by 3 | % adding spaces before the character. 4 | % 5 | % Syntax: 6 | % text = alignCharacter(text,alignmentCharacter) 7 | % 8 | % Inputs: 9 | % text - cell array of character vectors 10 | % alignmentCharacter - single that will be alighned (e.g. '%','=') 11 | % 12 | % Outputs 13 | % textu - resulting cell array of character vectors 14 | % 15 | rows = strsplit(text,'\n'); 16 | IComment = cell(size(rows)); 17 | for i = 1 : length(rows) 18 | IComment{i} = find(rows{i}==alignmentCharacter,1); 19 | end 20 | IComment_ = cell2mat(IComment); 21 | if ~isempty(IComment_) 22 | icomment = max(IComment_); 23 | for i = 1 : length(rows) 24 | if ~isempty(IComment{i}) 25 | rows{i} = [ ... 26 | rows{i}(1:IComment{i}-1) ... 27 | repmat(' ',1,icomment-IComment{i}) ... 28 | rows{i}(IComment{i}:end) ]; 29 | end 30 | end 31 | end 32 | text = strjoin(rows,'\n'); 33 | end -------------------------------------------------------------------------------- /utils/formatting/capitalize.m: -------------------------------------------------------------------------------- 1 | function str = capitalize(str) 2 | % CAPITALIZE capitalizes the first character of a characeter vector. 3 | if ischar(str) && length(str)>=1 4 | str = [ upper(str(1)) str(2:end) ]; 5 | end 6 | end -------------------------------------------------------------------------------- /utils/formatting/fillEditorLineEndByCharacter.m: -------------------------------------------------------------------------------- 1 | function lineEndStr = fillEditorLineEndByCharacter(str,fillChar) 2 | 3 | % --- Matlab editor line limit 4 | if verLessThan('matlab','9.4') % R2018a 5 | lineColumn = 80; 6 | else 7 | matlabSettings = settings(); 8 | lineColumn = matlabSettings.matlab.editor.displaysettings.linelimit.LineColumn.ActiveValue; 9 | end 10 | 11 | % --- Get current line indentation lengths 12 | lineAtCaret = getLineAtCaretPosition(); 13 | tokens = regexp(lineAtCaret,'^([ ]*)','tokens','once'); 14 | if isempty(tokens) 15 | indentationStr = ''; 16 | else 17 | indentationStr = tokens{1}; 18 | end 19 | indentationLength = length(indentationStr); 20 | 21 | % --- Word at caret 22 | wordAtCaret = getWordAtCaretPosition(); 23 | 24 | nFill = lineColumn - indentationLength - length(str) + length(wordAtCaret); 25 | lineEndStr = repmat(fillChar,1,nFill); 26 | 27 | end -------------------------------------------------------------------------------- /utils/formatting/singleSpace.m: -------------------------------------------------------------------------------- 1 | function text = singleSpace(text,compact) 2 | % SINGLESPACE forces a single space after '(', ',' and before ')'. If compact 3 | % flag is true that it forces no space after '(', a single space after ',' and 4 | % no space before ')'. 5 | % 6 | % Syntax: 7 | % text = singleSpace(text,targetSymbols) 8 | % 9 | % Inputs: 10 | % text ... source text (character array) 11 | % compact ... compact format flag (logical) 12 | % 13 | % Examples: 14 | % >> singleSpace('fce(in1,arg2,arg3)') 15 | % ans = 16 | % 'fce( in1, arg2, arg3 )' 17 | % 18 | % >> singleSpace('fce( in1 , arg2 , arg3 )') 19 | % ans = 20 | % 'fce( in1, arg2, arg3 )' 21 | % 22 | % >> singleSpace('fce( in1 , arg2 , arg3 )',true) 23 | % ans = 24 | % 'fce( in1, arg2, arg3 )' 25 | % 26 | if nargin<2 27 | compact = false; 28 | end 29 | % --- 30 | expression = '\([ ]*'; 31 | if compact 32 | replace = '\('; 33 | else 34 | replace = '\( '; 35 | end 36 | text = regexprep(text,expression,replace); 37 | % --- 38 | expression = '[ ]*,[ ]*'; 39 | replace = ', '; 40 | text = regexprep(text,expression,replace); 41 | % --- 42 | expression = '[ ]*\)'; 43 | if compact 44 | replace = '\)'; 45 | else 46 | replace = ' \)'; 47 | end 48 | text = regexprep(text,expression,replace); 49 | end -------------------------------------------------------------------------------- /utils/formatting/strAbs.m: -------------------------------------------------------------------------------- 1 | function str = strAbs(str) 2 | % STRABS computes the absolute value of a number in a character vector. 3 | % Returns the input argument if coversion fails. 4 | % 5 | % Syntax: 6 | % str = strAbsoluteValue(str) 7 | % 8 | % Inputs: 9 | % str - input number (character vector) 10 | % 11 | % Outputs: 12 | % str - output number (character vector) 13 | % 14 | x = str2double(str); 15 | if ~isnan(x) 16 | x = abs(x); 17 | str = num2str(x); 18 | end 19 | end -------------------------------------------------------------------------------- /utils/getAppID.m: -------------------------------------------------------------------------------- 1 | function id = getAppID(appName) 2 | % GETAPPID returns Matlab App ID from its name. 3 | % 4 | % Inputs: 5 | % appName ... App name (character vector) 6 | % 7 | % Outputs: 8 | % id ........ unique App ID (character vector) 9 | % 10 | id = []; 11 | appinfo = matlab.apputil.getInstalledAppInfo; 12 | if ~isempty(appinfo) 13 | ind = find(strcmp({appinfo.name},appName)); 14 | if length(ind)==1 15 | id = appinfo(ind).id; 16 | else 17 | % --- multiple matches - return the last ID from a sorted list 18 | ID = {appinfo(ind).id}; 19 | ID = sort(ID); 20 | id = ID(end); 21 | end 22 | end 23 | 24 | -------------------------------------------------------------------------------- /utils/regexp/decomposeRegexpPlaceholder.m: -------------------------------------------------------------------------------- 1 | function tokens = decomposeRegexpPlaceholder(placeholder) 2 | indSlash = find(placeholder=='/'); 3 | % --- Indicate slashes that are enclosed in the { } brackets 4 | isEnclosed = false(size(indSlash)); 5 | for i = 1 : length(indSlash) 6 | nLeftOpeningBrackets = sum( placeholder(1:indSlash(i)-1) == '{' ); 7 | nLeftClosingBrackets = sum( placeholder(1:indSlash(i)-1) == '}' ); 8 | isEnclosed(i) = (nLeftOpeningBrackets~=nLeftClosingBrackets); 9 | end 10 | % --- Select non-enclosed slashes only 11 | indSlash = indSlash(~isEnclosed); 12 | % --- Split to tokens 13 | tokens = {}; 14 | i1 = 1; 15 | for i = 1 : length(indSlash) 16 | i2 = indSlash(i)-1; 17 | tokens{end+1} = placeholder(i1:i2); 18 | i1 = indSlash(i)+1; 19 | end 20 | i2 = length(placeholder); 21 | tokens{end+1} = placeholder(i1:i2); 22 | end -------------------------------------------------------------------------------- /utils/regexp/passFirstIfNotEqual.m: -------------------------------------------------------------------------------- 1 | function out = passFirstIfNotEqual(var1,var2,in1,in2) 2 | if isequal(var1,var2) 3 | out = in2; 4 | else 5 | out = in1; 6 | end 7 | 8 | -------------------------------------------------------------------------------- /utils/regexp/passIfEqual.m: -------------------------------------------------------------------------------- 1 | function out = passIfEqual(var1,var2,in) 2 | if isequal(var1,var2) 3 | out = in; 4 | else 5 | out = ''; 6 | end 7 | 8 | -------------------------------------------------------------------------------- /utils/regexp/passIfNotEmpty.m: -------------------------------------------------------------------------------- 1 | function out = passIfNotEmpty(arg,in) 2 | if isempty(arg) 3 | out = ''; 4 | else 5 | out = in; 6 | end 7 | 8 | -------------------------------------------------------------------------------- /utils/regexp/passIfNotEqual.m: -------------------------------------------------------------------------------- 1 | function out = passIfNotEqual(var1,var2,in) 2 | if isequal(var1,var2) 3 | out = ''; 4 | else 5 | out = in; 6 | end 7 | 8 | -------------------------------------------------------------------------------- /utils/regexp/textMate2regexprep.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trnkap/matlab-snippets/6a912cf1d27136952524ed40ba2ceb2c80e1d674/utils/regexp/textMate2regexprep.m --------------------------------------------------------------------------------