How to indent macros in this manner using a beautifier? - clang

I want my preprocessors to be indented in this manner:
int foo_func()
{
normal_code();
normal_code();
#ifdef FOO
# define aaa
# define bbb
code_that_only_foo();
code_that_only_foo();
#endif
normal_code_again();
normal_code_again();
}
I have tried clang-format, but it removes all spaces after # directive, and I failed to find any option to control that behavior. So, Could clang-format perform preprocessor indentation in that way?

If you cannot find a tool that does the job, write a tool that does:
#!/usr/bin/env python3
from sys import stdin
from string import whitespace
def main():
not_directive = whitespace + '#'
indentation = 0
for line in stdin:
stripped = line.lstrip()
if stripped.startswith('#'):
directive = stripped.lstrip(not_directive)
if directive.startswith('endif'):
indentation -= 1
print('#{}{}'.format(' ' * indentation, directive), end='')
if directive.startswith('if'):
indentation += 1
else:
print(line, end='')
if __name__ == '__main__':
main()
See it working online
It reads the source from the stdin, and writes changed source to the stdout.
You can easily redirect input and output with shell.
If you don't know Python3 and wish to understand it:
string.lstrip(chars) returns string with chars removed from it's beggining.
chars defaults to whitespace.
'test' * 0 => '', 'test' * 1 => 'test', 'test' * 3 => 'testtesttest'
'#{}{}'.format('textA', 'textB') => '#textAtextB'

Related

syntax highlighting autocmd is not working in neovim

I am new to vim and esp. in lua scripting. I want to create an autocmd such that all the jinja files will get yaml syntax highlighting.
local a = vim.api
a.nvim_create_autocmd( { "BufNewFile", "BufRead" }, {
pattern = { "*.j2" },
command = [[ lua(syntax = "html")]],
})
but this is not working. Could someone point the obvious.
DD.
I give you an Example on how i do Lua Syntaxhighlightning for my own *.luado files.
Before i have copied ( as super Q User: root.root ) /usr/share/nvim/runtime/syntax/lua.vim to /usr/share/nvim/runtime/syntax/luado.vim.
So i can change it independently from original lua.vim.
It is not necessary to change luado.vim for the Example below.
~/.config/nvim/lua/init.lua required by ~/.config/nvim/init.vim
( At First and off course before: syntax on )
--[[ Automatic Execution of Lua Oneliner if file extension *.luado
With Lua Syntaxhighlighting ]]
vim.api.nvim_create_autocmd({"BufEnter"},{
pattern = {"*.luado"},
command = "luado vim.api.nvim_command('setfiletype luado') load(line, 'koys_nvim_auto_luado')()"
})
Triggers at "BufEnter" and shows that "BufNewFile", "BufRead" not really needed.
( Every time before it is shown from Buffer ;-) )
Impression
Now lets change to next Buffer with :bn to test3.luado
And back with :bp to test2.luado (Output of set)
(test2.luado will be shown after ENTER/RETURN)

Print NSLocalizedString key instead of value

I need to print the keys of Localizable.strings in my App, instead of their values (for a debugging purpose). Is there a fast way to override the NSLocalizedString() method or redefine the macro, something like:
#define NSLocalizedString(key, comment) NSLocalizedString(key, key)
One option would be to export your app for localizations via Product Menu > Export Localizations within Xcode, then save the xcloc file to your Desktop.
After which you could use a python script to parse the inner xliff (xml) to find the file elements with original attributes which contain Localizable.strings and print the trans-unit's source element text within the body of them. Here's an example of a python script which should do it localizationKeys.py:
import sys
import os.path
from xml.etree import ElementTree as et
import argparse as ap
import re
if __name__ == '__main__':
parser = ap.ArgumentParser()
# filename argument ex: de.xliff
parser.add_argument('filename', help="filename of the xliff to find keys ex:de.xliff")
# verbose flag
parser.add_argument('-v', '--verbose', action='store_true', default=False, help='Show all the output')
args = parser.parse_args()
if (os.path.isfile(args.filename)):
tree = et.parse(args.filename)
root = tree.getroot()
match = re.match(r'\{.*\}', root.tag)
ns = match.group(0) if match else ''
files = root.findall(ns + 'file')
for file in files:
originalAttr = file.attrib['original']
# find all files which contain Localizable.strings
if originalAttr != None and 'Localizable.strings' in originalAttr:
if args.verbose == True:
print("----- Localizations for file: " + originalAttr + " -----")
# grab the body element
bodyElement = file.find(ns + 'body')
# get all the trans-units
transUnits = bodyElement.findall(ns + 'trans-unit')
for transUnit in transUnits:
# print all the source values (keys)
print(transUnit.find(ns + 'source').text)
else:
print("No file found with the specified name: " + args.filename)
Which you could then use as follows:
python3 localizationKeys.py en.xcloc/Localized\ Contents/en.xliff
Or if you'd prefer to print to to a file instead
python3 localizationKeys.py en.xcloc/Localized\ Contents/en.xliff > output.txt
This could almost definitely be more concise using xpath instead, but this is just what I came up with quickly.
Ok, this is how I obtained what I needed
// Overriding NSLocalizedString to print keys instead of values
#ifdef NSLocalizedString
#undef NSLocalizedString
#endif
#define NSLocalizedString(key, comment) key
In this way the App use the keys instead of the values

