text.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. /**
  2. * @license
  3. * Visual Blocks Language
  4. *
  5. * Copyright 2012 Google Inc.
  6. * https://developers.google.com/blockly/
  7. *
  8. * Licensed under the Apache License, Version 2.0 (the "License");
  9. * you may not use this file except in compliance with the License.
  10. * You may obtain a copy of the License at
  11. *
  12. * http://www.apache.org/licenses/LICENSE-2.0
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS,
  16. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. */
  20. /**
  21. * @fileoverview Generating Python for text blocks.
  22. * @author q.neutron@gmail.com (Quynh Neutron)
  23. */
  24. 'use strict';
  25. goog.provide('Blockly.Python.texts');
  26. goog.require('Blockly.Python');
  27. Blockly.Python['text'] = function(block) {
  28. // Text value.
  29. var code = Blockly.Python.quote_(block.getFieldValue('TEXT'));
  30. return [code, Blockly.Python.ORDER_ATOMIC];
  31. };
  32. Blockly.Python['text_join'] = function(block) {
  33. // Create a string made up of any number of elements of any type.
  34. //Should we allow joining by '-' or ',' or any other characters?
  35. switch (block.itemCount_) {
  36. case 0:
  37. return ['\'\'', Blockly.Python.ORDER_ATOMIC];
  38. break;
  39. case 1:
  40. var element = Blockly.Python.valueToCode(block, 'ADD0',
  41. Blockly.Python.ORDER_NONE) || '\'\'';
  42. var code = 'str(' + element + ')';
  43. return [code, Blockly.Python.ORDER_FUNCTION_CALL];
  44. break;
  45. case 2:
  46. var element0 = Blockly.Python.valueToCode(block, 'ADD0',
  47. Blockly.Python.ORDER_NONE) || '\'\'';
  48. var element1 = Blockly.Python.valueToCode(block, 'ADD1',
  49. Blockly.Python.ORDER_NONE) || '\'\'';
  50. var code = 'str(' + element0 + ') + str(' + element1 + ')';
  51. return [code, Blockly.Python.ORDER_ADDITIVE];
  52. break;
  53. default:
  54. var elements = [];
  55. for (var i = 0; i < block.itemCount_; i++) {
  56. elements[i] = Blockly.Python.valueToCode(block, 'ADD' + i,
  57. Blockly.Python.ORDER_NONE) || '\'\'';
  58. }
  59. var tempVar = Blockly.Python.variableDB_.getDistinctName('x',
  60. Blockly.Variables.NAME_TYPE);
  61. var code = '\'\'.join([str(' + tempVar + ') for ' + tempVar + ' in [' +
  62. elements.join(', ') + ']])';
  63. return [code, Blockly.Python.ORDER_FUNCTION_CALL];
  64. }
  65. };
  66. Blockly.Python['text_append'] = function(block) {
  67. // Append to a variable in place.
  68. var varName = Blockly.Python.variableDB_.getName(block.getFieldValue('VAR'),
  69. Blockly.Variables.NAME_TYPE);
  70. var value = Blockly.Python.valueToCode(block, 'TEXT',
  71. Blockly.Python.ORDER_NONE) || '___';
  72. return varName + ' = str(' + varName + ') + str(' + value + ')\n';
  73. };
  74. Blockly.Python['text_length'] = function(block) {
  75. // Is the string null or array empty?
  76. var value = Blockly.Python.valueToCode(block, 'VALUE',
  77. Blockly.Python.ORDER_NONE) || '___';
  78. return ['len(' + value + ')', Blockly.Python.ORDER_FUNCTION_CALL];
  79. };
  80. Blockly.Python['text_isEmpty'] = function(block) {
  81. // Is the string null or array empty?
  82. var value = Blockly.Python.valueToCode(block, 'VALUE',
  83. Blockly.Python.ORDER_NONE) || '___';
  84. var code = 'not len(' + value + ')';
  85. return [code, Blockly.Python.ORDER_LOGICAL_NOT];
  86. };
  87. Blockly.Python['text_indexOf'] = function(block) {
  88. // Search the text for a substring.
  89. // Should we allow for non-case sensitive???
  90. var operator = block.getFieldValue('END') == 'FIRST' ? 'find' : 'rfind';
  91. var substring = Blockly.Python.valueToCode(block, 'FIND',
  92. Blockly.Python.ORDER_NONE) || '___';
  93. var text = Blockly.Python.valueToCode(block, 'VALUE',
  94. Blockly.Python.ORDER_MEMBER) || '___';
  95. var code = text + '.' + operator + '(' + substring + ') + 1';
  96. return [code, Blockly.Python.ORDER_ADDITIVE];
  97. };
  98. Blockly.Python['text_charAt'] = function(block) {
  99. // Get letter at index.
  100. // Note: Until January 2013 this block did not have the WHERE input.
  101. var where = block.getFieldValue('WHERE') || 'FROM_START';
  102. var text = Blockly.Python.valueToCode(block, 'VALUE',
  103. Blockly.Python.ORDER_MEMBER) || '___';
  104. switch (where) {
  105. case 'FIRST':
  106. var code = text + '[0]';
  107. return [code, Blockly.Python.ORDER_MEMBER];
  108. case 'LAST':
  109. var code = text + '[-1]';
  110. return [code, Blockly.Python.ORDER_MEMBER];
  111. case 'FROM_START':
  112. var at = Blockly.Python.getAdjustedInt(block, 'AT');
  113. var code = text + '[' + at + ']';
  114. return [code, Blockly.Python.ORDER_MEMBER];
  115. case 'FROM_END':
  116. var at = Blockly.Python.getAdjustedInt(block, 'AT', 1, true);
  117. var code = text + '[' + at + ']';
  118. return [code, Blockly.Python.ORDER_MEMBER];
  119. case 'RANDOM':
  120. Blockly.Python.definitions_['import_random'] = 'import random';
  121. var functionName = Blockly.Python.provideFunction_(
  122. 'text_random_letter',
  123. ['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(text):',
  124. ' x = int(random.random() * len(text))',
  125. ' return text[x];']);
  126. code = functionName + '(' + text + ')';
  127. return [code, Blockly.Python.ORDER_FUNCTION_CALL];
  128. }
  129. throw 'Unhandled option (text_charAt).';
  130. };
  131. Blockly.Python['text_getSubstring'] = function(block) {
  132. // Get substring.
  133. var text = Blockly.Python.valueToCode(block, 'STRING',
  134. Blockly.Python.ORDER_MEMBER) || '___';
  135. var where1 = block.getFieldValue('WHERE1');
  136. var where2 = block.getFieldValue('WHERE2');
  137. switch (where1) {
  138. case 'FROM_START':
  139. var at1 = Blockly.Python.getAdjustedInt(block, 'AT1');
  140. if (at1 == '0') {
  141. at1 = '';
  142. }
  143. break;
  144. case 'FROM_END':
  145. var at1 = Blockly.Python.getAdjustedInt(block, 'AT1', 1, true);
  146. break;
  147. case 'FIRST':
  148. var at1 = '';
  149. break;
  150. default:
  151. throw 'Unhandled option (text_getSubstring)';
  152. }
  153. switch (where2) {
  154. case 'FROM_START':
  155. var at2 = Blockly.Python.getAdjustedInt(block, 'AT2', 1);
  156. break;
  157. case 'FROM_END':
  158. var at2 = Blockly.Python.getAdjustedInt(block, 'AT2', 0, true);
  159. // Ensure that if the result calculated is 0 that sub-sequence will
  160. // include all elements as expected.
  161. if (!Blockly.isNumber(String(at2))) {
  162. Blockly.Python.definitions_['import_sys'] = 'import sys';
  163. at2 += ' or sys.maxsize';
  164. } else if (at2 == '0') {
  165. at2 = '';
  166. }
  167. break;
  168. case 'LAST':
  169. var at2 = '';
  170. break;
  171. default:
  172. throw 'Unhandled option (text_getSubstring)';
  173. }
  174. var code = text + '[' + at1 + ' : ' + at2 + ']';
  175. return [code, Blockly.Python.ORDER_MEMBER];
  176. };
  177. Blockly.Python['text_changeCase'] = function(block) {
  178. // Change capitalization.
  179. var OPERATORS = {
  180. 'UPPERCASE': '.upper()',
  181. 'LOWERCASE': '.lower()',
  182. 'TITLECASE': '.title()'
  183. };
  184. var operator = OPERATORS[block.getFieldValue('CASE')];
  185. var text = Blockly.Python.valueToCode(block, 'TEXT',
  186. Blockly.Python.ORDER_MEMBER) || '___';
  187. var code = text + operator;
  188. return [code, Blockly.Python.ORDER_MEMBER];
  189. };
  190. Blockly.Python['text_trim'] = function(block) {
  191. // Trim spaces.
  192. var OPERATORS = {
  193. 'LEFT': '.lstrip()',
  194. 'RIGHT': '.rstrip()',
  195. 'BOTH': '.strip()'
  196. };
  197. var operator = OPERATORS[block.getFieldValue('MODE')];
  198. var text = Blockly.Python.valueToCode(block, 'TEXT',
  199. Blockly.Python.ORDER_MEMBER) || '___';
  200. var code = text + operator;
  201. return [code, Blockly.Python.ORDER_MEMBER];
  202. };
  203. Blockly.Python['text_print'] = function(block) {
  204. // Print statement.
  205. var msg = Blockly.Python.valueToCode(block, 'TEXT',
  206. Blockly.Python.ORDER_NONE) || '___';
  207. return 'print(' + msg + ')\n';
  208. };
  209. Blockly.Python['text_prompt_ext'] = function(block) {
  210. // Prompt function.
  211. var functionName = Blockly.Python.provideFunction_(
  212. 'text_prompt',
  213. ['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(msg):',
  214. ' try:',
  215. ' return raw_input(msg)',
  216. ' except NameError:',
  217. ' return input(msg)']);
  218. if (block.getField('TEXT')) {
  219. // Internal message.
  220. var msg = Blockly.Python.quote_(block.getFieldValue('TEXT'));
  221. } else {
  222. // External message.
  223. var msg = Blockly.Python.valueToCode(block, 'TEXT',
  224. Blockly.Python.ORDER_NONE) || '___';
  225. }
  226. var code = functionName + '(' + msg + ')';
  227. var toNumber = block.getFieldValue('TYPE') == 'NUMBER';
  228. if (toNumber) {
  229. code = 'float(' + code + ')';
  230. }
  231. return [code, Blockly.Python.ORDER_FUNCTION_CALL];
  232. };
  233. Blockly.Python['text_print_multiple'] = function(block) {
  234. // Create a list with any number of elements of any type.
  235. var inner_prints = new Array(block.itemCount_);
  236. for (var n = 0; n < block.itemCount_; n++) {
  237. inner_prints[n] = Blockly.Python.valueToCode(block, 'PRINT' + n,
  238. Blockly.Python.ORDER_NONE) || '___';
  239. }
  240. var code;
  241. if (block.itemCount_ == 1) {
  242. code = 'print(' + inner_prints.join(', ') + ')\n';
  243. } else {
  244. code = 'print(' + inner_prints.join(', ') + ')\n';
  245. }
  246. return code;
  247. };
  248. Blockly.Python['text_prompt'] = Blockly.Python['text_prompt_ext'];
  249. Blockly.Python['text_lower'] = function(block) {
  250. var text_input = Blockly.Python.valueToCode(block,"TEXT_INPUT",Blockly.Python.ORDER_ATOMIC) || '';
  251. var code = text_input + ".lower()"
  252. return [code, Blockly.Python.ORDER_ATOMIC];
  253. }