def run(self, edit): settings = self.view.settings() file_name = self.view.file_name() if file_name is not None and s.get("ignore_sublime_settings"): _, ext = os.path.splitext(file_name) if ext in [".sublime-settings", ".sublime-project"]: return # settings opts = jsbeautifier.default_options() opts.indent_char = " " if settings.get( "translate_tabs_to_spaces") else "\t" opts.indent_size = int( settings.get("tab_size")) if opts.indent_char == " " else 1 opts = jsf_rc.augment_options(opts, s) if s.get("jsbeautifyrc_files"): opts = jsf_rc.augment_options_by_rc_files(opts, self.view) selection = self.view.sel()[0] # formatting a selection/highlighted area if (len(selection) > 0 and s.get("format_selection")): jsf.format_selection(self.view, edit, opts) else: self.change_syntax() jsf.format_whole_file(self.view, edit, opts)
def run(self, edit): settings = self.view.settings() # settings opts = jsbeautifier.default_options() opts.indent_char = " " if settings.get("translate_tabs_to_spaces") else "\t" opts.indent_size = int(settings.get("tab_size")) if opts.indent_char == " " else 1 opts.max_preserve_newlines = s.get("max_preserve_newlines") or 3 opts.preserve_newlines = s.get("preserve_newlines") or True opts.jslint_happy = s.get("jslint_happy") or False opts.brace_style = s.get("brace_style") or "collapse" opts.s = s.get("keep_array_indentation") or False opts.indent_level = s.get("indent_level") or 0 selection = self.view.sel()[0] nwsOffset = self.prev_non_whitespace() # do formatting and replacement replaceRegion = selection if len(selection) > 0 else sublime.Region(0, self.view.size()) res = jsbeautifier.beautify(self.view.substr(replaceRegion), opts) self.view.replace(edit, replaceRegion, res) # re-place cursor offset = self.get_nws_offset(nwsOffset, self.view.substr(sublime.Region(0, self.view.size()))) rc = self.view.rowcol(offset) pt = self.view.text_point(rc[0], rc[1]) sel = self.view.sel() sel.clear() self.view.sel().add(sublime.Region(pt)) self.view.show_at_center(pt)
def to_json(self): """format to node.js module""" del self.nodes[:] dump = self.booster.get_dump(with_stats=True, dump_format='json') for i, tree in enumerate(dump): self.nodes.append([]) self.recursive_bfs(json.loads(tree)) for i, n in enumerate(self.nodes): self.nodes[i] = """{ predict: function(d) { return this.n0(d); },""" + ','.join(n) model_js = """module.exports = {{ predict: function(d) {{ return {}this.boosters.map(function(x) {{ return x.predict(d); }}).reduce(function(a, b) {{return a + b;}})){};}}, boosters: [""" if self.regression: model_js = model_js.format('Math.exp({} + '.format(base_score), '') else: model_js = model_js.format('1 / (1 + Math.exp(-', ')') model_js = model_js + '},'.join(self.nodes) + '}]};\n' # beautify opts = jsbeautifier.default_options() opts.indent_size = 2 model_js = jsbeautifier.beautify(model_js, opts) return model_js
def run(self, edit): settings = self.view.settings() file_name = self.view.file_name() if file_name is not None and s.get("ignore_sublime_settings"): _, ext = os.path.splitext(file_name) if ext in {".sublime-settings", ".sublime-project"}: return # settings opts = jsbeautifier.default_options() opts.indent_char = " " if settings.get("translate_tabs_to_spaces") else "\t" opts.indent_size = int(settings.get("tab_size")) if opts.indent_char == " " else 1 opts = jsf_rc.augment_options(opts, s) if s.get("jsbeautifyrc_files"): opts = jsf_rc.augment_options_by_rc_files(opts, self.view) selection = self.view.sel()[0] # formatting a selection/highlighted area if(len(selection) > 0): jsf.format_selection(self.view, edit, opts) else: jsf.format_whole_file(self.view, edit, opts)
def run(self, edit): settings = self.view.settings() # settings opts = jsbeautifier.default_options() opts.indent_char = " " if settings.get("translate_tabs_to_spaces") else "\t" opts.indent_size = int(settings.get("tab_size")) if opts.indent_char == " " else 1 opts.max_preserve_newlines = s.get("max_preserve_newlines") or 3 opts.preserve_newlines = s.get("preserve_newlines") or True opts.jslint_happy = s.get("jslint_happy") or False opts.brace_style = s.get("brace_style") or "collapse" opts.keep_array_indentation = s.get("keep_array_indentation") or False opts.keep_function_indentation = s.get("keep_function_indentation") or False opts.indent_with_tabs = s.get("indent_with_tabs") or False opts.eval_code = s.get("eval_code") or False opts.unescape_strings = s.get("unescape_strings") or False opts.break_chained_methods = s.get("break_chained_methods") or False selection = self.view.sel()[0] formatSelection = False # formatting a selection/highlighted area if(len(selection) > 0): formatSelection = True if formatSelection: self.format_selection(edit, opts) else: self.format_whole_file(edit, opts)
def insertStuff(self, pre, after, preTwo, afterTwo, type): sels = self.view.sel() nSel = 0 for sel in sels: nSel += 1 for sel in sels: if sel.empty(): continue str = self.view.substr(sel) tab = self.insert_start_line(sel) opts = jsbeautifier.default_options() opts.indent_size = 4; if nSel == 1: str = self.insert_tab_line(str) str = str.replace('\n'+tab, '\n') str = pre + '\n\t' + str + '\n' + after str = self.normalize_line_endings(str) str = jsbeautifier.beautify(str, opts) self.view.run_command('insert_snippet', {"contents": str}) else: str = self.insert_tab_line(str) str = preTwo + '\n\t' + tab + str + '\n' + tab + afterTwo str = self.normalize_line_endings(str) str = jsbeautifier.beautify(str, opts) self.view.replace(self.edit, sel, str) sublime.status_message(type + ' added')
def run(self, edit): settings = self.view.settings() # settings opts = jsbeautifier.default_options() opts.indent_char = " " if settings.get("translate_tabs_to_spaces") else "\t" opts.indent_size = int(settings.get("tab_size")) if opts.indent_char == " " else 1 opts.max_preserve_newlines = s.get("max_preserve_newlines") or 3 opts.preserve_newlines = s.get("preserve_newlines") or True opts.space_in_paren = s.get("space_in_paren") or False opts.jslint_happy = s.get("jslint_happy") or False opts.brace_style = s.get("brace_style") or "collapse" opts.keep_array_indentation = s.get("keep_array_indentation") or False opts.keep_function_indentation = s.get("keep_function_indentation") or False opts.indent_with_tabs = s.get("indent_with_tabs") or False opts.eval_code = s.get("eval_code") or False opts.unescape_strings = s.get("unescape_strings") or False opts.break_chained_methods = s.get("break_chained_methods") or False selection = self.view.sel()[0] formatSelection = False # formatting a selection/highlighted area if(len(selection) > 0): formatSelection = True if formatSelection: self.format_selection(edit, opts) else: self.format_whole_file(edit, opts)
def options(): op = jsbeautifier.default_options() fn = get_config_filename('JS Beautify') if not os.path.isfile(fn): return op with open(fn) as f: d = json.load(f) op.indent_size = d.get('indent_size', 4) op.indent_char = d.get('indent_char', ' ') op.indent_with_tabs = d.get('indent_with_tabs', False) op.preserve_newlines = d.get('preserve_newlines', True) op.max_preserve_newlines = d.get('max_preserve_newlines', 10) op.space_in_paren = d.get('space_in_paren', False) op.e4x = d.get('e4x', False) op.jslint_happy = d.get('jslint_happy', False) op.brace_style = d.get('brace_style', 'collapse') op.keep_array_indentation = d.get('keep_array_indentation', False) op.keep_function_indentation = d.get('keep_function_indentation', False) op.eval_code = d.get('eval_code', False) op.unescape_strings = d.get('unescape_strings', False) op.wrap_line_length = d.get('wrap_line_length', 0) op.break_chained_methods = d.get('break_chained_methods', False) return op
def get(self, request, link): try: data = DjangoPastebin.objects.get(link=link) except ObjectDoesNotExist: return render(request, template_name='error.html') if check_link(data.created, data.expiry): return render(request, template_name='error.html') expiry_in = data.created + datetime.timedelta( days=data.expiry) - timezone.now() expiry_str = "" if expiry_in.days > 0: expiry_str += str(expiry_in.days) + "Days, " if (expiry_in.seconds // (3600)) % 24 > 0: expiry_str += str((expiry_in.seconds // (3600)) % 24) + "Hours, " if (expiry_in.seconds // 60) % (60) > 0: expiry_str += str((expiry_in.seconds // (60)) % 60) + "Minutes" elif expiry_in.seconds > 0: expiry_str += str(expiry_in.seconds) + "Seconds" opts = jsbeautifier.default_options() opts.indent_size = 4 res = jsbeautifier.beautify(data.content, opts) return render(request, 'dpasteview.html', context={ 'data': res, 'img': data.image, 'video': data.video, 'expiry': expiry_str, 'form': DpasteForm, })
def normalJS(self): """ normal JS extract javascript <script> </script> and then normal it by jsbeautifier """ js_re = re.compile(r'<script[\s\S]*?</script>') js_list = js_re.findall(self.contents) js_split = js_re.split(self.contents) js_content = "" js_head = re.compile(r'<script.*?>') js_end = re.compile(r'</script>') opts = jsbeautifier.default_options() opts.eol = '\n' opts.preserve_newlines = 0 opts.keep_function_indentation = 1 self.contents = js_split[0] for i in xrange(len(js_list)): js = js_list[i] head = js_head.findall(js) end = js_end.findall(js) js = js_head.sub('', js) js = js_end.sub('', js) js = jsbeautifier.beautify(js, opts) js_content = head[0] + '\n' + js + '\n' + end[0] + '\n' self.contents += js_content + js_split[i + 1]
def beautified_js(input_js): if isinstance(input_js, bytes): input_js = str(input_js, 'utf-8') options = jsbeautifier.default_options() options.indent_size = 4 return jsbeautifier.beautify(input_js, options)
def get_message(self): opts = jsbeautifier.default_options() opts.indent_size = 2 return { "text": "```\n" + jsbeautifier.beautify(self.payload, opts) + "\n```" }
def dump2json(obj): if type(obj) is dict: obj2dict = obj else: obj2dict = obj.__dict__ options = jsbeautifier.default_options() options.indent_size = 4 return jsbeautifier.beautify(json.dumps(obj2dict), options)
def parseproblem(dic, outfile): opts = jsbeautifier.default_options() opts.indent_size = 2 res = jsbeautifier.beautify(json.dumps(dic), opts) print(res) outfile.write("Parsing Problem\n") tmphold = res + "\n" outfile.write(tmphold)
def doStr(self, json): self.append.init() self.read(json['body']) js = ''.join(str(x) for x in self.append.getStr()) opts = jsbeautifier.default_options() opts.space_in_paren = True opts.indent_size = 4 return jsbeautifier.beautify(js, opts)
def beautify(string: str) -> str: opts = jsbeautifier.default_options() opts.indent_size = 4 opts.preserve_newlines = False opts.indent_char = ' ' opts.space_before_conditional = True opts.end_with_newline = True return jsbeautifier.beautify(string, opts)
def style(self, code): opts = jsbeautifier.default_options() opts.end_with_newline = True opts.operator_position = "preserve-newline" opts.wrap_line_length = 132 opts.brace_style = "collapse,preserve-inline" opts.keep_array_indentation = True return jsbeautifier.beautify(code, opts)
def p_init(t): 'init : INT MAIN LPAREN RPAREN LBRACE start RBRACE' print("Parse success") #print(t[6]) opts = jsbeautifier.default_options() opts.brace_style = 'expand' with open("parse_tree.txt", "w+") as parse_tree: parse_tree.write(jsbeautifier.beautify(str(t[6]), opts=opts))
def prettystringjs(self, str): opts = jsbeautifier.default_options() opts.max_preserve_newlines = 1 res = jsbeautifier.beautify(str) return res
def main(): """MAIN FUNCTION""" my_moves = build_moves() opts = jsbeautifier.default_options() opts.indent_size = 4 with open('../output/moves.json', 'w') as moves: moves.write(jsbeautifier.beautify(json.dumps(my_moves))) with open('../output/moves_min.json', 'w') as moves_min: json.dump(my_moves, moves_min)
def main(): """Main Method""" opts = jsbeautifier.default_options() opts.indent_size = 4 my_pokedex = build_pokedex() with open("../output/pokedex.json", 'w') as pokedex: pokedex.write(jsbeautifier.beautify(json.dumps(my_pokedex))) with open("../output/pokedex_min.json", 'w') as pokedex_min: json.dump(my_pokedex, pokedex_min)
def main(): """MAIN FUNCTION""" my_items = build_items() opts = jsbeautifier.default_options() opts.indent_size = 4 with open('../output/items.json', 'w') as items: items.write(jsbeautifier.beautify(json.dumps(my_items))) with open('../output/items_min.json', 'w') as items_min: json.dump(my_items, items_min)
def blockChain(): opts = jsbeautifier.default_options() opts.indent_size = 2 response = { "chain": BlockChainMessage().dumps(coordinator.blockchain), "size": len(coordinator.blockchain.chain), } return jsonify(response), 200
def run(self, edit): opts = jsbeautifier.default_options(); opts.indent_char = "\t" opts.indent_size = 1 opts.max_preserve_newlines = 3 selection = self.view.sel()[0] replaceRegion = selection if len(selection) > 0 else sublime.Region(0, self.view.size()) res = jsbeautifier.beautify(self.view.substr(replaceRegion), opts) prePos = self.view.sel()[0] self.view.replace(edit, replaceRegion, res) self.view.show_at_center(prePos.begin())
def run(self, edit): settings = self.view.settings() # settings opts = jsbeautifier.default_options() opts.indent_char = " " if settings.get( "translate_tabs_to_spaces") else "\t" opts.indent_size = int( settings.get("tab_size")) if opts.indent_char == " " else 1 opts.max_preserve_newlines = s.get("max_preserve_newlines") or 3 opts.preserve_newlines = s.get("preserve_newlines") or True opts.jslint_happy = s.get("jslint_happy") or False opts.brace_style = s.get("brace_style") or "collapse" opts.keep_array_indentation = s.get("keep_array_indentation") or False opts.keep_function_indentation = s.get( "keep_function_indentation") or False opts.indent_with_tabs = s.get("indent_with_tabs") or False opts.eval_code = s.get("eval_code") or False opts.unescape_strings = s.get("unescape_strings") or False opts.break_chained_methods = s.get("break_chained_methods") or False selection = self.view.sel()[0] nwsOffset = self.prev_non_whitespace() # do formatting and replacement replaceRegion = None formatSelection = False # formatting a selection/highlighted area if (len(selection) > 0): formatSelection = True replaceRegion = selection # formatting the entire file else: replaceRegion = sublime.Region(0, self.view.size()) res = jsbeautifier.beautify(self.view.substr(replaceRegion), opts) if (not formatSelection and settings.get('ensure_newline_at_eof_on_save')): res = res + "\n" self.view.replace(edit, replaceRegion, res) # re-place cursor offset = self.get_nws_offset( nwsOffset, self.view.substr(sublime.Region(0, self.view.size()))) rc = self.view.rowcol(offset) pt = self.view.text_point(rc[0], rc[1]) sel = self.view.sel() sel.clear() self.view.sel().add(sublime.Region(pt)) self.view.show_at_center(pt)
def multiline_view(js): opts = jsbeautifier.default_options() opts.indent_size = 2 js = jsbeautifier.beautify(''.join(js), opts) multiLine = [] for line in js.split('\n'): if not line: continue multiLine.append(line) return multiLine
def run(self, edit): settings = sublime.load_settings(base_name) opts = jsbeautifier.default_options() opts.indent_char = settings.get("indent_char", None) opts.indent_size = settings.get("indent_size", None) opts.max_preserve_newlines = settings.get("max_preserve_newlines", None) selection = self.view.sel()[0] replaceRegion = selection if len(selection) > 0 else sublime.Region(0, self.view.size()) res = jsbeautifier.beautify(self.view.substr(replaceRegion), opts) prePos = self.view.sel()[0] self.view.replace(edit, replaceRegion, res) self.view.show_at_center(prePos.begin())
def setUpClass(cls): options = jsbeautifier.default_options() options.indent_size = 4 options.indent_char = " " options.preserve_newlines = True options.jslint_happy = False options.keep_array_indentation = False options.brace_style = "collapse" options.indent_level = 0 cls.options = options cls.wrapregex = re.compile("^(.+)$", re.MULTILINE)
def run(self, edit): settings = self.view.settings() opts = jsbeautifier.default_options() opts.indent_char = " " if settings.get("translate_tabs_to_spaces") else "\t" opts.indent_size = int(settings.get("tab_size")) if opts.indent_char == " " else 1 opts.max_preserve_newlines = 3 selection = self.view.sel()[0] replaceRegion = selection if len(selection) > 0 else sublime.Region(0, self.view.size()) res = jsbeautifier.beautify(self.view.substr(replaceRegion), opts) prePos = self.view.sel()[0] self.view.replace(edit, replaceRegion, res) self.view.show_at_center(prePos.begin())
def setUpClass(cls): options = jsbeautifier.default_options() options.indent_size = 4 options.indent_char = ' ' options.preserve_newlines = True options.jslint_happy = False options.keep_array_indentation = False options.brace_style = 'collapse' options.indent_level = 0 cls.options = options cls.wrapregex = re.compile('^(.+)$', re.MULTILINE)
def build_page(self, path): curr_dir = path + '/base' try: os.mkdir(curr_dir) except: pass opts = jsbeautifier.default_options() opts.indent_size = 2 opts.max_preserve_newlines = 30 with open(f"{curr_dir}/{self.name}-base.page.ts", 'w') as ts_file: s = jsbeautifier.beautify(self.build_ts(), opts) ts_file.write(s)
def combine(): final_json = [] PATH = sys.argv[2] for i in range(NUM_BATCHES): with open(PATH + ".%d.mcp" % i) as fp: tmp_list = json.load(fp) final_json += tmp_list import jsbeautifier opts = jsbeautifier.default_options() opts.indent_size = 2 with open(PATH + ".mcp", 'w') as fp: fp.write(jsbeautifier.beautify(json.dumps(final_json), opts))
def run(self, edit, indent_size, brace_style): selections = self.view.sel() for sel in selections: if sel.size() == 0 and len(selections) == 1: region = sublime.Region(0, self.view.size()) else: region = sel content = self.view.substr(region) opts = jsbeautifier.default_options() opts.brace_style = brace_style opts.indent_size = int(indent_size) res = jsbeautifier.beautify(content, opts) self.view.replace(edit, region, res)
def render_to_js_string(template: str, context: {}): output = render_to_string(template, context) options = jsbeautifier.default_options() opts_file = getattr(settings, 'EDITOR_CONFIG', '.editorconfig') options.brace_style = 'collapse,preserve-inline' try: jsbeautifier.set_file_editorconfig_opts(opts_file, options) except PathError: log("No editor config found at: {opts_file}") log("Using defaults.") return jsbeautifier.beautify(output, opts=options)
def jsonFormat(): import jsbeautifier buffer = vim.current.buffer json = "".join(buffer) opts = jsbeautifier.default_options() opts.indent_size = 2 opts.space_in_empty_paren = True res = jsbeautifier.beautify(json, opts).split('\n') buffer[0:len(res)] = res if vim.eval("&ft") == "": vim.command("set filetype=json")
def process(self, data): super(DeenPluginJsBeautifierFormatter, self).process(data) if not JSBEAUTIFIER: LOGGER.warning('jsbeautifier is not available') return opts = jsbeautifier.default_options() opts.unescape_strings = True try: data = jsbeautifier.beautify(data.decode(), opts).encode() except (UnicodeDecodeError, TypeError) as e: self.error = e return return data
def setUpClass(cls): options = jsbeautifier.default_options() options.indent_size = 4 options.indent_char = ' ' options.preserve_newlines = True options.jslint_happy = False options.keep_array_indentation = False options.brace_style = 'collapse' options.indent_level = 0 options.break_chained_methods = False cls.options = options cls.wrapregex = re.compile('^(.+)$', re.MULTILINE)
def un_zip(target_path): """ 解压缩目标压缩包 实现新需求,解压缩后相应的js文件做代码格式化 :return: """ logger.info("[Pre][Unzip] Upzip file {}...".format(target_path)) if not os.path.isfile(target_path): logger.warn("[Pre][Unzip] Target file {} is't exist...pass".format( target_path)) return False zip_file = zipfile.ZipFile(target_path) target_file_path = target_path + "_files/" if os.path.isdir(target_file_path): logger.debug("[Pre][Unzip] Target files {} is exist...continue".format( target_file_path)) return target_file_path else: os.mkdir(target_file_path) for names in zip_file.namelist(): zip_file.extract(names, target_file_path) # 对其中部分文件中为js的时候,将js代码格式化便于阅读 if names.endswith(".js"): file_path = os.path.join(target_file_path, names) file = codecs.open(file_path, 'r+', encoding='utf-8', errors='ignore') file_content = file.read() file.close() new_file = codecs.open(file_path, 'w+', encoding='utf-8', errors='ignore') opts = jsbeautifier.default_options() opts.indent_size = 2 new_file.write(jsbeautifier.beautify(file_content, opts)) new_file.close() zip_file.close() return target_file_path
def process(self, objects_list, add_rooms=True, exclude_self=False, outfilename='ai2thor_objects_to_objects'): with open(objects_list, 'r') as f: lines = f.read().split('\n') objects = [line for line in lines if not line == ''] objects = [ ' '.join(np.unique([o] + camel_case_split(o))) for o in objects ] objects_all = objects name = '' if add_rooms: objects_all += ['Kitchen', 'Bedroom', 'Bathroom', 'LivingRoom'] name += '_rooms' #print('Added rooms') if exclude_self: _objects_all = [ ' '.join(objects_all[:ii] + objects_all[ii + 1:]) for ii, oo in enumerate(objects) ] name += '_exclude_self' else: _objects_all = [ ' '.join(objects_all) for ii, oo in enumerate(objects) ] name += '_include_self' output_path = self.root / 'datasets/ai2thor' output_path.mkdir(exist_ok=True, parents=True) outfilename += name out_fn = str(output_path / f'{outfilename}_concepts.json') if Path(out_fn).is_file(): print('Grounding file already exists.') return res = self.match_mentioned_concepts(sents=objects, answers=_objects_all) res = self.prune_concepts(res) opts = jsbeautifier.default_options() opts.indent_size = 2 with open(out_fn, 'w') as fp: fp.write(jsbeautifier.beautify(json.dumps(res), opts)) print(f'Saved to {out_fn}')
def listingf(dirList): filesToBeProcessed = [] for paths,dirs,files in os.walk(dirList): for file in files: filesToBeProcessed.append(os.path.join(os.path.abspath(paths), file)) opts = default_options() opts.wrap_line_length = 80 for file in filesToBeProcessed: res = beautify_file(file,opts); fnew = open(file, "w") fnew.write(res)
def run(self, edit): settings = self.view.settings() # settings opts = jsbeautifier.default_options() opts.indent_char = " " #if settings.get("translate_tabs_to_spaces") else "\t" simply ignore setting opts.indent_size = int(settings.get("tab_size")) if opts.indent_char == " " else 1 opts.max_preserve_newlines = s.get("max_preserve_newlines") or 3 opts.preserve_newlines = s.get("preserve_newlines") or True opts.jslint_happy = s.get("jslint_happy") or False opts.brace_style = s.get("brace_style") or "collapse" opts.keep_array_indentation = s.get("keep_array_indentation") or False opts.keep_function_indentation = s.get("keep_function_indentation") or False opts.indent_with_tabs = s.get("indent_with_tabs") or False opts.eval_code = s.get("eval_code") or False opts.unescape_strings = s.get("unescape_strings") or False opts.break_chained_methods = s.get("break_chained_methods") or False selection = self.view.sel()[0] nwsOffset = self.prev_non_whitespace() # do formatting and replacement replaceRegion = None formatSelection = False # formatting a selection/highlighted area if(len(selection) > 0): formatSelection = True replaceRegion = selection # formatting the entire file else: replaceRegion = sublime.Region(0, self.view.size()) orig = self.view.substr(replaceRegion) res = jsbeautifier.beautify(orig, opts) _, err = merge_utils.merge_code(self.view, edit, orig, res) if err: sublime.error_message("JsFormat: Merge failure: '%s'" % err) # re-place cursor offset = self.get_nws_offset(nwsOffset, self.view.substr(sublime.Region(0, self.view.size()))) rc = self.view.rowcol(offset) pt = self.view.text_point(rc[0], rc[1]) sel = self.view.sel() sel.clear() self.view.sel().add(sublime.Region(pt)) self.view.show_at_center(pt)
def run(self, edit): settings = self.view.settings() # settings opts = jsbeautifier.default_options() opts.indent_char = " " if settings.get("translate_tabs_to_spaces") else "\t" opts.indent_size = int(settings.get("tab_size")) if opts.indent_char == " " else 1 opts.max_preserve_newlines = s.get("max_preserve_newlines") or 3 opts.preserve_newlines = s.get("preserve_newlines") or True opts.jslint_happy = s.get("jslint_happy") or False opts.brace_style = s.get("brace_style") or "collapse" opts.keep_array_indentation = s.get("keep_array_indentation") or False opts.keep_function_indentation = s.get("keep_function_indentation") or False opts.indent_with_tabs = s.get("indent_with_tabs") or False opts.eval_code = s.get("eval_code") or False opts.unescape_strings = s.get("unescape_strings") or False opts.break_chained_methods = s.get("break_chained_methods") or False selection = self.view.sel()[0] nwsOffset = self.prev_non_whitespace() # do formatting and replacement replaceRegion = None formatSelection = False # formatting a selection/highlighted area if(len(selection) > 0): formatSelection = True replaceRegion = selection # formatting the entire file else: replaceRegion = sublime.Region(0, self.view.size()) res = jsbeautifier.beautify(self.view.substr(replaceRegion), opts) if(not formatSelection and settings.get('ensure_newline_at_eof_on_save')): res = res + "\n" self.view.replace(edit, replaceRegion, res) # re-place cursor offset = self.get_nws_offset(nwsOffset, self.view.substr(sublime.Region(0, self.view.size()))) rc = self.view.rowcol(offset) pt = self.view.text_point(rc[0], rc[1]) sel = self.view.sel() sel.clear() self.view.sel().add(sublime.Region(pt)) self.view.show_at_center(pt)
def jssource_file(file_path, beautifty = True, encoding = "utf-8"): """ Runs the javascript source file verification/validation process as defined by a series of specifications. :type file_path: String :param file_path: The path to the file that is going to be changed according to the jssource operation. :type beautifier: bool :param beautifier: If the beautification process should be run for the provided file for verification. :type encoding: String :param encoding: The encoding that is going to be used as the default one for the decoding operation in the source file. """ try: import jsbeautifier except ImportError: jsbeautifier = None is_min = file_path.endswith("min.js") if jsbeautifier and beautifty and not is_min: # reads the complete set of contents from the original # file and then tries to decode such contents using the # default encoding (as expected by the processor) file = open(file_path, "rb") try: contents = file.read() finally: file.close() contents = contents.decode(encoding) # creates the dictionary that will contain the complete # set of options to be applied in the beautify operation # and then uses such values to run the beautification process opts = jsbeautifier.default_options() opts.wrap_line_length = 120 opts.end_with_newline = True opts.preserve_newlines = True opts.operator_position = "after_newline" opts.eol = "\r\n" result = jsbeautifier.beautify(contents, opts = opts) # determines if the result from the beautification process # is a bytes or unicode value and if it's not runs the encoding # and the re-writes the file with the new contents is_unicode = legacy.is_unicode(result) if is_unicode: result = result.encode(encoding) file = open(file_path, "wb") try: file.write(result) finally: file.close()
def __init__(self, extender, controller, editable): self._extender = extender self._editable = editable # create an instance of Burp's text editor, to display the javascript self._txtInput = extender._callbacks.createTextEditor() self._txtInput.setEditable(editable) # Set JS Beautifier opts opts = jsbeautifier.default_options() opts.indent_size = 2 # Store httpHeaders incase request is modified self._httpHeaders = None return
def format(self, s, view): vSettings = view.settings() # settings opts = jsbeautifier.default_options() opts.indent_char = " " if vSettings.get("translate_tabs_to_spaces") else "\t" opts.indent_size = int(vSettings.get("tab_size")) if opts.indent_char == " " else 1 opts.max_preserve_newlines = self.settings.get("max_preserve_newlines") or 3 opts.preserve_newlines = self.settings.get("preserve_newlines") or True opts.jslint_happy = self.settings.get("jslint_happy") or False opts.brace_style = self.settings.get("brace_style") or "collapse" opts.keep_array_indentation = self.settings.get("keep_array_indentation") or False opts.indent_level = self.settings.get("indent_level") or 0 return jsbeautifier.beautify(s, opts)
def run(self, edit): settings = self.view.settings() opts = jsbeautifier.default_options() opts.indent_char = " " if settings.get( "translate_tabs_to_spaces") else "\t" opts.indent_size = int( settings.get("tab_size")) if opts.indent_char == " " else 1 opts.max_preserve_newlines = 3 selection = self.view.sel()[0] replaceRegion = selection if len(selection) > 0 else sublime.Region( 0, self.view.size()) res = jsbeautifier.beautify(self.view.substr(replaceRegion), opts) prePos = self.view.sel()[0] self.view.replace(edit, replaceRegion, res) self.view.show_at_center(prePos.begin())
def run(self, edit): settings = self.view.settings() opts = jsbeautifier.default_options() for (k,v) in opts.__dict__.items(): if s.has(k): setattr(opts,k,s.get(k)) selection = self.view.sel()[0] formatSelection = False # formatting a selection/highlighted area if(len(selection) > 0): formatSelection = True if formatSelection: self.format_selection(edit, opts) else: self.format_whole_file(edit, opts)
def __init__(self, settings, type, view): self.settings = settings self.type = type self.view = view if self.type is "js": self.options = jsbeautifier.default_options() if self.type is "css": self.options = cssbeautifier.default_options() self.augment_options(settings) view_settings = self.view.settings() if view_settings.get("translate_tabs_to_spaces"): self.options.indent_char = "\t" if self.options.indent_char is " ": self.options.indent_size = int(view_settings.get("tab_size")) else: self.options.indent_size = 1
def get_js_formatted(self, codestr): opts = jsbeautifier.default_options() opts.eval_code = False # pull indentation from user prefs use_tab = self.user_settings.get('translate_tabs_to_spaces',False) if use_tab: opts.indent_with_tabs = True else: opts.indent_char = " " opts.indent_size = int(self.user_settings.get('tab_size',False)) # pull the rest of settings from our config for k,v in self.settings.get('jsformat', {}).items(): setattr(opts, k, v) return jsbeautifier.beautify(codestr, opts)
def run(self, edit): settings = self.view.settings() opts = jsbeautifier.default_options() opts.indent_char = " " if settings.get("translate_tabs_to_spaces") else "\t" opts.indent_size = int(settings.get("tab_size")) if opts.indent_char == " " else 1 opts.max_preserve_newlines = s.get("max_preserve_newlines") or 3 opts.preserve_newlines = s.get("preserve_newlines") or True opts.jslint_happy = s.get("jslint_happy") or False opts.brace_style = s.get("brace_style") or "collapse" opts.s = s.get("keep_array_indentation") or False opts.indent_level = s.get("indent_level") or 0 selection = self.view.sel()[0] replaceRegion = selection if len(selection) > 0 else sublime.Region(0, self.view.size()) res = jsbeautifier.beautify(self.view.substr(replaceRegion), opts) prePos = self.view.sel()[0] self.view.replace(edit, replaceRegion, res) self.view.show_at_center(prePos.begin())
def prettyjs(self,direc): # path = '/Users/matin/Documents/ReposCheckout/test/Angular.js' opts = jsbeautifier.default_options() opts.max_preserve_newlines = 1 for subdir, dirs, files in os.walk(direc): for file in files: path = os.path.join(subdir, file) if (path.endswith(".js")): res = jsbeautifier.beautify_file(path, opts) jsfile = open(path, 'wb') jsfile.write(res) jsfile.close() print path
def run(self, edit): settings = self.view.settings() # settings opts = jsbeautifier.default_options() opts.indent_char = " " if settings.get("translate_tabs_to_spaces") else "\t" opts.indent_size = int(settings.get("tab_size")) if opts.indent_char == " " else 1 opts = jsf_rc.augment_options(opts, s) if s.get("jsbeautifyrc_files") == True: opts = jsf_rc.augment_options_by_rc_files(opts, self.view) selection = self.view.sel()[0] # formatting a selection/highlighted area if len(selection) > 0: jsf.format_selection(self.view, edit, opts) else: jsf.format_whole_file(self.view, edit, opts)
def run(self, edit): settings = self.view.settings() opts = jsbeautifier.default_options() for (k,v) in opts.__dict__.items(): if s.has(k): setattr(opts,k,s.get(k)) # try to make it useful without any settings per project if s.get('use_original_indentation',False): setattr(opts,'indent_with_tabs',not settings.get('translate_tabs_to_spaces')) setattr(opts,'indent_size',int(settings.get('tab_size', 8))) selection = self.view.sel()[0] formatSelection = False # formatting a selection/highlighted area if(len(selection) > 0): formatSelection = True if formatSelection: self.format_selection(edit, opts) else: self.format_whole_file(edit, opts)
def process(self, view): replace_region = None pos = None sel = view.sel() if len(sel) == 1: region = sel[0] if region.empty(): # Get all document pos = region.begin() replace_region = view.line( Region(0, view.size())) else: replace_region = view.line(sel[0]) else: return content = view.substr(replace_region) opts = jsbeautifier.default_options() s = load_settings(settings.filename) opts.brace_style = s.get('brace_style', opts.brace_style) opts.eval_code = s.get('eval_code', opts.eval_code) opts.indent_char = s.get('indent_char', opts.indent_char) opts.indent_size = s.get('indent_size', opts.indent_size) opts.indent_with_tabs = s.get('indent_with_tabs', opts.indent_with_tabs) opts.jslint_happy = s.get('jslint_happy', opts.jslint_happy) opts.keep_array_indentation = s.get('keep_array_indentation', opts.keep_array_indentation) opts.keep_function_indentation = s.get('keep_function_indentation', opts.keep_function_indentation) opts.max_preserve_newlines = s.get('max_preserve_newlines', opts.max_preserve_newlines) opts.preserve_newlines = s.get('preserve_newlines', opts.preserve_newlines) opts.unescape_strings = s.get('unescape_strings', opts.unescape_strings) fixed = jsbeautifier.beautify(content, opts) if fixed != content: edit = view.begin_edit() view.replace(edit, replace_region, fixed) view.end_edit(edit) if pos: view.sel().clear() view.sel().add(pos) view.show_at_center(pos)
def options(): op = jsbeautifier.default_options() ini = format_proc.ini_filename() if os.path.isfile(ini): d = eval(open(ini).read()) op.indent_size = d["indent_size"] op.indent_char = d["indent_char"] op.indent_with_tabs = d["indent_with_tabs"] op.preserve_newlines = d["preserve_newlines"] op.max_preserve_newlines = d["max_preserve_newlines"] op.space_in_paren = d["space_in_paren"] op.e4x = d["e4x"] op.jslint_happy = d["jslint_happy"] op.brace_style = d["brace_style"] op.keep_array_indentation = d["keep_array_indentation"] op.keep_function_indentation = d["keep_function_indentation"] op.eval_code = d["eval_code"] op.unescape_strings = d["unescape_strings"] op.wrap_line_length = d["wrap_line_length"] op.break_chained_methods = d["break_chained_methods"] return op
def render(request, restrouter, ext_namespace, api_url): """ Get all Serializers from loaded REST API's, extract their attributes and convert to JS template. """ template = loader.get_template('output.html') context = Context() context['items'] = [] for item in restrouter.registry: url = item[0] serializer = item[1].serializer_class context['items'].append({ 'fields': extract(serializer), 'ordering': get_ordering_options(serializer), # Assumed that the class name without the Serializer part is the ExtJS # model and store name 'class': serializer.__name__.replace('Serializer', ''), # e.g. news-posts 'url': url, # e.g. Namespace.model.Class 'namespace': ext_namespace, # e.g. /api/ 'api_url': api_url }) jsbeautifier_options = jsbeautifier.default_options() jsbeautifier_options.indent_size = 4 jsbeautifier_options.brace_style = "expand" # A lot of newlines are created in the template so we want to remove them. jsbeautifier_options.preserve_newlines = False # Beautify the Django template javascript_template = jsbeautifier.beautify(template.render(context), jsbeautifier_options) # Return response as javascript so it can be loaded directly from HTML return HttpResponse(javascript_template, content_type="application/javascript")
def extractJS(code): return code JSCode = [] unescapedBytes = [] try: code = unescapeHTMLEntities(code) scriptElements = re.findall(reJSscript, code, re.DOTALL | re.IGNORECASE) if scriptElements != []: code = '' for scriptElement in scriptElements: code += scriptElement + '\n\n' opts = jsbeautifier.default_options() opts.escape_strings = True code = jsbeautifier.beautify(code, opts) JSCode.append(code) ret = "" for code in JSCode: ret += code + "\n" except: ret = "Error extracting code." return ret
def __call__(self, data, **metadata): opts = jsbeautifier.default_options() opts.indent_size = 2 data = data.decode("utf-8", "replace") res = jsbeautifier.beautify(data, opts) return "JavaScript", format_text(res)
#!/usr/bin/env python import sys from sys import stdout import re from jsbeautifier import beautify, default_options tests_passed = 0 opts = default_options() opts.indent_size = 4 opts.indent_char = ' ' opts.preserve_newlines = True opts.jslint_happy = False opts.keep_array_indentation = False opts.brace_style = 'collapse' def test_fragment(input, expectation = None): global opts if expectation == None: expectation = input res = beautify(input, opts) if res != expectation: print("""=== TEST FAILED === %s Input: ------