Pandoc Lua : how to add a markdown block around a header without losing the markdown syntax #

I am trying to add a div around a markdown header in a Lua filter, but the # in front of the title disappear in the output.
Header = function(el)
if el.level == 1 then
local content = el.content
local pre = pandoc.RawBlock('markdown','::: test')
local post = pandoc.RawBlock('markdown',':::')
table.insert(content,1,pre)
table.insert(content, post)
return content
else
return el
end
end
Input:
# Linux
## Support for Linux users
Create a shell script
Expected Output
::: test
# Linux
:::
## Support for Linux users
Create a shell script
The content field contains the heading text, but the heading itself is the el element that's not returned. Returning it together with the raw blocks should work though:
return {
pre, el, post
}
Or use a Div element:
function Header (el)
if h.level == 1 then
return pandoc.Div(el, {class = 'test'})
end
end

How to check if a file is a text file?

Does Perl6 have something like the Perl5 -T file test to tell if a file is a text file?
There's nothing built in, however there is a module Data::TextOrBinary that does that.
use Data::TextOrBinary;
say is-text('/bin/bash'.IO); # False
say is-text('/usr/share/dict/words'.IO); # True
That's a heuristic that has not been translated to Perl 6. You can simply read it in UTF8 (or ASCII) to do the same:
given slurp("read-utf8.p6", enc => 'utf8') -> $f {
say "UTF8";
}
(substitute read-utf8.p6 by the name of the file you want to check)
we can make use of the File::Type with the following code.
use strict;
use warnings;
use File::Type;
my $file = '/path/to/file.ext';
my $ft = File::Type->new();
my $file_type = $ft->mime_type($file);
if ( $file_type eq 'application/octet-stream' ) {
# possibly a text file
}
elsif ( $file_type eq 'application/zip' ) {
# file is a zip archive
}
Source: https://metacpan.org/pod/File::Type

Please explain this code from watchr

I'm learning to use watchr, a ruby gem that watches files and runs something if they change
watch( 'test/test_.*\.rb' ) {|md| system("ruby #{md[0]}") }
watch( 'lib/(.*)\.rb' ) {|md| system("ruby test/test_#{md[1]}.rb") }
Specifically, I don't understand what md[0] and md[1] are. I know that 'test/tests_.*\.rb' is a regular expression and it's retrieving a list of files. I also know that |md| represents filenames that match the regular expression. But I'm not sure what md[0] and md[1] would point to
I suspect that md is a MatchData instance, where [0] it the entire matched text and [1] is the first captured sub-expression), in this case the filename inside the lib directory, without the extension.
Ruby's regular expression operator (=~) returns an object that responds to :[]. The values 0 and 1 refer to the matched string and the first group (the part in the parentheses).
So for example if the strings being tested were:
"test/test_sample.rb"
"lib/sample.rb"
Then the first expression (/test/test_.*.rb/) would match "test/test_sample.rb", and the second expression (/lib/(.*).rb/) would match "sample". You can see this in the console:
> /test\/test_.*\.rb/ =~ "test/test_sample.rb"
# => 0
> $~[0]
# => "test/test_sample.rb"
> /lib\/(.*)\.rb/ =~ "lib/sample.rb"
# => 0
> $~[0]
# => "lib/sample.rb"
> $~[1]
# => "sample"
md stands for MatchData, which is the class of the object Ruby uses to return the result of the regex match.
zetetic's answer is correct; md is an instance of Rudy's MatchData class, which is the result of applying the regular expression on the modified file (see String#match).
The relevant line from the Watchr source code is at: https://github.com/mynyml/watchr/blob/17fa9bf80998483f9cf69a934bbcb726a0c389fa/lib/watchr/script.rb#L204

Resources